init: Air780EPM 官方 LuatOS 项目代码基线
- 来源: 合宙 LuatOS 官方仓库 air780epm 模块完整代码 - 路径: luatos/air780epm/module/Air780EPM/demo 含官方 demo(含 mqtt/mqtts/socket/uart 等) - 后续: 基于 demo 开发 UART<->MQTT 数据上报功能
This commit is contained in:
@@ -0,0 +1,171 @@
|
|||||||
|
# Prerequisites
|
||||||
|
*.d
|
||||||
|
*.luac
|
||||||
|
*.lnks
|
||||||
|
*.pdf
|
||||||
|
.vscode
|
||||||
|
vscode.code-workspace
|
||||||
|
.idea
|
||||||
|
|
||||||
|
# Object files
|
||||||
|
*.o
|
||||||
|
*.ko
|
||||||
|
*.obj
|
||||||
|
*.elf
|
||||||
|
|
||||||
|
# Linker output
|
||||||
|
*.ilk
|
||||||
|
*.map
|
||||||
|
*.exp
|
||||||
|
|
||||||
|
# Precompiled Headers
|
||||||
|
*.gch
|
||||||
|
*.pch
|
||||||
|
|
||||||
|
# Libraries
|
||||||
|
*.lib
|
||||||
|
*.a
|
||||||
|
*.la
|
||||||
|
*.lo
|
||||||
|
|
||||||
|
# Shared objects (inc. Windows DLLs)
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.so.*
|
||||||
|
*.dylib
|
||||||
|
|
||||||
|
# Executables
|
||||||
|
*.exe
|
||||||
|
*.out
|
||||||
|
*.app
|
||||||
|
*.i*86
|
||||||
|
*.x86_64
|
||||||
|
*.hex
|
||||||
|
|
||||||
|
# Debug files
|
||||||
|
*.dSYM/
|
||||||
|
*.su
|
||||||
|
*.idb
|
||||||
|
*.pdb
|
||||||
|
|
||||||
|
# Kernel Module Compile Results
|
||||||
|
#*.mod*
|
||||||
|
*.cmd
|
||||||
|
.tmp_versions/
|
||||||
|
modules.order
|
||||||
|
Module.symvers
|
||||||
|
Mkfile.old
|
||||||
|
dkms.conf
|
||||||
|
|
||||||
|
bsp/air302/FlashToolCLI/
|
||||||
|
bsp/air302/tmp/
|
||||||
|
bsp/air302/local*
|
||||||
|
bsp/air302/disk/
|
||||||
|
*.zip
|
||||||
|
tools/
|
||||||
|
testcase/
|
||||||
|
oldmodule/
|
||||||
|
olddemo/
|
||||||
|
script/
|
||||||
|
|
||||||
|
|
||||||
|
bsp/air640w/disk/
|
||||||
|
bsp/air640w/tmp/
|
||||||
|
bsp/air640w/local*
|
||||||
|
|
||||||
|
__pycache__
|
||||||
|
*.pyc
|
||||||
|
|
||||||
|
*.tlv
|
||||||
|
*.fs
|
||||||
|
bsp/air302/air302_sdk/**
|
||||||
|
/bsp/air724/sdk/out
|
||||||
|
/bsp/air724/sdk/hex
|
||||||
|
/bsp/air724/sdk/prebuilts/win32
|
||||||
|
|
||||||
|
*.cmake
|
||||||
|
*.xmake
|
||||||
|
|
||||||
|
debug.log
|
||||||
|
|
||||||
|
量产文件
|
||||||
|
|
||||||
|
CMakefiles
|
||||||
|
bsp/pc/build/
|
||||||
|
bsp/win32/build/
|
||||||
|
bsp/win32/release/
|
||||||
|
bsp/pico/build/
|
||||||
|
bsp/linux/build/
|
||||||
|
bsp/zephyr/
|
||||||
|
|
||||||
|
|
||||||
|
build/
|
||||||
|
*.bat
|
||||||
|
cmd.lnk
|
||||||
|
|
||||||
|
luat/demo/
|
||||||
|
tools/snippet.json
|
||||||
|
|
||||||
|
self_docs/
|
||||||
|
# cursor编程相关文件
|
||||||
|
.cursor/*
|
||||||
|
openspec/*
|
||||||
|
.codex
|
||||||
|
|
||||||
|
app_engine/
|
||||||
|
bsp/
|
||||||
|
luat/
|
||||||
|
|
||||||
|
# MCP server
|
||||||
|
.chroma_code/
|
||||||
|
components/
|
||||||
|
components/h264/test/test_h264
|
||||||
|
testcase/ctx.json
|
||||||
|
bsp/pc/pclogs/
|
||||||
|
bsp/pc/spidrv/
|
||||||
|
bsp/pc/fskv.bin
|
||||||
|
bsp/pc/otp.bin
|
||||||
|
|
||||||
|
.worktree
|
||||||
|
.worktrees/
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# Local AI / IDE tooling state (Mavis, Antigravity, OpenCode, etc.)
|
||||||
|
.mavis/
|
||||||
|
.antigravitycli/
|
||||||
|
.opencode/
|
||||||
|
/docs/superpowers
|
||||||
|
# Media artifacts accidentally saved at repo root by tooling
|
||||||
|
/matrix-media-*.mp4
|
||||||
|
/pgfs_flow.mp4
|
||||||
|
/pcconf/
|
||||||
|
/pgfs_video/
|
||||||
|
/bsp/air1601/artifacts/
|
||||||
|
|
||||||
|
# Local worktrees (not to be tracked from the main checkout)
|
||||||
|
# Note: .claude/skills/ is intentionally tracked so /luatos-hw-test ships with the repo.
|
||||||
|
/.claude/settings.local.json
|
||||||
|
/.claude/worktrees/
|
||||||
|
/.fleet-worktrees/
|
||||||
|
|
||||||
|
# PC BSP runtime artifacts (not to be tracked)
|
||||||
|
/bsp/pc/CrashDump_*.dmp
|
||||||
|
/bsp/pc/LastCoverageResults.log
|
||||||
|
/bsp/pc/test_output.txt
|
||||||
|
/bsp/pc/test_sqlite3_suite.db*
|
||||||
|
/bsp/pc/test_dir/
|
||||||
|
/bsp/pc/test_dir1/
|
||||||
|
/bsp/pc/test_fs_dir/
|
||||||
|
/bsp/pc/file2.txt
|
||||||
|
/bsp/pc/mount_test.txt
|
||||||
|
/bsp/pc/os_test_*.txt
|
||||||
|
/bsp/pc/test_io.txt
|
||||||
|
|
||||||
|
*.dmp
|
||||||
|
testresult/
|
||||||
|
app_store/
|
||||||
|
*.bin
|
||||||
|
single_app.json
|
||||||
|
.qoder/
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
# AGENTS.md - LuatOS AI Agent Configuration
|
||||||
|
|
||||||
|
> **AGENTS.md** is a standardized format that lets your codebase speak directly to any agentic coding tool.
|
||||||
|
> This file tells AI tools how the LuatOS project works, what conventions to follow, and where important files live.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
**LuatOS** is an embedded Lua operating system based on Lua 5.3 VM, developed by openLuat (合宙). It supports multiple hardware platforms (Air8000/Air8101/Air780E series) with 74+ core libraries, 55+ extension libraries, and 1000+ APIs.
|
||||||
|
|
||||||
|
### Tech Stack
|
||||||
|
- **Core Language**: Lua 5.3.5 (optimized by openLuat)
|
||||||
|
- **Build System**: xmake
|
||||||
|
- **Target Platforms**: Embedded MCU (ARM/RISC-V), PC Simulator (Windows/Linux/macOS)
|
||||||
|
- **License**: MIT License
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Agent Persona
|
||||||
|
|
||||||
|
You are a **LuatOS Development Expert** with deep knowledge of:
|
||||||
|
- Embedded systems programming in C and Lua
|
||||||
|
- Lua 5.3 VM internals and C API
|
||||||
|
- RTOS concepts (task scheduling, event loops, concurrency)
|
||||||
|
- Hardware abstraction layers (GPIO, UART, SPI, I2C, ADC, PWM)
|
||||||
|
- Network protocols (TCP/UDP, HTTP, MQTT, WebSocket, CoAP)
|
||||||
|
- GUI frameworks (LVGL, embedded displays)
|
||||||
|
- Build systems (xmake, cross-compilation)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Key Directories
|
||||||
|
|
||||||
|
```
|
||||||
|
LuatOS/
|
||||||
|
├── lua/ # Lua VM source (based on 5.3.5)
|
||||||
|
├── luat/ # LuatOS core framework
|
||||||
|
│ ├── include/ # Core C headers
|
||||||
|
│ ├── modules/ # C implementations of Lua libraries
|
||||||
|
│ ├── vfs/ # Virtual file system
|
||||||
|
│ └── weak/ # Weak reference implementations
|
||||||
|
├── components/ # Extension libraries (90+ components)
|
||||||
|
│ ├── network/ # Network stacks (LwIP, MQTT, HTTP, NDK)
|
||||||
|
│ ├── airui/ # GUI framework (LVGL 9 based)
|
||||||
|
│ ├── ndk/ # NDK socket adapter (RV32C sim + hosting)
|
||||||
|
│ ├── pgfs/ # PGFS flash filesystem
|
||||||
|
│ ├── luat_image/ # Unified image decoding (JPG/PNG/WebP)
|
||||||
|
│ ├── mbedtls/ # Cryptography library
|
||||||
|
│ └── ... # Bluetooth, audio, sensors, etc.
|
||||||
|
├── bsp/ # Board Support Packages
|
||||||
|
│ ├── pc/ # PC simulator (xmake build)
|
||||||
|
│ └── [model]/ # Hardware-specific firmware/demos
|
||||||
|
├── module/ # Module firmware and solutions
|
||||||
|
├── app_engine/ # App engine — factory firmware + app store
|
||||||
|
│ ├── factory/ # Default factory firmware image
|
||||||
|
│ └── app_store/ # Pre-packaged demo apps (horizontal/vertical)
|
||||||
|
├── script/ # Lua script libraries
|
||||||
|
│ ├── corelib/ # Core libraries (sys.lua, etc.)
|
||||||
|
│ ├── libs/ # External driver libraries
|
||||||
|
│ └── turnkey/ # Ready-to-use project templates
|
||||||
|
├── testcase/ # Test suites (utest + feature tests)
|
||||||
|
├── tools/ # Auxiliary tools
|
||||||
|
├── docs/ # Documentation (known issues, RFA, VFS)
|
||||||
|
└── bsp/pc/build/ # PC simulator build output
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Component AGENTS.md Standard
|
||||||
|
|
||||||
|
Several sub-directories carry their own `AGENTS.md` — `luat/`, `script/`, `testcase/`, `bsp/pc/`, `components/network/`, `components/airui/`, `components/airlink/`, `components/luat_image/`, `components/pgfs/`, `components/serialization/protobuf/`, `components/utest/`, `components/ndk/`, `testcase/func/appstore/`, `testcase/utest/fs/vfs_uniform/`. Use the following rule to decide whether a new component needs one.
|
||||||
|
|
||||||
|
**Create a component-level `AGENTS.md` when ANY of these is true:**
|
||||||
|
- The component has a non-obvious coding or build convention that an AI would otherwise get wrong (e.g. `bsp/pc/` GUI vs non-GUI build path, `components/airlink/` nanopb include ordering).
|
||||||
|
- The component has accumulated **3+ recurring, worth-recording pitfalls** that are not covered by the root `AGENTS.md` (e.g. `components/serialization/protobuf/` ARM stack-slot debugging).
|
||||||
|
- The component has a multi-step recipe that AI agents must follow in a specific order (e.g. `components/ndk/` regression chain).
|
||||||
|
|
||||||
|
**Do NOT create a component-level `AGENTS.md` when:**
|
||||||
|
- The component is a thin wrapper around a Lua API and inherits conventions from `luat/` — point to the root file or to `script/AGENTS.md` instead.
|
||||||
|
- The content would just duplicate the root `AGENTS.md` Build & Test Commands section.
|
||||||
|
- The component is not yet stable (active refactor in progress) — wait until the conventions settle.
|
||||||
|
|
||||||
|
**Style requirements for any new `AGENTS.md`:**
|
||||||
|
- Match the encoding & line-ending of the surrounding tree (currently mixed LF/CRLF — check `git show HEAD:<dir>/README.md` first).
|
||||||
|
- Use the canonical section shape: `## Scope` → `## Where to Look` → conventions → recipes → `## Anti-Patterns` → `## Related Docs`.
|
||||||
|
- Keep it a **single point of authority**: if the root `AGENTS.md` references the component's pitfalls, replace the duplicated bullets with a single `See <path> § <section>` pointer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Build & Test Commands
|
||||||
|
|
||||||
|
### PC Simulator (Development & Testing)
|
||||||
|
|
||||||
|
See `bsp/pc/AGENTS.md` for detailed PC Simulator build and development instructions.
|
||||||
|
|
||||||
|
**Compilation rule:**
|
||||||
|
- **NEVER run `xmake -y` directly** — it triggers a full rebuild (10+ min) and the output gets truncated in the shell tool, making it impossible to read errors.
|
||||||
|
- **ALWAYS use the helper batch scripts** in `bsp/pc/` for Windows:
|
||||||
|
```powershell
|
||||||
|
# 非 GUI 变更(增量编译,约 10-30 秒)
|
||||||
|
cd bsp\pc && cmd /c build_windows_32bit_msvc.bat
|
||||||
|
# 或 64 位
|
||||||
|
cd bsp\pc && cmd /c build_windows_64bit_msvc.bat
|
||||||
|
```
|
||||||
|
- The scripts call `build_with_summary.ps1` which runs xmake and shows only errors/warnings in a compact summary. Full log is written to `bsp/pc/build/logs/`.
|
||||||
|
- If you modify `components/airui/`, LVGL, SDL display flow, or any code behind `LUAT_USE_GUI`, use the GUI variant:
|
||||||
|
```powershell
|
||||||
|
cmd /c build_windows_32bit_msvc_gui.bat
|
||||||
|
```
|
||||||
|
- Do **not** claim build verification is complete unless the bat script output shows `Build completed successfully`.
|
||||||
|
|
||||||
|
### Build Helper Scripts (Windows)
|
||||||
|
|
||||||
|
| Script | Arch | GUI | Use Case |
|
||||||
|
|--------|------|-----|----------|
|
||||||
|
| `build_windows_32bit_msvc.bat` | x86 | No | 日常非 GUI 增量编译(推荐) |
|
||||||
|
| `build_windows_64bit_msvc.bat` | x64 | No | 64 位测试 |
|
||||||
|
| `build_windows_32bit_msvc_gui.bat` | x86 | Yes | AirUI/LVGL/SDL 变更验证 |
|
||||||
|
| `build_windows_64bit_msvc_gui.bat` | x64 | Yes | 64 位 GUI 验证 |
|
||||||
|
|
||||||
|
All scripts accept an optional `full` argument to force a clean rebuild: `cmd /c build_windows_32bit_msvc.bat full`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run a test case (pass exactly two script directories)
|
||||||
|
build/out/luatos-lua.exe ../../testcase/common/scripts/ ../../testcase/<feature>/<feature>_basic/scripts/
|
||||||
|
|
||||||
|
# Example
|
||||||
|
build/out/luatos-lua.exe ../../testcase/common/scripts/ ../../testcase/unit/tools/mreport/scripts/
|
||||||
|
```
|
||||||
|
|
||||||
|
### Creating New Tests
|
||||||
|
|
||||||
|
1. Create directory: `testcase/<feature>/<feature>_basic/scripts/`
|
||||||
|
2. Create `metas.json` with test metadata
|
||||||
|
3. Create `main.lua`:
|
||||||
|
```lua
|
||||||
|
PROJECT = "testcase_name"
|
||||||
|
VERSION = "1.0.0"
|
||||||
|
require("testrunner")
|
||||||
|
sys.taskInit(function()
|
||||||
|
-- test logic
|
||||||
|
end)
|
||||||
|
sys.run()
|
||||||
|
```
|
||||||
|
4. Create `<feature>_test.lua` with functions starting with `test_`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Coding Conventions
|
||||||
|
|
||||||
|
### C Code (Core & Modules)
|
||||||
|
|
||||||
|
**Naming:**
|
||||||
|
- Core APIs use `luat_` prefix: `luat_gpio_set`, `luat_uart_open`, `luat_spi_transfer`
|
||||||
|
- Module files: `luat_lib_<module>.c` (e.g., `luat_lib_gpio.c`, `luat_lib_uart.c`)
|
||||||
|
- Headers located in `luat/include/`
|
||||||
|
|
||||||
|
**Feature Flags:**
|
||||||
|
- Use `LUAT_USE_<FEATURE>` macros to control compilation
|
||||||
|
- Example: `LUAT_USE_GUI` enables GUI support (LVGL/SDL2)
|
||||||
|
|
||||||
|
**Code Style:**
|
||||||
|
- Follow existing patterns in `luat/modules/`
|
||||||
|
- Use `luat_` prefix for all public APIs
|
||||||
|
- Document functions with Doxygen-style comments
|
||||||
|
|
||||||
|
**Quality & Safety (project-wide C conventions):**
|
||||||
|
- **Address arithmetic**: use `uint64_t` as an intermediate when computing differences of two `uint32_t` addresses/offsets — direct subtraction on `uint32_t` silently wraps at zero. Cast each operand to `uint64_t` *before* the subtraction.
|
||||||
|
- **Atomic counters**: any counter touched by more than one thread (e.g. `ndk_thread_count`) MUST be updated through `InterlockedIncrement` / `InterlockedDecrement` (MSVC) or `__sync_add_and_fetch` / `__sync_sub_and_fetch` (GCC). Plain `++` / `--` on a shared counter is a data race.
|
||||||
|
- **Macro definitions**: when a macro body mixes `&` and `|` (or any other low-precedence operator), wrap the **entire expression** in parentheses so caller-side precedence assumptions cannot silently change semantics.
|
||||||
|
- **Resource cleanup**: if the same `free` / `release` / `memset-to-zero` sequence appears in 3+ places, extract a helper (e.g. `ndk_free_fields()` in `components/ndk/src/luat_ndk.c`) rather than duplicating the pattern.
|
||||||
|
|
||||||
|
### Lua Code (Scripts & Applications)
|
||||||
|
|
||||||
|
**Task Management:**
|
||||||
|
```lua
|
||||||
|
-- Use sys.taskInit for concurrency
|
||||||
|
sys.taskInit(function()
|
||||||
|
-- long-running task
|
||||||
|
end)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Entry Point:**
|
||||||
|
```lua
|
||||||
|
-- Scripts must end with sys.run()
|
||||||
|
sys.run()
|
||||||
|
```
|
||||||
|
|
||||||
|
**Logging:**
|
||||||
|
```lua
|
||||||
|
log.info(tag, message) -- Info level
|
||||||
|
log.warn(tag, message) -- Warning level
|
||||||
|
log.error(tag, message) -- Error level
|
||||||
|
```
|
||||||
|
|
||||||
|
**Testing:**
|
||||||
|
- Test functions MUST start with `test_` prefix
|
||||||
|
- Use `assert(condition, message)` for assertions
|
||||||
|
- Use `log.info()` for test output
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Overview
|
||||||
|
|
||||||
|
### Layer 1: Lua VM (`lua/`)
|
||||||
|
- Based on Lua 5.3.5 official source
|
||||||
|
- Optimized by openLuat for performance and memory
|
||||||
|
|
||||||
|
### Layer 2: Core Framework (`luat/`)
|
||||||
|
- **Task Scheduling**: Coroutine management, event loop
|
||||||
|
- **VFS**: Unified file interface (FATFS/LFS support)
|
||||||
|
- **HAL**: Hardware abstraction (GPIO/UART/SPI/I2C/etc.)
|
||||||
|
|
||||||
|
### Layer 3: Components (`components/`)
|
||||||
|
- **Network**: LwIP, MQTT, HTTP, WebSocket, CoAP
|
||||||
|
- **GUI**: LVGL 9 + AirUI, U8G2
|
||||||
|
- **Security**: mbedtls, crypto, xxtea
|
||||||
|
- **Storage**: FATFS, LFS, SFUD, FlashDB
|
||||||
|
- **Multimedia**: Audio codecs (OPUS/AMR), images (JPEG/PNG)
|
||||||
|
|
||||||
|
### Layer 4: Script Layer (`script/`)
|
||||||
|
- **corelib**: System core libraries (sys.lua task system)
|
||||||
|
- **libs**: Standardized peripheral drivers
|
||||||
|
- **turnkey**: Complete project templates
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Agent Boundaries
|
||||||
|
|
||||||
|
### ✅ Allowed Actions
|
||||||
|
|
||||||
|
- Read and analyze any source file in the repository
|
||||||
|
- Modify C code in `luat/modules/` following existing patterns
|
||||||
|
- Modify Lua scripts in `script/` and `testcase/`
|
||||||
|
- Update configuration files (`.github/`, `xmake.lua`, etc.)
|
||||||
|
- Add new test cases following the established structure
|
||||||
|
- Fix bugs and improve performance
|
||||||
|
|
||||||
|
### ❌ Forbidden Actions
|
||||||
|
|
||||||
|
- **NEVER** commit code without explicit user confirmation
|
||||||
|
- **NEVER** delete configuration files (`.env`, `xmake.lua`, `.gitignore`, etc.)
|
||||||
|
- **NEVER** suppress type errors or warnings with workarounds
|
||||||
|
- **NEVER** remove existing tests to make build pass
|
||||||
|
- **NEVER** modify code you haven't read first
|
||||||
|
- **NEVER** make large refactors without discussing with user first
|
||||||
|
|
||||||
|
### ⚠️ Security Alerts
|
||||||
|
|
||||||
|
If you discover any of the following, STOP and report immediately:
|
||||||
|
- Hardcoded credentials or API keys
|
||||||
|
- Buffer overflow vulnerabilities
|
||||||
|
- Unvalidated user input in security-critical code
|
||||||
|
- Insecure cryptographic implementations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tool Selection Guide
|
||||||
|
|
||||||
|
### When to Use Specialized Agents
|
||||||
|
|
||||||
|
| Task Type | Agent | Description |
|
||||||
|
|-----------|-------|-------------|
|
||||||
|
| Find existing code patterns | `explore` | Search codebase structure, patterns, and styles |
|
||||||
|
| Look up library documentation | `librarian` | Search external docs, official APIs, OSS examples |
|
||||||
|
| Complex architecture decisions | `oracle` | Multi-system tradeoffs, unfamiliar patterns |
|
||||||
|
| Complex scope clarification | `metis` | Ambiguous requirements, pre-planning analysis |
|
||||||
|
| Review work plans | `momus` | Evaluate plans for clarity and completeness |
|
||||||
|
|
||||||
|
### Background Execution
|
||||||
|
|
||||||
|
Always run exploration and research tasks in background mode for parallel execution:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
task(subagent_type="explore", run_in_background=true, ...)
|
||||||
|
task(subagent_type="librarian", run_in_background=true, ...)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Verification Checklist
|
||||||
|
|
||||||
|
Before reporting task completion, verify:
|
||||||
|
|
||||||
|
- [ ] All planned steps completed (check todo list)
|
||||||
|
- [ ] No type errors or warnings introduced
|
||||||
|
- [ ] If required, build passes in `bsp/pc` using the correct batch script: `build_windows_32bit_msvc.bat` for non-GUI changes, `build_windows_32bit_msvc_gui.bat` for AirUI/LVGL/SDL changes (never run `xmake -y` directly)
|
||||||
|
- [ ] Tests pass (if applicable)
|
||||||
|
- [ ] Code follows existing patterns
|
||||||
|
- [ ] No hardcoded credentials or security issues
|
||||||
|
- [ ] User's original request fully addressed
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Key Files Reference
|
||||||
|
|
||||||
|
| File | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `bsp/pc/xmake.lua` | PC simulator build configuration |
|
||||||
|
| `bsp/pc/build_with_summary.ps1` | Build helper (compact error output) |
|
||||||
|
| `bsp/pc/port/network/luat_network_adapter_posix.c` | PC network adapter |
|
||||||
|
| `luat/include/luat.h` | Core header file |
|
||||||
|
| `luat/include/luat_conf_bsp.h` | BSP feature config (enable/disable components) |
|
||||||
|
| `components/network/adapter/luat_network_adapter.c` | Network framework state machine |
|
||||||
|
| `components/network/adapter/luat_network_adapter.h` | Network adapter API definitions |
|
||||||
|
| `components/network/adapter/luat_lib_socket.c` | Socket Lua bindings |
|
||||||
|
| `components/ndk/src/luat_ndk.c` | NDK socket adapter |
|
||||||
|
| `components/pgfs/src/pgfs.c` | PGFS flash filesystem core |
|
||||||
|
| `components/luat_image/luat_image.c` | Image decoder dispatch table |
|
||||||
|
| `script/corelib/sys.lua` | Lua task system core |
|
||||||
|
| `testcase/common/scripts/testrunner.lua` | Test framework |
|
||||||
|
| `module/<model>/core` | Module firmware description |
|
||||||
|
| `app_engine/factory/main.lua` | Factory firmware entry point |
|
||||||
|
| `tools/sys_pub.py` | 扫描 `@sys_pub` 注释块生成 wiki 的 sys_pub.md(只扫 luat/lua/components/bsp/rtt) |
|
||||||
|
| `tools/sys_pub_audit.py` | 审计工具:找出 C 层 `sys_pub` 已发布但未写 `@sys_pub` 文档的系统消息 |
|
||||||
|
| `.github/workflows/windows-build.yml` | CI configuration (Windows matrix build) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Debugging Lessons & Common Pitfalls
|
||||||
|
|
||||||
|
### Memory Initialization
|
||||||
|
- `lua_newuserdata` does **NOT** zero memory — always `memset` the returned pointer
|
||||||
|
- `malloc` / `luat_heap_malloc` also do not zero — use `memset` or `calloc`
|
||||||
|
- Uninitialized pointers (e.g. `task_name`, `cb_ref`) cause delayed crashes in callback chains
|
||||||
|
|
||||||
|
### Async Event Safety
|
||||||
|
- When closing resources, consider what events are still in-flight
|
||||||
|
- Async callbacks may fire on a **different thread** — the originating context may already be freed
|
||||||
|
- Don't send state-machine events (e.g. `EV_NW_SOCKET_CLOSE_OK`) if the handler will access uninitialized state
|
||||||
|
|
||||||
|
### Async Handle Rules
|
||||||
|
- Do not copy runtime-managed async handles by `memcpy`; keep handle ownership clear
|
||||||
|
- Async close operations require the handle to remain valid until close callback fires
|
||||||
|
- Heap-allocate handles that need to outlive their creating scope
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019-2026 openLuat & AirM2M
|
||||||
|
|
||||||
|
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.
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
|
||||||
|
[](https://gitee.com/openLuat/LuatOS/stargazers)
|
||||||
|
[](https://gitee.com/openLuat/LuatOS/members)
|
||||||
|
[](/LICENSE)
|
||||||
|
|
||||||
|
LuatOS,基于强大的Lua引擎架构设计,Lua脚本开发,快速实现业务逻辑;
|
||||||
|
|
||||||
|
LuatOS,在合宙历史上经历了两个阶段,一个是LuatOS-Air,一个是LuatOS-SoC,也就是现在的LuatOS;
|
||||||
|
|
||||||
|
LuatOS-Air,典型硬件为Air724UG,为合宙上一代的产品;
|
||||||
|
|
||||||
|
LuatOS,也就是曾经命名过的LuatOS-SoC,是合宙现在主推的开发方式,所支持的硬件如下:
|
||||||
|
|
||||||
|
Air8000系列,包括Air8000/Air8000W/Air8000G/Air8000T/Air8000A/Air8000D等;
|
||||||
|
|
||||||
|
Air8101系列,包括Air8101/Air8101A等;
|
||||||
|
|
||||||
|
Air780Exx系列,包括Air780EPM/Air780EHM/Air780EHV/Air780EGH等;
|
||||||
|
|
||||||
|
**LuatOS,现已支持74个核心库,55个扩展库,1000余个API,100多个基于场景的demo,让你开发智能设备像做PPT一样轻松。**
|
||||||
|
|
||||||
|
本仓库包含如下文件夹:
|
||||||
|
|
||||||
|
1. `.github文件夹`,Github Action 配置文件, 用于自动化构建和测试
|
||||||
|
2. `components 组件库`,,LuatOS在Lua基础上扩展的一系列库的源码
|
||||||
|
3. `lua文件夹`,Lua虚拟机5.3系列的源码, 经过合宙优化和测试
|
||||||
|
4. `luat文件夹`,LuatOS核心框架代码
|
||||||
|
5. `module文件夹`,合宙模组和工业引擎主流型号的固件、demo、project参考代码等
|
||||||
|
6. `script文件夹`,LuatOS扩展库
|
||||||
|
7. `tools文件夹`,辅助工具
|
||||||
|
8. `.gitignore` Git的文件忽略配置文件
|
||||||
|
|
||||||
|
|
||||||
|
## 快速入门
|
||||||
|
|
||||||
|
1. 使用或购买支持的开发板
|
||||||
|
* [合宙官方淘宝店](https://luat.taobao.com)
|
||||||
|
* [PC - 无需开发板的模拟器](bsp/pc/)
|
||||||
|
2. 掌握[刷机](https://docs.openluat.com/air780epm/common/Luatools/)
|
||||||
|
3. 尝试[学习LuatOS](https://docs.openluat.com/osapi/luatos_framework/), 浏览[API](https://docs.openluat.com/osapi/), [30分钟入门lua语法(视频)](https://docs.openluat.com/air780epm/product/video/)
|
||||||
|
4. 愉快地写业务代码
|
||||||
|
|
||||||
|
## 资料大全
|
||||||
|
|
||||||
|
* [docs@luatos](https://docs.openluat.com/)
|
||||||
|
* 跨平台命令行工具 [luatos-cli](https://gitee.com/openLuat/luatos-cli)
|
||||||
|
|
||||||
|
|
||||||
|
## 授权协议
|
||||||
|
|
||||||
|
[MIT License](LICENSE)
|
||||||
|
|
||||||
|
```lua
|
||||||
|
print("感谢您使用LuatOS ^_^")
|
||||||
|
print("Thank you for using LuatOS ^_^")
|
||||||
|
```
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
# ARP 1000ms 定时器低功耗化改造 / netdrv.arpSleep API
|
||||||
|
|
||||||
|
> 适用:基于 `net_lwip2` adapter + `netdrv` 框架的 BSP(Air8000A/U/N/AB/W/D/DB/T 等),目标是消除 `pm.power(pm.WORK_MODE, 1)` 进入 Slp1 后由 ARP 1000ms 定时器(`etharp_tmr`)带来的周期性唤醒功耗。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 背景与问题
|
||||||
|
|
||||||
|
### 1.1 现象
|
||||||
|
|
||||||
|
Air8000A 系列模组进入低功耗模式后,预期功耗 ~40-70uA,但实测有持续 1Hz 的电流脉冲。串口/EPAT 日志可观察到:
|
||||||
|
|
||||||
|
```
|
||||||
|
03:0048:07:06464 D/net arp_pm: TICK etharp_tmr
|
||||||
|
03:0148:07:05760 D/net arp_pm: TICK etharp_tmr
|
||||||
|
03:0248:07:05440 D/net arp_pm: TICK etharp_tmr
|
||||||
|
... 每秒一次, 无限持续 ...
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 根因
|
||||||
|
|
||||||
|
`net_lwip2.c` 为每个 netif 维护了一个 1000ms 周期的 ARP timer(`prvlwip.arp_timer`),作用是周期性扫描 ARP 表 + 重传 ARP 请求。当编译选项是 `LUAT_NETDRV_ARP_TIMER_ALWAYS_ON` 时它永久 1Hz 跑;当编译为 on-demand 时它本应在「不需要 ARP」时停止,但:
|
||||||
|
|
||||||
|
- WIFI/CH390/AP 任一 netif 处于 `link_up` 且 `gw_mac` 尚未解析时,定时器都会启动;
|
||||||
|
- 进入低功耗前没有任何代码主动告诉 net_lwip2「我要睡了,把定时器停掉」。
|
||||||
|
|
||||||
|
### 1.3 多次尝试的失败路径
|
||||||
|
|
||||||
|
| 方案 | 结果 |
|
||||||
|
|---|---|
|
||||||
|
| 在 `luat_lib_pm.c` 的 `l_pm_power_ctrl` 加 hook:`id==LUAT_PM_POWER_WORK_MODE && onoff!=0` 时调用 `net_lwip2_arp_timer_sleep_prepare()` | 失败。Air8000 的 `pm.power(WORK_MODE,1)` 编译宏走 `LUAT_USE_DRV_PM` 分支,最初 hook 放在 `#else` 内,从未生效。 |
|
||||||
|
| 把 hook 移到 `#ifdef LUAT_USE_DRV_PM` **外** | 失败。Air8000 实际把 `pm.power(WORK_MODE,1)` 重定向到 `pm.request(Slp1)` 路径(日志只看到 `I/pm request mode=Slp1`,看不到我们注册的 `arp_pm: pm.power(...)` 行),完全绕过 `l_pm_power_ctrl`。 |
|
||||||
|
| 同时在 `l_pm_request` 加 hook | 部分固件构建仍未触发。该路径在 SoC 内部由 drv_pm 框架管理,钩子位置和编译条件因平台而异,不可靠。 |
|
||||||
|
| 用 `netdrv.ctrl(LWIP_ETH, CTRL_UPDOWN, 0)` 让 `LINK_DOWN` 事件触发 `apply_stop` | 在 ETH 场景下有效,但 STA/AP 场景下 WIFI 芯片会被直接掉电,netif 不一定经过标准 LINK_DOWN 事件。 |
|
||||||
|
|
||||||
|
### 1.4 最终选择
|
||||||
|
|
||||||
|
**抛弃所有 pm 钩子,改用一个显式的 Lua API:`netdrv.arpSleep()` / `netdrv.arpResume()`。** 由低功耗脚本在 `pm.power(WORK_MODE,1)` 之前主动调用,直接把 `EV_LWIP_ARP_TIMER_SLEEP` 事件 post 给 lwip task。完全与 pm 框架解耦。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 系统架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ Lua: drv_lowpower.lua │
|
||||||
|
│ 1. dhcpsrv.stop(_G.eth_dhcpsrv) 关闭 dhcpsrv 协程 │
|
||||||
|
│ 2. netdrv.ctrl(LWIP_ETH, CTRL_UPDOWN, 0) 关 CH390 │
|
||||||
|
│ 3. netdrv.arpSleep() 关闭 ARP timer │
|
||||||
|
│ 4. pm.power(pm.WORK_MODE, 1) 进入 Slp1 │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ C: l_netdrv_arp_sleep (luat_lib_netdrv.c) │
|
||||||
|
│ net_lwip2_arp_timer_sleep_prepare() │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌──────────────────────────────────────────────────────────┐
|
||||||
|
│ C: net_lwip2.c │
|
||||||
|
│ platform_send_event(EV_LWIP_ARP_TIMER_SLEEP) │
|
||||||
|
│ └─> lwip task 收到事件 │
|
||||||
|
│ └─> apply_stop() │
|
||||||
|
│ └─> luat_stop_rtos_timer(arp_timer) │
|
||||||
|
│ └─> arp_timer_in_sleep = 1 │
|
||||||
|
└──────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 改动清单
|
||||||
|
|
||||||
|
### 3.1 C 层
|
||||||
|
|
||||||
|
| 文件 | 改动 | 必须重编 |
|
||||||
|
|---|---|---|
|
||||||
|
| `components/network/adapter_lwip2/net_lwip2.h` | 声明 `net_lwip2_arp_timer_sleep_prepare/wakeup_resume` 等公共 API | ✅ |
|
||||||
|
| `components/network/adapter_lwip2/net_lwip2.c` | 实现 sleep/resume API + EV_LWIP_ARP_TIMER_SLEEP/RESUME 事件处理;修复 `LINK_STATE` 钩子用 `netif_is_link_up()`(不是 `netif_is_up()`);`any_adapter_need_arp` 同步加上 link_up 检查 | ✅ |
|
||||||
|
| `components/network/netdrv/src/luat_netdrv_lwip_etharp.c` | `gw_mac_valid` 通知(STABLE 时置 1, free 时置 0) | ✅ |
|
||||||
|
| `components/network/netdrv/src/luat_netdrv_ch390h_task.c` | 所有 CH390 处于 `CH390H_STATUS_STOPPED` 时 task 进入 `LUAT_WAIT_FOREVER` 等待,不再 1Hz 心跳;新增 `luat_ch390h_task_wakeup()` | ✅ |
|
||||||
|
| `components/network/netdrv/src/luat_netdrv_ch390h.c` | `CTRL_UPDOWN=1` 时调用 `luat_ch390h_task_wakeup()` 把 task 从 FOREVER 等待唤醒 | ✅ |
|
||||||
|
| `components/network/netdrv/binding/luat_lib_netdrv.c` | 新增 Lua API `netdrv.arpSleep()` / `netdrv.arpResume()` | ✅ |
|
||||||
|
|
||||||
|
### 3.2 Lua 层
|
||||||
|
|
||||||
|
| 文件 | 改动 | 必须重编 |
|
||||||
|
|---|---|---|
|
||||||
|
| `script/libs/dhcpsrv.lua` | 新增 `dhcpsrv.stop(srv)` API;`dhcp_task` 加 `srv.stop` 退出条件 | ❌ 刷脚本即可 |
|
||||||
|
| `module/Air8000/demo/network_routing/wifi_out_ethernet_in_wifi_in/netif_app.lua` | `dhcpsrv.create` 返回值存到 `_G.eth_dhcpsrv` / `_G.ap_dhcpsrv`,供 drv_lowpower 引用 | ❌ |
|
||||||
|
| `module/Air8000/demo/network_routing/wifi_out_ethernet_in_wifi_in/drv_lowpower.lua` | 休眠前: stop dhcpsrv + CTRL_UPDOWN=0 + `netdrv.arpSleep()`;UART1 唤醒回调: `netdrv.arpResume()` + CTRL_UPDOWN=1 + 重新 create dhcpsrv | ❌ |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 新增 Lua API
|
||||||
|
|
||||||
|
### 4.1 `netdrv.arpSleep()`
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- 进入 pm.power(pm.WORK_MODE, 1) 之前调用
|
||||||
|
netdrv.arpSleep()
|
||||||
|
pm.power(pm.WORK_MODE, 1)
|
||||||
|
```
|
||||||
|
|
||||||
|
- **作用**:直接 post `EV_LWIP_ARP_TIMER_SLEEP` 事件给 lwip task,task 收到后立即 stop ARP 1000ms 定时器,并把当前 running 状态保存到 `arp_timer_sleep_saved` 字段以便恢复时判断。
|
||||||
|
- **返回**:boolean。`true` 表示事件已投递(编译启用了 `LUAT_USE_NETDRV_LWIP_ARP` 且未开 `LUAT_NETDRV_ARP_TIMER_ALWAYS_ON`);`false` 表示当前固件 ARP timer 是 always-on 模式或未启用,无效。
|
||||||
|
- **线程安全**:可在任意 task / 协程中调用。
|
||||||
|
|
||||||
|
### 4.2 `netdrv.arpResume()`
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- 唤醒回调里调用
|
||||||
|
netdrv.arpResume()
|
||||||
|
```
|
||||||
|
|
||||||
|
- **作用**:post `EV_LWIP_ARP_TIMER_RESUME` 事件给 lwip task。task 收到后清 `arp_timer_in_sleep` 标志位,然后检查 `arp_timer_sleep_saved` 或 `any_adapter_need_arp()`,若仍有 adapter 需要 ARP(admin_up + link_up + gw_mac 未解析),重新启动定时器;否则保持停止。
|
||||||
|
- **返回**:boolean,同上。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 关键 C 实现要点
|
||||||
|
|
||||||
|
### 5.1 `LINK_STATE` 事件钩子修复
|
||||||
|
|
||||||
|
```c
|
||||||
|
// 文件: components/network/adapter_lwip2/net_lwip2.c
|
||||||
|
case EV_LWIP_NETIF_LINK_STATE:
|
||||||
|
{
|
||||||
|
uint8_t idx = event.Param3;
|
||||||
|
#ifndef LUAT_NETDRV_ARP_TIMER_ALWAYS_ON
|
||||||
|
// 注意: 这里是 link state 事件, 必须用 netif_is_link_up() 判断 link 层状态,
|
||||||
|
// 不能用 netif_is_up() (它是 admin state). CH390 CTRL_UPDOWN=0 只调
|
||||||
|
// netif_set_link_down, 不动 admin state, 误用 netif_is_up 会导致 link down
|
||||||
|
// 被错判为 LINK_UP 而重新启动 ARP 定时器.
|
||||||
|
if (prvlwip.lwip_netif[idx] != NULL
|
||||||
|
&& netif_is_up(prvlwip.lwip_netif[idx])
|
||||||
|
&& netif_is_link_up(prvlwip.lwip_netif[idx])) {
|
||||||
|
// LINK_UP 分支
|
||||||
|
prvlwip.gw_mac_valid[idx] = 0;
|
||||||
|
net_lwip2_arp_timer_apply_start();
|
||||||
|
} else {
|
||||||
|
// LINK_DOWN 分支
|
||||||
|
prvlwip.gw_mac_valid[idx] = 0;
|
||||||
|
if (!net_lwip2_any_adapter_need_arp()) {
|
||||||
|
net_lwip2_arp_timer_apply_stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
net_lwip2_check_network_ready(idx);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.2 `any_adapter_need_arp` 充要条件
|
||||||
|
|
||||||
|
```c
|
||||||
|
static int net_lwip2_any_adapter_need_arp(void)
|
||||||
|
{
|
||||||
|
uint8_t i;
|
||||||
|
for (i = 0; i < NW_ADAPTER_INDEX_LWIP_NETIF_QTY; i++) {
|
||||||
|
if (prvlwip.lwip_netif[i] != NULL
|
||||||
|
&& netif_is_up(prvlwip.lwip_netif[i])
|
||||||
|
&& netif_is_link_up(prvlwip.lwip_netif[i]) // 必须 link_up
|
||||||
|
&& prvlwip.gw_mac_valid[i] == 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.3 CH390 task FOREVER 等待
|
||||||
|
|
||||||
|
```c
|
||||||
|
// 文件: components/network/netdrv/src/luat_netdrv_ch390h_task.c
|
||||||
|
static void ch390_task_main(void* args) {
|
||||||
|
// ...
|
||||||
|
while (1) {
|
||||||
|
// ...
|
||||||
|
int any_active = 0;
|
||||||
|
for (size_t i = 0; i < MAX_CH390H_NUM; i++) {
|
||||||
|
if (ch390h_drvs[i] != NULL
|
||||||
|
&& ch390h_drvs[i]->status != CH390H_STATUS_STOPPED) {
|
||||||
|
any_active = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!any_active) {
|
||||||
|
// 所有 CH390 都 STOPPED, 不再 1Hz 心跳, 直到收到消息(IRQ 或 CTRL_UPDOWN=1)
|
||||||
|
ret = task_wait_msg(LUAT_WAIT_FOREVER);
|
||||||
|
}
|
||||||
|
else if (s_ch390h_mode == 0) {
|
||||||
|
ret = task_wait_msg(5); // PULL: 5ms
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ret = task_wait_msg(1000); // IRQ: 1Hz 心跳
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void luat_ch390h_task_wakeup(void) {
|
||||||
|
if (qt == NULL) return;
|
||||||
|
uint32_t len = 0;
|
||||||
|
luat_rtos_queue_get_cnt(qt, &len);
|
||||||
|
if (len > 4) return;
|
||||||
|
pkg_evt_t evt = { .id = 2 };
|
||||||
|
luat_rtos_queue_send(qt, &evt, sizeof(pkg_evt_t), 0);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5.4 `netdrv.arpSleep` Lua binding
|
||||||
|
|
||||||
|
```c
|
||||||
|
// 文件: components/network/netdrv/binding/luat_lib_netdrv.c
|
||||||
|
static int l_netdrv_arp_sleep(lua_State *L) {
|
||||||
|
#if defined(LUAT_USE_NETDRV_LWIP_ARP) && !defined(LUAT_NETDRV_ARP_TIMER_ALWAYS_ON)
|
||||||
|
net_lwip2_arp_timer_sleep_prepare();
|
||||||
|
lua_pushboolean(L, 1);
|
||||||
|
#else
|
||||||
|
lua_pushboolean(L, 0);
|
||||||
|
#endif
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注册:
|
||||||
|
{ "arpSleep", ROREG_FUNC(l_netdrv_arp_sleep)},
|
||||||
|
{ "arpResume", ROREG_FUNC(l_netdrv_arp_resume)},
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 业务侧使用模板
|
||||||
|
|
||||||
|
### 6.1 应用脚本(暴露 dhcpsrv 句柄)
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- netif_app.lua
|
||||||
|
local function wifi_eth_setup()
|
||||||
|
-- ...
|
||||||
|
-- 用全局变量暴露给低功耗模块, 进入休眠前会调用 dhcpsrv.stop(eth_dhcpsrv)
|
||||||
|
_G.eth_dhcpsrv = dhcpsrv.create({ adapter = socket.LWIP_ETH })
|
||||||
|
end
|
||||||
|
|
||||||
|
local function wifi_sta_ap_setup()
|
||||||
|
-- ...
|
||||||
|
_G.ap_dhcpsrv = dhcpsrv.create(dhcpsrv_opts)
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 低功耗脚本(关闭顺序)
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- drv_lowpower.lua 在 pm.power(pm.WORK_MODE, 1) 之前
|
||||||
|
|
||||||
|
-- 1) 关 dhcpsrv 协程 (消除 1Hz sys.waitUntil 唤醒)
|
||||||
|
if dhcpsrv and dhcpsrv.stop and _G.eth_dhcpsrv then
|
||||||
|
dhcpsrv.stop(_G.eth_dhcpsrv)
|
||||||
|
_G.eth_dhcpsrv = nil
|
||||||
|
end
|
||||||
|
if dhcpsrv and dhcpsrv.stop and _G.ap_dhcpsrv then
|
||||||
|
dhcpsrv.stop(_G.ap_dhcpsrv)
|
||||||
|
_G.ap_dhcpsrv = nil
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 2) 关 CH390 PHY + 让 ch390_task 进入 FOREVER 等待
|
||||||
|
if netdrv and netdrv.CTRL_UPDOWN and socket.adapter and socket.adapter(socket.LWIP_ETH) then
|
||||||
|
pcall(netdrv.ctrl, socket.LWIP_ETH, netdrv.CTRL_UPDOWN, 0)
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 3) 关 ARP 1000ms 定时器
|
||||||
|
if netdrv and netdrv.arpSleep then
|
||||||
|
netdrv.arpSleep()
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 4) 进入低功耗
|
||||||
|
pm.power(pm.WORK_MODE, 1)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.3 唤醒回调(恢复顺序)
|
||||||
|
|
||||||
|
```lua
|
||||||
|
local function uart1_wakeup_read(_, len)
|
||||||
|
if len == -1 then
|
||||||
|
pm.power(pm.WORK_MODE, 0)
|
||||||
|
|
||||||
|
-- 1) 恢复 ARP 定时器 (内部判断是否真的需要启动)
|
||||||
|
if netdrv and netdrv.arpResume then
|
||||||
|
netdrv.arpResume()
|
||||||
|
end
|
||||||
|
-- 2) 重启 CH390 PHY + task
|
||||||
|
if netdrv and netdrv.CTRL_UPDOWN then
|
||||||
|
pcall(netdrv.ctrl, socket.LWIP_ETH, netdrv.CTRL_UPDOWN, 1)
|
||||||
|
end
|
||||||
|
-- 3) 重建 dhcpsrv (stop 是一次性的)
|
||||||
|
if dhcpsrv and dhcpsrv.create and not _G.eth_dhcpsrv then
|
||||||
|
_G.eth_dhcpsrv = dhcpsrv.create({adapter = socket.LWIP_ETH})
|
||||||
|
end
|
||||||
|
|
||||||
|
uart.write(1, "lowpower wakeup\r\n")
|
||||||
|
end
|
||||||
|
-- ...
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 验证标准
|
||||||
|
|
||||||
|
### 7.1 重编 BSP(不能只刷脚本)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 在 bsp/Air8000 目录下
|
||||||
|
xmake -y
|
||||||
|
# 烧入新的 .soc
|
||||||
|
```
|
||||||
|
|
||||||
|
判断标准:开机日志里必须看到这一行说明 C 改动已编入:
|
||||||
|
|
||||||
|
```
|
||||||
|
I/net arp_pm: INIT adapter=2 on-demand mode, timer created (stopped)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 进入休眠期望日志
|
||||||
|
|
||||||
|
```
|
||||||
|
I/user.lowpower_task enter
|
||||||
|
I/user.drv_lowpower stop ap dhcpsrv
|
||||||
|
I/user.dhcpsrv dhcp_task exit, adapter 3
|
||||||
|
I/user.drv_lowpower ch390 skip CTRL_UPDOWN=0 (LWIP_ETH not present)
|
||||||
|
I/user.drv_lowpower netdrv.arpSleep() -> stop ARP 1000ms timer
|
||||||
|
I/net arp_pm: API sleep_prepare -> post EV_SLEEP
|
||||||
|
I/net arp_pm: EVENT SLEEP saved=1 running=1
|
||||||
|
I/net arp_pm: apply_stop running=1 -> stop
|
||||||
|
I/pm request mode=Slp1, prev=Slp1
|
||||||
|
(之后串口不再出现 D/net arp_pm: TICK etharp_tmr)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.3 唤醒期望日志
|
||||||
|
|
||||||
|
```
|
||||||
|
I/pm wakeup
|
||||||
|
I/net arp_pm: API wakeup_resume -> post EV_RESUME
|
||||||
|
I/net arp_pm: EVENT RESUME saved=1 in_sleep=1
|
||||||
|
I/net arp_pm: apply_start running=0 in_sleep=0 -> start 1000ms
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 排障 checklist
|
||||||
|
|
||||||
|
| 现象 | 可能原因 | 排查方法 |
|
||||||
|
|---|---|---|
|
||||||
|
| 看不到 `netdrv.arpSleep()` 日志 | Lua 脚本未更新 | 重新 download script |
|
||||||
|
| 看到 Lua 日志但没 `API sleep_prepare` | C 改动没编入 | 必须重编 BSP,不能只刷脚本 |
|
||||||
|
| 看到 `apply_stop` 但 TICK 仍在 | 多个 lwip task 实例 / timer 二次注册 | 抓 `INIT` 日志确认初始化次数 |
|
||||||
|
| `not such netdrv 4` 警告 | CH390 没初始化 | 检查 `wifi_eth_setup()` 是否被调用 |
|
||||||
|
| `apply_start skip running=1 in_sleep=0` 之后又出现 TICK | LINK_UP/DOWN 误判 | 确认 net_lwip2.c 用的是 `netif_is_link_up()` 不是 `netif_is_up()` |
|
||||||
|
| 唤醒后 `arpResume` 后没自动启动 timer | `any_adapter_need_arp` 返回 false | 正常,等业务流量触发 SET_IP/LINK_UP 时会自启 |
|
||||||
|
| WIFI STA 仍 1Hz 唤醒 | LWIP_DHCP `dhcp_fine_tmr` 500ms / `dhcp_coarse_tmr` 60s | 改用静态 IP 或在 lwipopts.h 关 LWIP_DHCP |
|
||||||
|
| 仍有 10Hz 唤醒 | `LWIP_IGMP=1` (`igmp_tmr` 100ms) 或 `LWIP_IPV6_MLD=1` | 在 BSP lwipopts.h 设为 0 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 其他功耗杀手提醒
|
||||||
|
|
||||||
|
`netdrv.arpSleep()` 只解决 ARP 1000ms 定时器。要达到最低功耗还需注意:
|
||||||
|
|
||||||
|
1. **LWIP_DHCP**:500ms / 60s 周期,必杀。静态 IP 或编译关闭。
|
||||||
|
2. **LWIP_IGMP / LWIP_IPV6_MLD**:100ms 周期,致命。`lwipopts.h` 设为 0。
|
||||||
|
3. **CH390 PULL 模式**:5ms 轮询。必须接 INT 脚走 IRQ 模式。
|
||||||
|
4. **AGPIO 高电平 + 外部下拉电阻**:每 100K 下拉 ~33uA。
|
||||||
|
5. **GNSS / GSensor 电源开关 (GPIO24)**:拉低省 88uA。
|
||||||
|
6. **WIFI 芯片 (GPIO23)**:`pm.power(pm.WIFI, 0)` 或 `gpio.setup(23, nil, gpio.PULLDOWN)` 省 42uA。
|
||||||
|
7. **dhcpsrv.lua 协程**:1Hz `sys.waitUntil`,用 `dhcpsrv.stop(srv)` 关掉。
|
||||||
|
8. **CH390 task 1Hz 心跳**:用 `netdrv.ctrl(LWIP_ETH, CTRL_UPDOWN, 0)` 让 task 进 FOREVER 等待。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 历史决策记录
|
||||||
|
|
||||||
|
| 日期 | 决策 | 原因 |
|
||||||
|
|---|---|---|
|
||||||
|
| 2026-06-23 | 在 `luat_lib_pm.c` 加 sleep hook | 最初方案,认为 `pm.power(WORK_MODE,1)` 会经过 `l_pm_power_ctrl` |
|
||||||
|
| 2026-06-23 | hook 移到 `#ifdef LUAT_USE_DRV_PM` 外 | 发现 Air8000 走 DRV_PM 分支,hook 被跳过 |
|
||||||
|
| 2026-06-24 | 修复 `EV_LWIP_NETIF_LINK_STATE` 用 `netif_is_link_up()` | 发现 `CTRL_UPDOWN=0` 时 link_down 被错判为 LINK_UP |
|
||||||
|
| 2026-06-24 | 抛弃 pm hook,改用 `netdrv.arpSleep()` Lua API | 发现 Air8000 `pm.power(WORK_MODE,1)` 实际走 `pm.request(Slp1)` 路径,绕过所有 pm 钩子 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 相关文件索引
|
||||||
|
|
||||||
|
- 内核 ARP 定时器实现: [components/network/adapter_lwip2/net_lwip2.c](../components/network/adapter_lwip2/net_lwip2.c)
|
||||||
|
- ARP 定时器公共 API: [components/network/adapter_lwip2/net_lwip2.h](../components/network/adapter_lwip2/net_lwip2.h)
|
||||||
|
- gw_mac 通知: [components/network/netdrv/src/luat_netdrv_lwip_etharp.c](../components/network/netdrv/src/luat_netdrv_lwip_etharp.c)
|
||||||
|
- CH390 task: [components/network/netdrv/src/luat_netdrv_ch390h_task.c](../components/network/netdrv/src/luat_netdrv_ch390h_task.c)
|
||||||
|
- CH390 控制: [components/network/netdrv/src/luat_netdrv_ch390h.c](../components/network/netdrv/src/luat_netdrv_ch390h.c)
|
||||||
|
- netdrv Lua binding: [components/network/netdrv/binding/luat_lib_netdrv.c](../components/network/netdrv/binding/luat_lib_netdrv.c)
|
||||||
|
- dhcpsrv: [script/libs/dhcpsrv.lua](../script/libs/dhcpsrv.lua)
|
||||||
|
- 示例 demo: [module/Air8000/demo/network_routing/wifi_out_ethernet_in_wifi_in/](../module/Air8000/demo/network_routing/wifi_out_ethernet_in_wifi_in/)
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
# netdrv IKEv2/IPsec 客户端设计文档
|
||||||
|
|
||||||
|
> 适用范围:LuatOS `netdrv` 框架下的 IKEv2/IPsec 隧道模式客户端
|
||||||
|
> (ESP tunnel mode)。首期已在 PC 模拟器上对接真实 strongSwan 网关
|
||||||
|
> `ipsec.air32.cn`(strongSwan 5.9.13, Ubuntu 24.04 云主机)联调通过。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 目标与范围
|
||||||
|
|
||||||
|
在 netdrv 框架内新增 `netdrv.IPSEC` 虚拟网卡,实现:
|
||||||
|
|
||||||
|
- IKEv2 发起端(RFC 7296),服务器证书链校验 + 强制 EAP-MSCHAPv2;
|
||||||
|
- NAT-T(RFC 3948):UDP 500 启动,探测到 NAT 后切换 4500;
|
||||||
|
- DPD 保活、CHILD_SA 到期重协商(CREATE_CHILD_SA,默认带 PFS,
|
||||||
|
KE + 新 Ni/Nr 按 RFC 7296 §2.17 派生 KEYMAT;网关不支持 PFS 时自动
|
||||||
|
无 KE 重试一次并保持旧 SA 在线)、IKE SA 到期全量重建;
|
||||||
|
- 套件扩展:IKE DH 组 19/20/21(ECP-256/384/521,RFC 4753),
|
||||||
|
ESP AES-GCM-128/256(RFC 4106 AEAD,SA 内无 INTEG transform);
|
||||||
|
- MOBIKE(RFC 4555,opt-in,默认关闭):本地地址变化时发送
|
||||||
|
INFORMATIONAL(UPDATE_SA_ADDRESSES + NAT-D),处理对端发起的地址更新,
|
||||||
|
以及 established 状态下的对端地址学习;不做 ADDITIONAL_IP4_ADDRESS
|
||||||
|
通告与 COOKIE2;
|
||||||
|
- CP(Configuration Payload)下发虚拟 IPv4 + DNS;
|
||||||
|
- ESP 隧道模式(RFC 4303)AES-CBC-128/256 + HMAC-SHA1-96 /
|
||||||
|
HMAC-SHA2-256-128 或 AES-GCM-128/256,32 包反重放窗口,
|
||||||
|
ESP-in-UDP(4500)。
|
||||||
|
|
||||||
|
明确不做:IKEv1、L2TP/IPsec、ESP 传输模式、客户端证书认证、
|
||||||
|
IPv6 隧道、MOBIKE 的 ADDITIONAL_IP4_ADDRESS 通告与 COOKIE2。
|
||||||
|
MOBIKE 默认关闭(`ipsec_mobike_enable` 未配置时行为与旧版一致,
|
||||||
|
地址变化仍走断线重连)。
|
||||||
|
|
||||||
|
## 2. 文件布局
|
||||||
|
|
||||||
|
代码按用户要求拆分到独立子模块 `components/network/ipsec/`(内部头在
|
||||||
|
`include/ipsec/`,源文件在 `src/`):
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `include/ipsec/ipsec_crypto.h` + `src/ipsec_crypto.c` | PRF+/HMAC、DH modp2048、IKE/CHILD 密钥派生、AUTH 计算/验签、X.509 链+SAN 校验(信任锚由 `ipsec_ca_cert_pem` 提供;不提供时默认 fail-closed,仅当显式开启 `ipsec_insecure_cert_ok` 才接受证书且仍校验 SAN) |
|
||||||
|
| `include/ipsec/ipsec_esp.h` + `src/ipsec_esp.c` | ESP 隧道封装/解封(AES-CBC + HMAC 或 AES-GCM AEAD)、SPI 方向、32 包反重放 |
|
||||||
|
| `include/ipsec/ipsec_ike.h` + `src/ipsec_ike.c` | IKEv2 状态机:SA_INIT/AUTH/EAP/CREATE_CHILD_SA/INFORMATIONAL、payload 编解码、SK 加密、NAT-T 切换、DPD、重协商、虚拟 netif 与 adapter 收发 |
|
||||||
|
| `include/ipsec/ipsec_vendor_md4.h` + `src/ipsec_vendor_md4.c` | MD4(Apache-2.0, 从 mbedTLS 2.x vendor, 自包含) |
|
||||||
|
| `include/ipsec/ipsec_vendor_chap_ms.h` + `src/ipsec_vendor_chap_ms.c` | MS-CHAPv2(BSD, 移植自 lwIP2.2 `chap_ms.c`),含 strongSwan 线格式与 RFC 3079 MSK 派生、RFC 2759 测试向量自检 |
|
||||||
|
| `src/luat_netdrv_ipsec.c` | netdrv 胶水层:setup/ctrl(UPDOWN)/dhcp(-1)/debug + 链路状态回调 |
|
||||||
|
| `components/network/netdrv/include/luat_netdrv_ipsec.h` | 胶水层头文件(保持在 netdrv/include) |
|
||||||
|
|
||||||
|
接入点:
|
||||||
|
|
||||||
|
- `luat_netdrv_drv.h`:`LUAT_NETDRV_IMPL_IPSEC 7`
|
||||||
|
- `luat_netdrv.h`:`luat_netdrv_ipsec_conf_t` + `conf->ipsec_conf`
|
||||||
|
- `luat_netdrv.c` / `luat_lib_netdrv.c`:setup 分发与 `ipsec_*` 参数解析
|
||||||
|
- `bsp/pc/xmake.lua`:ipsec 子模块头文件搜索路径(`components/network/ipsec/include`)
|
||||||
|
- `bsp/pc/include/luat_conf_bsp.h`:`LUAT_USE_NETDRV_IPSEC 1`
|
||||||
|
- `bsp/pc/include/lwipopts.h`:`MEMP_NUM_SYS_TIMEOUT 30`
|
||||||
|
- `bsp/pc/port/luat_crypto_mini.c`:PC 模拟器 TRNG 每次调用重新播种
|
||||||
|
|
||||||
|
## 3. 架构与数据流
|
||||||
|
|
||||||
|
```
|
||||||
|
Lua (netdrv.setup / socket.*)
|
||||||
|
|
|
||||||
|
v
|
||||||
|
luat_netdrv_ipsec.c (setup/ctrl/dhcp/debug, IP_READY/IP_LOSE 事件)
|
||||||
|
|
|
||||||
|
v
|
||||||
|
ipsec_ike.c (IKEv2 状态机, tcpip 线程)
|
||||||
|
| netif (虚拟网卡, 全流量默认路由)
|
||||||
|
| | netif output -> ESP 封装 -> adapter UDP TX(4500)
|
||||||
|
| | adapter RX(4500) -> IKE(4字节零前缀) 或 ESP -> 内层 IP 注入
|
||||||
|
|
|
||||||
|
+-- network_ctrl_t (luat_network_adapter, 单 socket: 500 -> 4500)
|
||||||
|
```
|
||||||
|
|
||||||
|
- IKE 与 ESP 共用同一个 adapter UDP socket:先在 500 上完成
|
||||||
|
IKE_SA_INIT,NAT 探测后切换到本地/远端 4500(RFC 3948 非 ESP
|
||||||
|
marker 区分 IKE 与 ESP)。这是标准 NAT-T 形态,避免了双 socket
|
||||||
|
同端口绑定的问题。
|
||||||
|
- 所有状态机工作经 `tcpip_callback_with_block` 汇聚到 tcpip 线程;
|
||||||
|
adapter 回调只拷贝数据并投递,与 L2TP/OpenVPN 客户端一致。
|
||||||
|
- CP 下发虚拟 IP 后 `netif_set_addr` + `netif_set_default`,DNS 写入
|
||||||
|
`network_set_dns_server`。
|
||||||
|
|
||||||
|
## 4. 协议要点与互操作细节
|
||||||
|
|
||||||
|
- 套件:IKE `{aes256-sha256, aes128-sha1} × {modp2048, ecp256, ecp384,
|
||||||
|
ecp521}!`(8 个提案,DH14 优先;响应者选中其它组时按 RFC 7296 §2.7
|
||||||
|
的 INVALID_KE 通知重试,IKE_SA_INIT 默认先发 DH14 的 KE);
|
||||||
|
ESP `aes256-sha256, aes128-sha1, aes256gcm16, aes128gcm16!`
|
||||||
|
(AEAD 提案无 INTEG transform,transform id 20 + KEY_LENGTH 属性)。
|
||||||
|
- CHILD_SA 重协商默认带 PFS:请求载荷顺序 `SA | Ni | KE | TSi | TSr`,
|
||||||
|
使用 IKE_SA_INIT 协商出的 DH 组生成新的临时密钥对;响应解析新 Nr 与
|
||||||
|
KE,KEYMAT = prf+(SK_d, g^ir | Ni | Nr)。响应缺少 KE 或带
|
||||||
|
NO_PROPOSAL_CHOSEN/TS_UNACCEPTABLE 时,自动无 KE 重试一次并保持旧 SA
|
||||||
|
在线(与旧版行为一致)。
|
||||||
|
- MOBIKE 更新载荷顺序:`N(UPDATE_SA_ADDRESSES) | N(NAT_DETECTION_SOURCE_IP)
|
||||||
|
| N(NAT_DETECTION_DESTINATION_IP)`(RFC 4555 §2.2),NAT-D 复用
|
||||||
|
IKE_SA_INIT 的 SHA-1 哈希方式;对端发起的更新用当前本地 IP 校验
|
||||||
|
目标 NAT-D,不匹配则忽略;established 状态下的地址学习只发生在
|
||||||
|
密码学验证通过之后:ESP 报文在 ICV/解密成功后、对端
|
||||||
|
UPDATE_SA_ADDRESSES 在 SK 解密 + NAT-D 校验通过后、已认证的
|
||||||
|
INFORMATIONAL 响应在 ICV 校验通过后(RFC 4555 §3,
|
||||||
|
未认证报文一律不得改写对端地址)。
|
||||||
|
- IKE 请求单在途槽位:`pending_msgid/last_tx` 全 client 一份,
|
||||||
|
DPD/MOBIKE 更新/CREATE_CHILD_SA 任一在途时其余请求让路(下一秒
|
||||||
|
tick 重试);INFORMATIONAL 响应(DPD/MOBIKE ack)经 SK 解密 +
|
||||||
|
ICV 校验后才采信;msgid 全链路 32 位(RFC 7296 单调不回绕)。
|
||||||
|
- IKE SK 载荷:AES-CBC + HMAC;**ICV 只覆盖 IKE 报文本身**(strongSwan
|
||||||
|
收到 4500 报文会先剥离 4 字节非 ESP marker 再校验)。
|
||||||
|
- ESP AEAD(RFC 4106):8 字节显式 IV,GCM IV = salt(4) | IV(8),
|
||||||
|
AAD = SPI | SEQ,ICV 16 字节,padding 按 4 字节对齐;KEYMAT 每方向为
|
||||||
|
`enc_key(16/32) + salt(4)`(RFC 7296 §3.3.2),无 INTEG 密钥。
|
||||||
|
- AUTH:EAP 模式按 RFC 7296 §2.16 用 MSK 作为共享密钥;
|
||||||
|
`"Key Pad for IKEv2"` 为 17 字节(不含 NUL)。
|
||||||
|
- MSK:按 strongSwan 的 RFC 3079 实现——
|
||||||
|
`master=SHA1(HH|NT-Response|Magic1)`,
|
||||||
|
`recv/send=SHA1(master[0:16]|0x00*40|Magic2/3|0xF2*40)`,
|
||||||
|
`MSK=recv[0:16]|send[0:16]|0x00*32`。
|
||||||
|
- MS-CHAPv2 线格式采用 strongSwan/Windows 客户端格式:
|
||||||
|
`opcode|id|ms_length|value_size|...`(区别于 RFC 2759 排版)。
|
||||||
|
- ESP SPI 方向:发起端**发送**用响应者分配的 SPI(SAr2),**接收**
|
||||||
|
用自己提议的 SPI(SAi2)。
|
||||||
|
- 证书链:配置了 `ipsec_ca_cert_pem` 时按该信任锚做链校验并校验
|
||||||
|
SAN `ipsec.air32.cn`;未配置时默认 **fail-closed**(固件不再内置任何
|
||||||
|
信任锚),仅当显式设置 `ipsec_insecure_cert_ok=true` 才接受服务器证书,
|
||||||
|
且仍强制 SAN 匹配。mbedTLS 校验需传 `mbedtls_x509_crt_profile_default`,
|
||||||
|
PEM 缓冲需 NUL 结尾(mbedTLS 3.x 的 PEM 识别条件)。
|
||||||
|
|
||||||
|
## 5. 配置参考(Lua)
|
||||||
|
|
||||||
|
```lua
|
||||||
|
netdrv.setup(socket.LWIP_USER1, netdrv.IPSEC, {
|
||||||
|
ipsec_remote_ip = "154.8.159.79", -- 网关 IP(仅字面量)
|
||||||
|
ipsec_remote_port = 500, -- IKE 端口, 默认 500
|
||||||
|
ipsec_username = "vpnuser",
|
||||||
|
ipsec_password = "xxxx",
|
||||||
|
ipsec_san = "ipsec.air32.cn", -- 服务器 SAN 校验
|
||||||
|
-- ipsec_ca_cert_pem = "-----BEGIN CERTIFICATE-----...", -- 建议配置信任锚;
|
||||||
|
-- -- 未配置且未开启 insecure 时无法连接 (fail-closed)
|
||||||
|
-- ipsec_insecure_cert_ok = false, -- 默认 false; true 表示无 CA 时仅校验 SAN 即接受
|
||||||
|
ipsec_mtu = 1400,
|
||||||
|
ipsec_retry_enable = true,
|
||||||
|
ipsec_retry_base_ms = 1000,
|
||||||
|
ipsec_retry_max_ms = 60000,
|
||||||
|
-- ipsec_mobike_enable = true, -- MOBIKE 双向地址更新 (默认关闭)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
`ipsec_mobike_enable`:布尔,默认 `false`。开启后客户端在 1s tick 轮询
|
||||||
|
本地地址,变化时发送 UPDATE_SA_ADDRESSES;底层 socket 关闭但传输仍在线
|
||||||
|
时重开同端口 socket 并走更新流程而非全量重建;同时支持对端发起的地址
|
||||||
|
更新与 established 状态下的地址学习。仅 utest 构建提供测试钩子
|
||||||
|
`netdrv.ipsec_sim_addr_change(id)` 模拟一次本地地址变更。
|
||||||
|
|
||||||
|
## 6. 联调记录(2026-08-12, PC 模拟器 ↔ ipsec.air32.cn)
|
||||||
|
|
||||||
|
联调期间发现并修复的问题:
|
||||||
|
|
||||||
|
| # | 现象 | 根因 | 修复 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | 网关对 IKE_SA_INIT 无响应 | Ni/NAT-D 载荷的 Next Payload 误用 notify 值(16388)而非载荷类型(41) | 改为 `IPSEC_PAYLOAD_NOTIFY` |
|
||||||
|
| 2 | IKE_AUTH 无响应, 网关日志 `message ID 16777216, expected 1` | msgid 以单字节写入 (`01 00 00 00`) 而非 4 字节大端 | `ike_put32(msg+20, msgid)` |
|
||||||
|
| 3 | 网关日志 `MAC verification failed` | mbedTLS 3 `aes_crypt_cbc` 会把最后一组密文写回 IV 缓冲, 覆盖了包内 IV | 用独立 IV 缓冲 |
|
||||||
|
| 4 | 网关日志 `MAC verification failed`(修复 3 后仍失败) | 4500 上 ICV 把 4 字节零前缀算进去了, 而 strongSwan 收到会先剥离 | ICV 只覆盖 IKE 报文 |
|
||||||
|
| 5 | `trust anchor parse failed -0x2180` | mbedTLS 3.x 仅当缓冲区 NUL 结尾才识别 PEM | 内嵌/用户 PEM 均保留 NUL 结尾 |
|
||||||
|
| 6 | `cert chain verify failed flags=0xFFFFFFFF` | `mbedtls_x509_crt_verify_with_profile` 的 profile 传 NULL 返回 BAD_INPUT_DATA | 传 `mbedtls_x509_crt_profile_default` |
|
||||||
|
| 7 | 服务器只发叶子证书, 链校验失败 | strongSwan `leftsendcert=always` 只发叶子;Let's Encrypt 2026 新链 | 内置 YE2/ISRG Root YE/ISRG Root X2 中间 CA |
|
||||||
|
| 8 | `server AUTH signature verification failed` | 裸 r\|s 转 DER 时长度公式少算 2 字节 | 修正 `total=6+r+s+pad` |
|
||||||
|
| 9 | 服务器 `INVALID_SYNTAX` 拒绝 EAP Identity 响应 | EAP 载荷构建后未 `p += plen`, 内层为空 | 修复三处 EAP 载荷 |
|
||||||
|
| 10 | `unhandled MS-CHAPv2 request opcode 1` | 用 RFC 2759 排版解析 strongSwan 的 Challenge | 按 strongSwan 线格式解析 |
|
||||||
|
| 11 | 最终 AUTH 被拒 | 内层 `"Key Pad for IKEv2"` 用 `sizeof`(含 NUL 18 字节) | 用 17 字节 |
|
||||||
|
| 12 | 最终 AUTH 被拒(修复 11 后仍失败) | MSK 的 master 用 `sizeof(inner)=79`(实际 67);且 0x36/0x5C 填充与 strongSwan 的 0x00/0xF2 不符;32 字节 key 从 20 字节 digest 越界拷贝 | 按 strongSwan 实现重写 MSK 派生 |
|
||||||
|
| 13 | ESP 无回包, 网关 `XfrmInNoStates` | ESP SPI 方向反了(发送用了自己提议的 SPI) | 发送用 SAr2 的 SPI |
|
||||||
|
| 14 | 隧道 IP 与策略不匹配 | CP 的 IPv4 字节序(`ip4_addr_set_u32` 需先 `lwip_htonl`) | 恢复 `lwip_htonl(ike_get32())` |
|
||||||
|
| 15 | 证书校验 `NOT_TRUSTED`(flags=0x8) | 网关改用私建 CA(`CN=IKEv2 VPN CA`,自签 10 年),strongSwan 只发叶子,内置 ISRG Root X1 / LE 中间链不再适用 | 测试脚本改从 `scripts/ikev2-ca.crt` 读取 CA 作为 `ipsec_ca_cert_pem` 传入;同时按需求移除固件内置信任锚,未配 CA 的默认行为在后续提交中收紧为 fail-closed(需显式 `ipsec_insecure_cert_ok=true` 才接受证书,且仍校验 SAN) |
|
||||||
|
|
||||||
|
服务器侧配合项(已处理,用户授权调试):
|
||||||
|
|
||||||
|
- 云主机 `dirtyfrag.conf` 禁用 `esp4` 内核模块(`install esp4 /bin/false`),
|
||||||
|
导致 XFRM SAD 安装失败(`netlink error: Requested type not found (93)`):
|
||||||
|
已注释该规则并加载 `esp4`/`xfrm_user`/`xfrm4_tunnel`;
|
||||||
|
- `ipsec.secrets` 私钥声明为 `: RSA` 但实际是 ECDSA P-384:
|
||||||
|
已改为 `: ECDSA`;
|
||||||
|
- 联调后 `charondebug` 已恢复 `ike 2`,`esp=aes256-sha256, aes128-sha1!`
|
||||||
|
已恢复原样。
|
||||||
|
|
||||||
|
## 7. 测试结果(PC 模拟器, testcase/unit/net/netdrv_ipsec_basic)
|
||||||
|
|
||||||
|
- `connect`:IKE_SA_INIT → 证书链+SAN 校验 → 服务器 AUTH 验签 →
|
||||||
|
EAP-MSCHAPv2(含服务器 Authenticator Response 校验)→ 双端 AUTH →
|
||||||
|
CP 下发虚拟 IP/DNS → 隧道上线 → 隧道内 TCP 到网关 SSH 收到 banner,
|
||||||
|
**3 passed / 0 failed**;
|
||||||
|
- `badpass`:错误密码 → EAP 失败 → 不 ready,**通过**;
|
||||||
|
- `sanit`:错误 SAN → 证书校验拒绝 → 不 ready,**通过**。
|
||||||
|
|
||||||
|
> 前置:`testcase/unit/net/netdrv_ipsec_basic/scripts/ikev2-ca.crt`
|
||||||
|
> (网关私建 CA)必须存在,测试会把它作为 `ipsec_ca_cert_pem` 传入;
|
||||||
|
> 测试账号凭据通过环境变量 `LUAT_IPSEC_USERNAME` / `LUAT_IPSEC_PASSWORD`
|
||||||
|
> 注入(不随源码分发),未设置时测试跳过。
|
||||||
|
> 固件默认 fail-closed:未传 `ipsec_ca_cert_pem` 且未显式开启
|
||||||
|
> `ipsec_insecure_cert_ok` 时拒绝连接(固件不再内置任何信任锚)。
|
||||||
|
|
||||||
|
## 8. 遗留与后续
|
||||||
|
|
||||||
|
- 集成联调(需网关侧重配,未完成项见交付说明):
|
||||||
|
- PFS:网关 `pfs=yes` + 缩短 lifetime,验证重协商日志、DPD、隧道不断流;
|
||||||
|
- ECP/GCM:网关 `ike=aes256-sha256-ecp256!` / `esp=aes256gcm16!` 建连;
|
||||||
|
- MOBIKE:`netdrv.ipsec_sim_addr_change` 触发 UPDATE_SA_ADDRESSES,
|
||||||
|
网关 `mobike=no` 时回退重连。
|
||||||
|
- 硬件 BSP:需确认目标板 lwip 导出符号(`pbuf/netif/sys/ip4_input`)
|
||||||
|
与 adapter 行为,并按验收清单在目标板重跑;
|
||||||
|
- 服务器 FORWARD 链的 IPsec 池 ACCEPT 规则与 `rightsourceip`
|
||||||
|
段需按实际网络调整(当前云主机 iptables 规则与池配置不完全一致,
|
||||||
|
隧道到网关本机可用,跨子网转发需核对);
|
||||||
|
- `netdrv.debug` 会输出 IKE/ESP 帧日志(含 SK 明文转储仅调试用)。
|
||||||
|
|
||||||
|
## 9. 相关文档
|
||||||
|
|
||||||
|
- RFC 7296(IKEv2)、RFC 3948(NAT-T)、RFC 4303(ESP)、
|
||||||
|
RFC 2759/3079(MS-CHAPv2/MSK)
|
||||||
|
- `docs/l2tp-design.md`(线程模型/胶水层/构建接线参考)
|
||||||
|
- `components/network/l2tp/src/l2tp_client.c` /
|
||||||
|
`components/network/openvpn/src/ovpn_client.c`(传输与 netif 参考)
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
# VFS 统一测试 — 已知问题 / Bug 列表
|
||||||
|
|
||||||
|
本文件由 `testcase/utest/fs/vfs_uniform/` 框架自动/手动追加, 汇总 vfs 统一接口在
|
||||||
|
6 个文件系统 (ram/posix/lfs2/fatfs/tfs/pgfs) 上的行为差异与已发现 bug.
|
||||||
|
|
||||||
|
## 格式
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
### <FS>::<test_name> [severity]
|
||||||
|
- **Expected**: 一句话预期行为
|
||||||
|
- **Actual**: 一句话实际行为
|
||||||
|
- **Source**: 源文件:行号 (定位)
|
||||||
|
- **Repro**:
|
||||||
|
1. 步骤 1
|
||||||
|
2. 步骤 2
|
||||||
|
- **Tags**: fs=<fs>, mode=<mode>, feature=<area>
|
||||||
|
```
|
||||||
|
|
||||||
|
## 索引
|
||||||
|
|
||||||
|
- [ram](#ram)
|
||||||
|
- [posix](#posix)
|
||||||
|
- [lfs2](#lfs2)
|
||||||
|
- [fatfs](#fatfs)
|
||||||
|
- [tfs](#tfs)
|
||||||
|
- [pgfs](#pgfs)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ram
|
||||||
|
|
||||||
|
(empty)
|
||||||
|
|
||||||
|
## posix
|
||||||
|
|
||||||
|
### posix::test_dir_nested_mkdir_auto_parent [med]
|
||||||
|
- **Expected**: `io.mkdir("a/b/c")` 在父目录 b 不存在时应自动创建 (与 ram 行为一致)
|
||||||
|
- **Actual**: `io.mkdir` 失败, 不创建父目录
|
||||||
|
- **Source**: `luat/vfs/luat_fs_posix.c:200-208` (直接调原生 `mkdir`, 不会递归创建父目录)
|
||||||
|
- **Repro**:
|
||||||
|
1. `io.mkdir("vfs_dir_a/b/c")` (b 不存在)
|
||||||
|
- **Tags**: fs=posix, mode=mkdir, feature=dir
|
||||||
|
|
||||||
|
### posix::test_edge_deep_nesting [low]
|
||||||
|
- **Expected**: `io.mkdir` 应能创建 7 级嵌套目录 (a/b/c/d/e/f/g)
|
||||||
|
- **Actual**: `io.mkdir` 失败, 因为中间父目录 (a, a/b, …) 不存在
|
||||||
|
- **Source**: `luat/vfs/luat_fs_posix.c:200-208` (同上, 单一 `mkdir` 调用)
|
||||||
|
- **Repro**:
|
||||||
|
1. `io.mkdir("vfs_edge_deep/a/b/c/d/e/f/g")`
|
||||||
|
- **Tags**: fs=posix, mode=mkdir, feature=dir
|
||||||
|
|
||||||
|
### posix::test_meta_rename_overwrite [low]
|
||||||
|
- **Expected**: `os.rename` 覆盖已存在目标文件应成功
|
||||||
|
- **Actual**: `os.rename` 失败, 源文件保持不变
|
||||||
|
- **Source**: `luat/vfs/luat_fs_posix.c:105-112` (直接调原生 `rename`; Windows 不允许 overwrite existing target)
|
||||||
|
- **Repro**:
|
||||||
|
1. `mkdir d; io.open("d/from.txt","wb"); io.open("d/to.txt","wb")`
|
||||||
|
2. `os.rename("d/from.txt", "d/to.txt")`
|
||||||
|
- **Tags**: fs=posix, mode=rename, feature=meta, platform=windows
|
||||||
|
|
||||||
|
## lfs2
|
||||||
|
|
||||||
|
> lfs2 跑通 26/30 (跳过 1 个 C13 嵌套 mkdir). 真实 bug 4 个 (含 2 个 refcount 缺失).
|
||||||
|
|
||||||
|
### lfs2::test_edge_long_filename [low]
|
||||||
|
- **Expected**: 60 字符文件名应可创建 (与 ram 一致)
|
||||||
|
- **Actual**: 60 字符文件名 open 失败
|
||||||
|
- **Source**: `luat/vfs/luat_fs_lfs2.c` (lfs2 默认 name_max=63, 但 PC 配置/驱动对长名更敏感)
|
||||||
|
- **Repro**:
|
||||||
|
1. `io.open("/lfs2/vfs_edge_<60 chars>.txt", "wb")`
|
||||||
|
- **Tags**: fs=lfs2, mode=create, feature=long-name
|
||||||
|
|
||||||
|
### lfs2::test_edge_deep_nesting [low]
|
||||||
|
- **Expected**: mkdir a/b/c/d/e/f/g 7 级嵌套应成功
|
||||||
|
- **Actual**: 失败
|
||||||
|
- **Source**: `luat/vfs/luat_fs_lfs2.c:206-223` (mkdir 不自动创建父目录)
|
||||||
|
- **Repro**:
|
||||||
|
1. `io.mkdir("/lfs2/vfs_edge_deep/a/b/c/d/e/f/g")`
|
||||||
|
- **Tags**: fs=lfs2, mode=mkdir, feature=deep-nesting
|
||||||
|
|
||||||
|
### lfs2::test_refcount_remove_open_fails [med]
|
||||||
|
- **Expected**: 打开中的文件不应被 os.remove 删除
|
||||||
|
- **Actual**: os.remove 成功了
|
||||||
|
- **Source**: `luat/vfs/luat_fs_lfs2.c:134` (直接调 `lfs_remove`, 不检查引用计数)
|
||||||
|
- **Repro**:
|
||||||
|
1. 创文件 p
|
||||||
|
2. `f = io.open(p, "r")`
|
||||||
|
3. `os.remove(p)` -- 期望失败
|
||||||
|
4. `f:close()`
|
||||||
|
- **Tags**: fs=lfs2, mode=read+remove, feature=refcount
|
||||||
|
|
||||||
|
### lfs2::test_refcount_rename_open_fails [med]
|
||||||
|
- **Expected**: 打开中的源文件不应被 os.rename 重命名
|
||||||
|
- **Actual**: os.rename 成功了
|
||||||
|
- **Source**: `luat/vfs/luat_fs_lfs2.c:134` (rename 路径同样不检查引用)
|
||||||
|
- **Repro**:
|
||||||
|
1. 创文件 src
|
||||||
|
2. `f = io.open(src, "r")`
|
||||||
|
3. `os.rename(src, dst)` -- 期望失败
|
||||||
|
4. `f:close()`
|
||||||
|
- **Tags**: fs=lfs2, mode=read+rename, feature=refcount
|
||||||
|
|
||||||
|
## fatfs
|
||||||
|
|
||||||
|
### fatfs::setup_module_not_found [high]
|
||||||
|
- **Expected**: 当 `fatfs` 模块在 PC BSP 中不可用时, `mount_fatfs.setup()` 应返回 false 让 `main.lua` 自跳过整个测试套
|
||||||
|
- **Actual**: `mount_fatfs.lua:9` 的 `require("fatfs")` 在 PC BSP 上直接抛出 "module 'fatfs' not found", VM 在 `main.lua` 检测 `fs_ok` 之前就崩溃退出, 测试套根本没有 self-skip 机会
|
||||||
|
- **Source**: `testcase/utest/fs/vfs_uniform/scripts/mount_fatfs.lua:9`
|
||||||
|
- **Repro**:
|
||||||
|
1. 在 PC 模拟器上跑 `vfs_uniform_fatfs`
|
||||||
|
2. `mount_fatfs.setup()` 里 `require("fatfs")` 失败, 抛错
|
||||||
|
3. 错误沿着 `require` 链 `vfs_uniform_mount.lua -> mount_fatfs.lua` 一路冒泡, VM 退出
|
||||||
|
4. `main.lua` 的 `if not fs_ok then ... os.exit(0) end` 永远不会执行
|
||||||
|
- **Tags**: fs=fatfs, mode=pc, feature=framework-bootstrap
|
||||||
|
|
||||||
|
### fatfs::pc_build_fatfs_module_unavailable [high]
|
||||||
|
- **Expected**: PC BSP 应当能 `require("fatfs")` 加载内置 fatfs 模块 (因为 `LUAT_USE_FATFS` 已在 `bsp/pc/include/luat_conf_bsp.h:145` 定义, 且 `luaopen_fatfs` 在 `bsp/pc/port/luat_base_mini.c:160` 注册)
|
||||||
|
- **Actual**: 当前 PC 二进制 `bsp/pc/build/out/luatos-lua.exe` 对 `require("fatfs")` 返回 "module not found", 同样 `require("uart")`/`require("json")` 等内置模块也都失败; 只有 `io`/`os`/`string`/`log`/`rtos` 这类 globals 仍可用. 整个 fatfs 测试套无法在 PC 上执行
|
||||||
|
- **Source**: `bsp/pc/port/luat_base_mini.c:159-161` (注册) vs PC BSP 实际加载行为
|
||||||
|
- **Repro**:
|
||||||
|
1. 写 `print(type(require("fatfs")))` 的最小 main.lua
|
||||||
|
2. 用 `bsp/pc/build/out/luatos-lua.exe ... /tmp/test/` 跑
|
||||||
|
3. 输出 `module 'fatfs' not found` 然后 `Lua VM exit!! reboot in 1000ms`
|
||||||
|
- **Tags**: fs=fatfs, mode=pc, feature=module-registration
|
||||||
|
|
||||||
|
## tfs
|
||||||
|
|
||||||
|
### tfs::tfs_mount_format_name_marker [high]
|
||||||
|
- **Expected**: `lf.mount(flash, "/tfs0", 0, 256*1024, {fs="tfs"})` 在 PC 模拟器空白 flash 上应返回 true, mount 后 VFS 即可在 /tfs0 上读写文件
|
||||||
|
- **Actual**: 第一次 `lf.mount` 返回 false, 日志显示 `tfs: format ret=0 read_errors=0` (format 成功) 紧接着 `tfs: open name marker failed` 和 `tfs: format mount failed`, 之后才出现 `tfs: anchor written chunk=0 seq=4096`; 二次 mount 找到 anchor 但仍 `tfs: open name marker failed` 触发 `tfs: probe failed, reformatting`, 再次 `tfs: open name marker failed` 后 `tfs: format or mount failed`
|
||||||
|
- **Source**: `components/little_flash/luat_little_flash_tfs.c:478` (`lf_tfs_write_name_marker` 中 `tfs_open` 失败) 与 `:1226` (`tfs: format mount failed`)
|
||||||
|
- **Repro**:
|
||||||
|
1. 在 PC 上跑 `D:/github/LuatOS/bsp/pc/build/out/luatos-lua.exe` 并加载 vfs_uniform_tfs/scripts
|
||||||
|
2. `mount_tfs.lua` 调 `spi.deviceSetup(1,255,...)` + `lf.init(spidev)` + `lf.mount(flash,"/tfs0",0,256*1024,{fs="tfs"})`
|
||||||
|
3. 观察: format ret=0 → open name marker failed → format mount failed, 紧接着 anchor 写入但 mount 仍失败
|
||||||
|
- **Tags**: fs=tfs, mode=mount, feature=format-name-marker
|
||||||
|
|
||||||
|
### tfs::all_tests_skipped_mount_unavailable [high]
|
||||||
|
- **Expected**: 30 个共享用例应在 /tfs0 上运行, 大部分通过
|
||||||
|
- **Actual**: 30 个用例全部 0/0 跳过, 因为 tfs mount 失败直接 `os.exit(0)`, 没有任何用例被执行
|
||||||
|
- **Source**: 测试 `main.lua` 在 `mount.setup()` 返回 false 时退出; 根因是 tfs mount bug
|
||||||
|
- **Repro**:
|
||||||
|
1. 跑 vfs_uniform_tfs (与上面 tfs_mount_format_name_marker 同一触发条件)
|
||||||
|
2. 日志最后两行: `tfs mount 失败` + `tfs FS 不可用, 退出`
|
||||||
|
- **Tags**: fs=tfs, mode=run, feature=suite-execution
|
||||||
|
|
||||||
|
|
||||||
|
## pgfs
|
||||||
|
|
||||||
|
> pgfs mounted successfully on PC simulator (`/pgfs0`, 256KB partition, virtual NAND
|
||||||
|
> W25N01GVZEIG). However the FTL has very few free blocks at mount time (`next=1, total=2,
|
||||||
|
> bad=0`), and the GC allocator reports `alloc_segment: no free blocks` whenever a write
|
||||||
|
> triggers a new segment allocation. This causes most write/read roundtrip assertions to
|
||||||
|
> fail with 0-byte content. Each test below is a separate symptom of the same root cause
|
||||||
|
> (or, in two cases, an independent semantic bug).
|
||||||
|
|
||||||
|
### pgfs::test_refcount_remove_open_fails [med]
|
||||||
|
- **Expected**: 打开中的文件不应被 os.remove 删除 (refcount 应阻止 remove)
|
||||||
|
- **Actual**: os.remove 成功了 (pgfs 直接删除了正在被读取的文件)
|
||||||
|
- **Source**: `components/pgfs/luat_pgfs_posix.c` (remove 路径未检查 refcount, 沿用 lfs2 的旧语义)
|
||||||
|
- **Repro**:
|
||||||
|
1. `io.open("/pgfs0/vfs_refcount_rm.txt", "wb")` 然后 close
|
||||||
|
2. `f = io.open("/pgfs0/vfs_refcount_rm.txt", "r")`
|
||||||
|
3. `os.remove("/pgfs0/vfs_refcount_rm.txt")` -- 期望失败, 实际成功
|
||||||
|
4. `f:close()`
|
||||||
|
- **Tags**: fs=pgfs, mode=read+remove, feature=refcount
|
||||||
|
|
||||||
|
### pgfs::test_meta_rename_overwrite [low]
|
||||||
|
- **Expected**: rename 覆盖已存在的目标文件应成功 (POSIX 行为)
|
||||||
|
- **Actual**: rename 失败, 目标文件保持旧内容
|
||||||
|
- **Source**: `components/pgfs/luat_pgfs_posix.c` rename 实现 (未先 unlink 目标)
|
||||||
|
- **Repro**:
|
||||||
|
1. `io.mkdir("/pgfs0/d")`
|
||||||
|
2. 创 `/pgfs0/d/from.txt` (内容 "new") 和 `/pgfs0/d/to.txt` (内容 "old")
|
||||||
|
3. `os.rename("/pgfs0/d/from.txt", "/pgfs0/d/to.txt")` -- 期望成功, 实际失败
|
||||||
|
- **Tags**: fs=pgfs, mode=rename, feature=metadata
|
||||||
|
|
||||||
|
### pgfs::test_basic_write_read_roundtrip [high]
|
||||||
|
- **Expected**: 写入 "hello" 后读取应得到 "hello"
|
||||||
|
- **Actual**: 读出为空字符串 (write 静默失败, 文件大小为 0)
|
||||||
|
- **Source**: `components/pgfs/pgfs_alloc_gc.c:78` `alloc_segment: no free blocks`
|
||||||
|
+ `components/pgfs/luat_pgfs_posix.c` (write 路径未检测 segment 分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. mount pgfs (256KB)
|
||||||
|
2. `f = io.open("/pgfs0/x.txt", "wb"); f:write("hello"); f:close()`
|
||||||
|
3. `f = io.open("/pgfs0/x.txt", "rb"); f:read("*a")` -- 期望 "hello", 实际 ""
|
||||||
|
- **Tags**: fs=pgfs, mode=wb/rb, feature=write-data-loss
|
||||||
|
|
||||||
|
### pgfs::test_basic_write_read_large [high]
|
||||||
|
- **Expected**: 写入 64KB 数据后读回应得到 65536 字节
|
||||||
|
- **Actual**: 读出 0 字节 (write 静默失败, 因 segment 分配失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (FTL 没有空闲块)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/big.bin", "wb"); f:write(<64KB>); f:close()`
|
||||||
|
2. `io.open("/pgfs0/big.bin", "rb"):read("*a")` -- 期望 65536 字节, 实际 0
|
||||||
|
- **Tags**: fs=pgfs, mode=wb/rb, feature=large-write-data-loss
|
||||||
|
|
||||||
|
### pgfs::test_edge_block_size_boundary [high]
|
||||||
|
- **Expected**: 4096 字节精确写入读回后, 大小和内容完全一致
|
||||||
|
- **Actual**: 读出 0 字节 (page-aligned 4KB 写入也静默失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (FTL 没有空闲块)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/block.bin", "wb"); f:write(<4096 bytes>); f:close()`
|
||||||
|
2. `f = io.open("/pgfs0/block.bin", "rb"); f:read("*a")` -- 期望 4096, 实际 0
|
||||||
|
- **Tags**: fs=pgfs, mode=wb/rb, feature=block-boundary
|
||||||
|
|
||||||
|
### pgfs::test_basic_seek_tell [high]
|
||||||
|
- **Expected**: 写入 100 字节, seek('set', 50) 后 tell() 返回 50, 读出第 51 字节 = 50
|
||||||
|
- **Actual**: seek() 返回 0, read 返回空 (文件为 0 字节, write 静默失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.bin", "wb"); f:write(<100 bytes>); f:close()`
|
||||||
|
2. `f = io.open("/pgfs0/x.bin", "rb"); f:seek("set", 50); print(f:seek())` -- 期望 50, 实际 0
|
||||||
|
- **Tags**: fs=pgfs, mode=rb, feature=seek-data-loss
|
||||||
|
|
||||||
|
### pgfs::test_basic_seek_end [high]
|
||||||
|
- **Expected**: 写入 100 字节后 seek('end') 给出位置 100
|
||||||
|
- **Actual**: seek() 返回 0 (文件为空, write 失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.bin", "wb"); f:write("x"*100); f:close()`
|
||||||
|
2. `f = io.open("/pgfs0/x.bin", "rb"); f:seek("end"); print(f:seek())` -- 期望 100, 实际 0
|
||||||
|
- **Tags**: fs=pgfs, mode=rb, feature=seek-end
|
||||||
|
|
||||||
|
### pgfs::test_basic_seek_cur [high]
|
||||||
|
- **Expected**: seek('end') 后 seek('cur', -10) 给出位置 90
|
||||||
|
- **Actual**: seek() 返回 0 (文件为空, write 失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.bin", "wb"); f:write("x"*100); f:close()`
|
||||||
|
2. `f = io.open("/pgfs0/x.bin", "rb"); f:seek("end"); f:seek("cur", -10); print(f:seek())`
|
||||||
|
-- 期望 90, 实际 0
|
||||||
|
- **Tags**: fs=pgfs, mode=rb, feature=seek-cur
|
||||||
|
|
||||||
|
### pgfs::test_meta_fsize [high]
|
||||||
|
- **Expected**: 写入 1234 字节, fs.fsize 应返回 1234
|
||||||
|
- **Actual**: fs.fsize 返回 0 (write 静默失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.bin", "wb"); f:write("Z"*1234); f:close()`
|
||||||
|
2. `fs.fsize("/pgfs0/x.bin")` -- 期望 1234, 实际 0
|
||||||
|
- **Tags**: fs=pgfs, mode=wb, feature=fsize
|
||||||
|
|
||||||
|
### pgfs::test_meta_rename_file [high]
|
||||||
|
- **Expected**: rename a->b 应成功, 之后 b 存在且内容是 "data-a"
|
||||||
|
- **Actual**: rename 返回 err=2 (源文件不存在 / 写入失败, 链式失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (写入失败导致源文件未创建, rename 报 ENOENT)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/a.txt", "wb"); f:write("data-a"); f:close()`
|
||||||
|
2. `os.rename("/pgfs0/a.txt", "/pgfs0/b.txt")` -- 期望 true, 实际 err=2
|
||||||
|
- **Tags**: fs=pgfs, mode=rename, feature=metadata-chain-failure
|
||||||
|
|
||||||
|
### pgfs::test_basic_append_mode [high]
|
||||||
|
- **Expected**: "foo" + append "bar" 后读出 "foobar"
|
||||||
|
- **Actual**: 读出空字符串 (write 静默失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.txt", "wb"); f:write("foo"); f:close()`
|
||||||
|
2. `f = io.open("/pgfs0/x.txt", "ab"); f:write("bar"); f:close()`
|
||||||
|
3. `io.open("/pgfs0/x.txt", "rb"):read("*a")` -- 期望 "foobar", 实际 ""
|
||||||
|
- **Tags**: fs=pgfs, mode=ab, feature=append-data-loss
|
||||||
|
|
||||||
|
### pgfs::test_posix_mode_w_plus [high]
|
||||||
|
- **Expected**: "w+" 打开后 write("xyz") 再 seek(0) read 应得到 "xyz"
|
||||||
|
- **Actual**: read 返回空字符串 (write 静默失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.txt", "w+"); f:write("xyz"); f:seek("set", 0); print(f:read("*a"))`
|
||||||
|
-- 期望 "xyz", 实际 ""
|
||||||
|
- **Tags**: fs=pgfs, mode=w+, feature=mode-flags
|
||||||
|
|
||||||
|
### pgfs::test_posix_mode_r_plus [high]
|
||||||
|
- **Expected**: "r+" 打开已有文件后 write + seek + read 应得到原长度 (首字节被覆盖)
|
||||||
|
- **Actual**: read 返回 0 字节字符串 (写时静默失败, 文件被截断/清空)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败) +
|
||||||
|
`components/pgfs/luat_pgfs_posix.c` (r+ 模式 open 后的截断/清空行为)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.txt", "wb"); f:write("initial"); f:close()`
|
||||||
|
2. `f = io.open("/pgfs0/x.txt", "r+"); f:write("X"); f:seek("set", 0); print(f:read("*a"))`
|
||||||
|
-- 期望 "Xniti..."(7 字节), 实际 ""
|
||||||
|
- **Tags**: fs=pgfs, mode=r+, feature=mode-flags
|
||||||
|
|
||||||
|
### pgfs::test_posix_binary_text_same [high]
|
||||||
|
- **Expected**: 写入 0x0A 0x0D 0x00 0xFF 后 read(4) 读出 4 字节
|
||||||
|
- **Actual**: read(4) 返回 nil (文件为空, write 静默失败)
|
||||||
|
- **Source**: 同 test_basic_write_read_roundtrip (根因 = FTL 段分配失败)
|
||||||
|
- **Repro**:
|
||||||
|
1. `f = io.open("/pgfs0/x.bin", "wb"); f:write("\x0A\x0D\x00\xFF"); f:close()`
|
||||||
|
2. `f = io.open("/pgfs0/x.bin", "rb"); f:read(4)` -- 期望 4 字节, 实际 nil
|
||||||
|
- **Tags**: fs=pgfs, mode=rb, feature=binary-mode
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
# netdrv L2TPv2 客户端驱动设计文档
|
||||||
|
|
||||||
|
> 适用范围:在 LuatOS `netdrv` 框架下新增 L2TPv2(RFC 2661)客户端驱动(LAC),
|
||||||
|
> 当前首期落地 PC 模拟器(`bsp/pc`),硬件 BSP 按需开启 `LUAT_USE_NETDRV_L2TP`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 背景与目标
|
||||||
|
|
||||||
|
LuatOS 需要在内网/办公网场景下提供「二层隧道 + PPP 拨号」的能力,典型形态是
|
||||||
|
接入企业 LNS(L2TP Network Server)获得内网 IP 并访问内网资源。
|
||||||
|
|
||||||
|
需求边界(与 lwip 自带 `pppol2tp.c` 的能力边界一致):
|
||||||
|
|
||||||
|
- ✅ L2TPv2 客户端(LAC),PPP over L2TP(UDP 隧道)
|
||||||
|
- ✅ PPP 认证:PAP + CHAP(MD5);可选 L2TP 隧道共享密钥认证(`l2tp_secret`)
|
||||||
|
- ❌ LNS(服务端)、L2TPv3、隧道切换、多隧道/多会话
|
||||||
|
- ❌ MSCHAPv2 / MPPE / EAP / CCP
|
||||||
|
|
||||||
|
核心约束:**外层 UDP 传输一律走 LuatOS network adapter**(`network_ctrl_t` UDP
|
||||||
|
模式,与 OpenVPN 客户端一致),不直接创建 lwip `udp_pcb`。这样 VPN 虚拟网卡与
|
||||||
|
底层物理网卡(4G/WiFi/ETH/CH390H)完全解耦,底层可以是任意 netdrv 适配器。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 总体设计
|
||||||
|
|
||||||
|
```
|
||||||
|
Lua 脚本 (netdrv.setup / netdrv.ready / socket.*)
|
||||||
|
|
|
||||||
|
+------------------v------------------+
|
||||||
|
| luat_netdrv_l2tp.c (胶水层) |
|
||||||
|
| setup/ctrl(UPDOWN)/dhcp/debug |
|
||||||
|
| PPP 状态回调 -> net_lwip2 链路状态 + |
|
||||||
|
| IP_READY / IP_LOSE 事件 |
|
||||||
|
+------------------+------------------+
|
||||||
|
|
|
||||||
|
+------------------v------------------+
|
||||||
|
| components/network/l2tp/src (核心) |
|
||||||
|
| - l2tp_client.c: 生命周期/定时器/传输 |
|
||||||
|
| - l2tp_ctrl.c: 控制面 (SCCRQ..StopCCN,|
|
||||||
|
| ns/nr 窗口, 定时重传) |
|
||||||
|
| - l2tp_ppp.c: PPP 数据面封装 + 状态回调|
|
||||||
|
+-------+---------------+------------+
|
||||||
|
| |
|
||||||
|
network_ctrl_t (UDP) vendored lwIP PPP 栈
|
||||||
|
luat_network_adapter l2tp/src/ppp/*.c
|
||||||
|
| |
|
||||||
|
底层物理网卡(4G/WiFi/ETH) ppp_pcb / netif
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.1 分层
|
||||||
|
|
||||||
|
1. **胶水层**(`luat_netdrv_l2tp.c`):把 L2TP 客户端包装成标准 `luat_netdrv_t`
|
||||||
|
驱动,负责配置拷贝、`LUAT_NETDRV_CTRL_UPDOWN` 控制、链路状态上报。
|
||||||
|
2. **客户端核心**(`components/network/l2tp/src/`,按协议层拆为三个文件):
|
||||||
|
- `l2tp_client.c`:生命周期/状态机/定时器/网络适配器传输
|
||||||
|
(`l2tp_udp_send`、`l2tp_timeout`、重连退避、`l2tp_client_*` API);
|
||||||
|
- `l2tp_ctrl.c`:L2TPv2 控制面从 lwip22 `netif/ppp/pppol2tp.c` 移植,
|
||||||
|
仅替换 UDP 收发为 `network_tx/network_rx`,去掉 `udp_pcb` 与传输
|
||||||
|
netif 参数(线格式/AVP 构造解析、ns/nr 窗口、定时重传);
|
||||||
|
- `l2tp_ppp.c`:PPP 会话运行在 vendor 的 lwIP PPP 栈上,
|
||||||
|
`struct link_callbacks` 的 `write/netif_output` 走 L2TP 数据封装,
|
||||||
|
并处理 `ppp_status_cb` 链路状态回调。
|
||||||
|
- 跨文件原型在 `components/network/l2tp/include/l2tp/`(`l2tp_ctrl.h` /
|
||||||
|
`l2tp_ppp.h`),公共客户端 API 在 `l2tp/l2tp_client.h`。
|
||||||
|
3. **PPP 栈**(`components/network/l2tp/src/ppp/`):lwIP 2.2.1
|
||||||
|
`ppp.c/lcp.c/ipcp.c/auth.c/fsm.c/upap.c/chap-new.c/chap-md5.c/magic.c/utils.c`
|
||||||
|
的 vendor 副本(保留 BSD 许可头,注明来源),由构建系统按需编译。
|
||||||
|
|
||||||
|
### 2.2 线程模型
|
||||||
|
|
||||||
|
- `create/connect/close` 与 `ppp_input` 的投递统一 marshal 到 lwip core 线程
|
||||||
|
(`tcpip_callback_with_block`,模式同 WG 驱动的 `exec_netif_add`);
|
||||||
|
- network adapter 回调(运行在 adapter 任务/Lua 主线程)内**只做数据拷贝**,
|
||||||
|
通过 `tcpip_callback` 投递给 tcpip 线程,PPP 状态机绝不在 adapter 线程执行;
|
||||||
|
- `transport_err` 标志由 adapter 回调置位,由 500ms 周期定时器(tcpip 线程)
|
||||||
|
消费,避免跨线程直接操作 PPP 状态机。
|
||||||
|
|
||||||
|
### 2.3 就绪信号
|
||||||
|
|
||||||
|
PPP 的 `sifup()` 在 `np_up()` 把 phase 推进到 `PPP_PHASE_RUNNING` **之前**就会
|
||||||
|
回调 `link_status_cb(PPPERR_NONE)`,因此驱动的 ready 判定使用 `ppp->if4_up`
|
||||||
|
(`sifup` 内部先置位再回调),而不是 phase==RUNNING,否则会出现一次误报
|
||||||
|
`IP_LOSE` 且不再上报 `IP_READY` 的竞态。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 方案选择与取舍
|
||||||
|
|
||||||
|
### 3.1 传输层:network adapter UDP 而非 lwip `udp_pcb`
|
||||||
|
|
||||||
|
| 方案 | 结论 |
|
||||||
|
|---|---|
|
||||||
|
| 直接创建 lwip `udp_pcb` 走底层 netif | 与 4G/WiFi/ETH 等 LuatOS 自有适配器耦合,需要额外的 netif 路由/ARP 处理,硬件差异大 |
|
||||||
|
| `network_ctrl_t` UDP(本方案) | 与 OpenVPN 客户端一致,底层网卡即插即用;天然支持「LNS 从随机源端口应答」(posix 适配器不 connect UDP socket) |
|
||||||
|
|
||||||
|
代价:多一次 adapter 层数据拷贝,VPN 隧道吞吐受 adapter 缓冲限制
|
||||||
|
(`network_tx/rx` 单包缓冲,L2TP 数据面当前使用 1600B 栈缓冲)。
|
||||||
|
|
||||||
|
### 3.2 PPP 栈:vendor lwip22 源码 vs 自己实现
|
||||||
|
|
||||||
|
lwip22 自带完整的 `ppp.c` 系列(LCP/IPCP/PAP/CHAP/FSM/魔法数),直接 vendor
|
||||||
|
到 `components/network/l2tp/src/ppp/` 并配套两个移植补丁:
|
||||||
|
|
||||||
|
1. **`ppp_pcb` 改用 `mem_malloc/mem_free`**:本仓库 lwip22 的 `memp_std.h`
|
||||||
|
裁剪掉了 PPP/PPPOL2TP 内存池,vendor 副本内自行 `LWIP_MEMPOOL_DECLARE`
|
||||||
|
可以编译,但为减少静态池开销并贴合本仓库约定,改为堆分配。
|
||||||
|
2. **MD5 走外部 mbedTLS**:`LWIP_USE_EXTERNAL_MBEDTLS=1` 把 `lwip_md5_*`
|
||||||
|
映射到 LuatOS 已有 mbedtls(`MBEDTLS_MD5_C` 在 PC 与硬件配置均已启用),
|
||||||
|
不再编译 lwip 内嵌 PolarSSL 副本。
|
||||||
|
|
||||||
|
### 3.3 编译选项覆盖:`luat_ppp_opts_override.h`
|
||||||
|
|
||||||
|
`bsp/pc/include/lwipopts.h` 写死 `PPP_SUPPORT 0`,且会**无条件重定义**,因此
|
||||||
|
per-file 命令行宏会被覆盖;同时 `ppp_opts.h` 的 `#if PPP_SUPPORT` 块在 override
|
||||||
|
生效之前求值(其中定义的 FSM/UPAP/CHAP/LCP 超时、`MAXNAMELEN/MAXSECRETLEN`、
|
||||||
|
`PPP_MRU`、`PPP_IPV4_SUPPORT` 等全部缺失)。
|
||||||
|
|
||||||
|
解决办法:xmake 仅对 vendor PPP 文件与 L2TP 客户端文件附加
|
||||||
|
`LUAT_L2TP_PPP_BUILD=1`,并在 `ppp_opts.h` 之后强制 include
|
||||||
|
`luat_ppp_opts_override.h`,统一恢复特性集:
|
||||||
|
|
||||||
|
```
|
||||||
|
PPP_SUPPORT=1, PPPOL2TP/PPPOS/PPPOE=0, LWIP_PPP_API=0,
|
||||||
|
PAP_SUPPORT=1, CHAP_SUPPORT=1, MSCHAP/EAP/CCP/MPPE/VJ/LQR=0,
|
||||||
|
PPP_IPV4_SUPPORT=(LWIP_IPV4), PPP_IPV6_SUPPORT=0, PPP_SERVER=0,
|
||||||
|
LWIP_USE_EXTERNAL_MBEDTLS=1, MEMP_NUM_PPP_PCB=1
|
||||||
|
```
|
||||||
|
|
||||||
|
配套提供 `components/network/l2tp/include/ppp_settings.h`:`lwip22/include/arch/cc.h`
|
||||||
|
无条件定义 `PPP_INCLUDE_SETTINGS_HEADER`,但仓库从未提供该 port 头文件
|
||||||
|
(PPP 此前从未编译),本文件为空实现(选项全部走 override 头)。
|
||||||
|
|
||||||
|
> 注意:这些宏只作用于 vendor PPP 文件与 L2TP 客户端文件,**不是全局宏**。
|
||||||
|
> 全局开启 `PPP_SUPPORT` 会触发 `lwip22/core/init.c` 的
|
||||||
|
> `#error "PPP_SUPPORT needs at least one of PPPOS_SUPPORT..."` 编译检查。
|
||||||
|
|
||||||
|
### 3.4 L2TP 控制面:自实现(`PPPOL2TP_SUPPORT=0`)
|
||||||
|
|
||||||
|
lwip 的 `pppol2tp.c` 与 `udp_pcb` 强耦合,且其头文件要求
|
||||||
|
`PPPOL2TP_SUPPORT=1`。本驱动把控制面逻辑平移到
|
||||||
|
`l2tp_ctrl.c`(常量、AVP 构造/解析、ns/nr 窗口、定时重传均照搬),
|
||||||
|
传输改为 adapter 调用,因此 vendor PPP 文件以 `PPPOL2TP_SUPPORT=0` 编译,
|
||||||
|
避免 `pppol2tp.c` 参与编译。
|
||||||
|
|
||||||
|
### 3.5 认证与隧道密钥
|
||||||
|
|
||||||
|
- `ppp_set_auth(ppp, PPPAUTHTYPE_ANY, user, passwd)`:PAP/CHAP-MD5 均可;
|
||||||
|
- `l2tp_secret` 非空时按 RFC 2661 在 SCCRQ/SCCRP/SCCCN 中携带
|
||||||
|
Challenge / Challenge-Response AVP(MD5(消息类型|secret|challenge))。
|
||||||
|
- 认证选项由**对端**在 LCP ConfReq 中提出:lwip 客户端的 LCP ConfReq 本身
|
||||||
|
不携带 auth 选项(`lcp_addci` 使用 gotoptions,客户端侧该位不置位),
|
||||||
|
因此 LNS 必须主动要求认证(真实 LNS 行为一致)。
|
||||||
|
|
||||||
|
### 3.6 断线检测与自动重连
|
||||||
|
|
||||||
|
- **PPP 层**:LCP keepalive(3s 间隔、3 次失败)检测静默断线(对端不响应);
|
||||||
|
对端 StopCCN 在 DATA 阶段不主动断开(沿用 pppol2tp 语义),由 keepalive 兜底。
|
||||||
|
- **传输层**:`EV_NW_RESULT_CLOSE`/`Param1!=0` 置 `transport_err`,500ms 周期
|
||||||
|
定时器消费并触发重连。
|
||||||
|
- 重连策略:指数退避(base 1s,max 60s,可配置),传输离线时按 base 轮询;
|
||||||
|
用户主动 `CTRL_UPDOWN=0` 不重连。
|
||||||
|
- 在线判定使用 setup 时捕获的 `transport_index`,而非运行时默认 adapter:
|
||||||
|
netdrv 虚拟网卡注册后 `network_register_get_default()` 会变成 USERx 自身,
|
||||||
|
若用运行时默认值会导致「传输离线」误判。
|
||||||
|
|
||||||
|
### 3.7 数据面 MTU 与缓冲
|
||||||
|
|
||||||
|
PPP MRU 默认 1450(`L2TP_DEFAULT_MTU`,可用 `l2tp_mtu` 配置);L2TP 数据头 6B
|
||||||
|
(flags + tunnel id + session id)。发送侧把 pbuf 拼成扁平缓冲后走
|
||||||
|
`network_tx`(1600B 栈缓冲),接收侧同样扁平缓冲 -> pbuf -> `ppp_input`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 文件与构建接线
|
||||||
|
|
||||||
|
### 4.1 新增/修改文件
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| `components/network/l2tp/include/l2tp/l2tp_client.h` | L2TP 客户端对外结构/API、协议常量 |
|
||||||
|
| `components/network/l2tp/include/l2tp/l2tp_ctrl.h` | 控制面跨文件原型(内部) |
|
||||||
|
| `components/network/l2tp/include/l2tp/l2tp_ppp.h` | PPP 胶水跨文件原型(内部) |
|
||||||
|
| `components/network/l2tp/src/l2tp_client.c` | 客户端核心(生命周期/定时器/传输/重连) |
|
||||||
|
| `components/network/l2tp/src/l2tp_ctrl.c` | 控制面(线格式/AVP/ns-nr 窗口/定时重传) |
|
||||||
|
| `components/network/l2tp/src/l2tp_ppp.c` | PPP 胶水(link_callbacks + 状态回调) |
|
||||||
|
| `components/network/netdrv/include/luat_netdrv_l2tp.h` | netdrv 胶水层头文件 |
|
||||||
|
| `components/network/l2tp/src/luat_netdrv_l2tp.c` | netdrv 胶水层(setup/ctrl/dhcp/debug/状态回调) |
|
||||||
|
| `components/network/l2tp/src/ppp/*.c` | vendored lwip 2.2.1 PPP 源码(10 个文件) |
|
||||||
|
| `components/network/l2tp/src/ppp/luat_ppp_opts_override.h` | PPP 编译选项覆盖 |
|
||||||
|
| `components/network/l2tp/include/ppp_settings.h` | lwip `PPP_INCLUDE_SETTINGS_HEADER` port 钩子 |
|
||||||
|
| `components/network/netdrv/include/luat_netdrv.h` | `luat_netdrv_l2tp_conf_t` + `conf.l2tp_conf` |
|
||||||
|
| `components/network/netdrv/include/luat_netdrv_drv.h` | `LUAT_NETDRV_IMPL_L2TP 6` + setup 声明 |
|
||||||
|
| `components/network/netdrv/src/luat_netdrv.c` | setup 分发新增 L2TP 分支 |
|
||||||
|
| `components/network/netdrv/binding/luat_lib_netdrv.c` | `l2tp_*` 配置解析 + `netdrv.L2TP` 常量 |
|
||||||
|
| `bsp/pc/include/luat_conf_bsp.h` | `LUAT_USE_NETDRV_L2TP 1` |
|
||||||
|
| `bsp/pc/include/lwipopts.h` | `MEMP_NUM_SYS_TIMEOUT` 17->24(PPP/L2TP 定时器预算) |
|
||||||
|
| `bsp/pc/xmake.lua` | lwip22 PPP 源码剔除 + vendor PPP 编译 |
|
||||||
|
| `testcase/unit/net/netdrv_l2tp_basic/` | 测试套件 + Python mock LNS |
|
||||||
|
|
||||||
|
### 4.2 xmake 接线要点(`bsp/pc/xmake.lua`)
|
||||||
|
|
||||||
|
```lua
|
||||||
|
-- 剔除 lwip22 自带 PPP(避免与 vendor 副本重复编译)
|
||||||
|
remove_files(lwip_path .. "netif/ppp/**.c")
|
||||||
|
|
||||||
|
-- netdrv 核心(VPN 子模块已拆出为独立目录)
|
||||||
|
add_files(luatos .. "components/network/netdrv/**.c")
|
||||||
|
|
||||||
|
-- L2TP 子模块:头文件路径 + vendor PPP + 客户端按文件附加编译宏
|
||||||
|
add_includedirs(luatos .. "components/network/l2tp/include")
|
||||||
|
add_includedirs(luatos .. "components/network/l2tp/src/ppp")
|
||||||
|
add_files(luatos .. "components/network/l2tp/src/ppp/*.c",
|
||||||
|
{defines = {"LUAT_L2TP_PPP_BUILD=1"}})
|
||||||
|
add_files(luatos .. "components/network/l2tp/src/l2tp_client.c",
|
||||||
|
luatos .. "components/network/l2tp/src/l2tp_ctrl.c",
|
||||||
|
luatos .. "components/network/l2tp/src/l2tp_ppp.c",
|
||||||
|
{defines = {"LUAT_L2TP_PPP_BUILD=1"}})
|
||||||
|
add_files(luatos .. "components/network/l2tp/src/luat_netdrv_l2tp.c")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 Lua 用法
|
||||||
|
|
||||||
|
```lua
|
||||||
|
netdrv.setup(socket.LWIP_USER1, netdrv.L2TP, {
|
||||||
|
l2tp_remote_ip = "10.0.0.1", -- 必填,LNS IP(仅 IP 字面量,同 OpenVPN)
|
||||||
|
l2tp_remote_port = 1701, -- 默认 1701
|
||||||
|
l2tp_username = "user", -- 可选
|
||||||
|
l2tp_password = "pass", -- 可选
|
||||||
|
l2tp_secret = nil, -- 可选,L2TP 隧道共享密钥
|
||||||
|
l2tp_mtu = 1450, -- 可选,默认 1450
|
||||||
|
l2tp_retry_enable = true, -- 可选,失败自动重连
|
||||||
|
l2tp_retry_base_ms = 1000,
|
||||||
|
l2tp_retry_max_ms = 60000,
|
||||||
|
})
|
||||||
|
-- 就绪判断沿用 netdrv.ready(id) 与 IP_READY/IP_LOSE 事件
|
||||||
|
-- netdrv.dhcp 对该网卡返回 -1(IP 由 IPCP 下发)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 测试方案
|
||||||
|
|
||||||
|
PC 模拟器 + Python mock LNS(`testcase/unit/net/netdrv_l2tp_basic/mock_lns.py`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# pap 场景
|
||||||
|
python testcase/unit/net/netdrv_l2tp_basic/mock_lns.py --port 1701 --auth pap --log &
|
||||||
|
LUAT_L2TP_TEST=pap build/out/luatos-lua.exe \
|
||||||
|
../../testcase/common/scripts/ ../../testcase/unit/net/netdrv_l2tp_basic/scripts/
|
||||||
|
|
||||||
|
# chap / reject / reconnect 场景分别用:
|
||||||
|
# --port 1702 --auth chap (LUAT_L2TP_TEST=chap)
|
||||||
|
# --port 1703 --reject-auth (LUAT_L2TP_TEST=reject)
|
||||||
|
# --port 1701 --drop-after 8 (LUAT_L2TP_TEST=reconnect)
|
||||||
|
```
|
||||||
|
|
||||||
|
四个场景均已实测通过(`### OVERALL_PASS ###`):
|
||||||
|
|
||||||
|
| 场景 | 验证点 |
|
||||||
|
|---|---|
|
||||||
|
| pap | 隧道建立 + PAP 认证 + IPCP 下发 192.168.8.2 + 隧道内 TCP echo |
|
||||||
|
| chap | CHAP-MD5 认证(挑战/响应校验)+ 同样链路验证 |
|
||||||
|
| reject | 密码错误 -> 认证失败、一直 not ready |
|
||||||
|
| reconnect | 会话中途断开 -> `IP_LOSE` -> 自动重连成功 |
|
||||||
|
|
||||||
|
回归:`netdrv_evt_pkg`(19/19)、`netdrv_lwip_intercept_basic`(3/3)通过;
|
||||||
|
PC 增量编译 `Build completed successfully`,无新增告警。
|
||||||
|
|
||||||
|
### mock LNS 实现要点(实测中踩过的坑,写在这里供后续参考)
|
||||||
|
|
||||||
|
- 每端第一条控制消息 NS 从 **0** 开始(SCCRP 的 NS 必须为 0);
|
||||||
|
- ZLB 不消耗 NS 槽位:其 NS 与下一条真实消息相同,接收方不推进 `peer_ns`;
|
||||||
|
- 数据包隧道/会话 ID 必须用**客户端分配**的 ID(lwip 按 `remote_*_id` 校验);
|
||||||
|
- LCP/IPCP 是对称协议:服务端必须发送自己的 ConfReq,否则客户端 FSM 停在
|
||||||
|
ACKRCVD 并重传;
|
||||||
|
- LCP Echo-Reply 必须携带**服务端自己的 magic**,lwip 会拒绝携带自身 magic
|
||||||
|
的 Echo-Reply(视为回环);
|
||||||
|
- CHAP 校验用的 secret 是 PPP 密码(客户端 `settings.passwd`),与 L2TP 隧道
|
||||||
|
`l2tp_secret` 无关;
|
||||||
|
- IPCP ConfNak 的 length 字段必须等于实际负载长度(含 DNS 选项时容易写错,
|
||||||
|
会导致客户端只解析到部分选项)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 尚待完善之处
|
||||||
|
|
||||||
|
1. **硬件 BSP 使能**:首期只落地 PC。硬件 BSP 需要确认 lwip 导出
|
||||||
|
`pbuf/netif/sys/ip4_input` 等符号;若未导出 `ip4_input`,在
|
||||||
|
`LUAT_USE_NETDRV_LWIP_ARP` 下把 vendor `ppp.c` 的调用改走
|
||||||
|
`luat_netdrv_ip4_input`。硬件侧建议在正式发布前跑一遍 mock LNS 验证。
|
||||||
|
2. **IPCP DNS 下发**:PC 当前 `LWIP_DNS=0`,`ppp.c` 的 `sdns()` 未编译,
|
||||||
|
IPCP 携带的 DNS 选项会被忽略。后续可评估启用 `LWIP_DNS` 或由驱动把
|
||||||
|
IPCP 协商出的 DNS 写入 `net_lwip2` 的 `set_dns_server`。
|
||||||
|
3. **LNS 域名支持**:`l2tp_remote_ip` 仅支持 IP 字面量;可通过传输 adapter
|
||||||
|
的 DNS 能力扩展域名解析(同 OpenVPN 现状)。
|
||||||
|
4. **隧道认证自动化测试**:`l2tp_secret` 的 Challenge/Challenge-Response
|
||||||
|
流程已实现,mock LNS 也支持 `--secret`,但当前四场景未覆盖,待补测试。
|
||||||
|
5. **认证/加密能力扩展**:MSCHAPv2、MPPE(CCP)、EAP 需要额外 vendor
|
||||||
|
`chap_ms.c/ccp.c/mppe.c/eap.c` 并调整编译选项,属后续需求。
|
||||||
|
6. **多实例**:当前按单会话设计(`MEMP_NUM_PPP_PCB=1`),多隧道/多会话、
|
||||||
|
隧道切换未支持。
|
||||||
|
7. **资源释放细节**:配置字符串(用户名/密码/密钥)在客户端生命周期内保留,
|
||||||
|
用户停止后不释放(便于再次启动);PPP 会话若处于 `TERMINATE` 进行中,
|
||||||
|
`ppp_free` 会等待状态归位,极端时序下可能保留 pcb 等待下一次 start 清理。
|
||||||
|
8. **定时器预算**:`MEMP_NUM_SYS_TIMEOUT` 由 17 提到 24 以容纳
|
||||||
|
PPP/L2TP 的 LCP-FSM + LCP-Echo + 认证 + IPCP-FSM + L2TP 控制/周期定时器;
|
||||||
|
硬件侧若同时跑 OpenVPN/WG,需按实际固件核对预算。
|
||||||
|
9. **CI 集成**:mock LNS 依赖本机 UDP 端口,目前是手工编排;后续可封装成
|
||||||
|
CI job(起 LNS -> 跑模拟器 -> 校验 OVERALL_PASS)。
|
||||||
|
10. **文档与 API 注释**:`luat_lib_netdrv.c` 已补充 `netdrv.L2TP` 用法注释,
|
||||||
|
建议后续在 `script/` 侧补充完整 usage.md/示例。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 相关文档
|
||||||
|
|
||||||
|
- `components/network/lwip22/netif/ppp/pppol2tp.c`(控制面移植来源)
|
||||||
|
- `components/network/lwip22/include/netif/ppp/ppp_opts.h`(选项语义)
|
||||||
|
- RFC 2661(Layer Two Tunneling Protocol "L2TP")
|
||||||
|
- `testcase/unit/net/netdrv_l2tp_basic/mock_lns.py`(测试用 LNS 参考实现)
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
# mobile RF 校准 rfa 重构实施计划
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans
|
||||||
|
>
|
||||||
|
> **Status**: ✅ 已完成 5 阶段 6 commit (2026-06-13, branch: `mobile-rf-test-rewrite`)
|
||||||
|
|
||||||
|
**Goal:** 把 `mobile` 库的 RF 校准功能从 C 端硬编码改为 Thin C / Fat Lua 架构, 沿用 `luat_mobile_rf_test_*` 前缀扩展
|
||||||
|
**Architecture:** Thin C (5 函数) / Fat Lua (新模块 `rfa.*`)
|
||||||
|
**Tech Stack:** C (luat_mobile_*) + Lua 5.3 + xmake + MSVC
|
||||||
|
|
||||||
|
**Worktree:** `D:\github\LuatOS\.worktrees\mobile-rf-test-rewrite` (branch `mobile-rf-test-rewrite`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
### New (Create)
|
||||||
|
- `script/libs/rfa.lua` — Lua 端 rfa.* 模块
|
||||||
|
- `testcase/utest/drv/mobile_rfa_basic/metas.json`
|
||||||
|
- `testcase/utest/drv/mobile_rfa_basic/scripts/main.lua`
|
||||||
|
- `testcase/utest/drv/mobile_rfa_basic/scripts/mobile_rfa_test.lua` — 13 case
|
||||||
|
- `tools/rfa_com0com/at_server_main/main.lua`
|
||||||
|
- `tools/rfa_com0com/setup_com0com_pair.ps1`
|
||||||
|
- `tools/rfa_com0com/test_rfa_com0com.py`
|
||||||
|
- `components/mobile/README_rfa.md`
|
||||||
|
- `docs/superpowers/specs/2026-06-13-mobile-rf-test-redesign-design.md`
|
||||||
|
- `docs/superpowers/plans/2026-06-13-mobile-rf-test-redesign.md` (本文件)
|
||||||
|
|
||||||
|
### Modify
|
||||||
|
- `components/mobile/luat_mobile.h` — 改 rf_test_*, 删 rfcal_*, 加 3 个新函数
|
||||||
|
- `components/mobile/luat_lib_mobile.c` — 改 nst_*, 删 rfcal_*, 加 5 个新绑定
|
||||||
|
- `bsp/pc/port/luat_mobile_pc.c` — 改 rf_test_*, 删 rfcal_*, 加 s_rf_test + 3 个新函数
|
||||||
|
- `components/mobile/luat_mobile_airlink_rpc.c` — 改 rf_test_*, 加 4 个新空桩
|
||||||
|
- `oldmodule/Air780E/demo/rf_test/main.lua` — 加 deprecation 注释
|
||||||
|
|
||||||
|
### Delete
|
||||||
|
- `lua/luat/rfcal_at_server.lua`
|
||||||
|
- `testcase/utest/drv/mobile_rfcal_basic/` (整目录)
|
||||||
|
- `tools/rfcal_com0com/` (整目录)
|
||||||
|
- `components/mobile/README_rfcal.md`
|
||||||
|
- `components/utest/mobile/luat_mobile_rfcal_utest.c`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1: 实化原有 rf_test_* + 新增 5 个新函数 (不删旧的) ✅
|
||||||
|
|
||||||
|
**Files:** `luat_mobile.h`, `luat_mobile_pc.c`, `luat_mobile_airlink_rpc.c`, `luat_lib_mobile.c`
|
||||||
|
|
||||||
|
**Commit:** `refactor(mobile): realize luat_mobile_rf_test_mode/input; add param/imei/set_rx_cb`
|
||||||
|
|
||||||
|
- [x] **Step 1:** `components/mobile/luat_mobile.h` 末尾追加 5 个新函数声明 + key 宏 + rx_cb 结构
|
||||||
|
- [x] **Step 2:** `bsp/pc/port/luat_mobile_pc.c` 顶部加 `s_rf_test` 静态结构
|
||||||
|
- [x] **Step 3:** `luat_mobile_pc.c` 312-319 行替换空桩为实化实现 (调 s_rf_test)
|
||||||
|
- [x] **Step 4:** `luat_mobile_pc.c` 末尾加 4 个新函数 (set_rx_cb / param / imei_get / imei_set)
|
||||||
|
- [x] **Step 5:** `luat_mobile_airlink_rpc.c` 419-427 改空桩, 加 4 个新空桩 (返 -1)
|
||||||
|
- [x] **Step 6:** `luat_lib_mobile.c` 加 5 个新绑定 (rfTestMode/Input/Param/Imei/ImeiSet) 并注册到 reg_mobile
|
||||||
|
- [x] **Step 7:** 编译 `cd bsp/pc && powershell -Command "& '.\build_windows_32bit_msvc.bat'"`
|
||||||
|
- [x] **Step 8:** 烟雾测试 `mobile_rf_test_smoke` 14/14 全过
|
||||||
|
|
||||||
|
## Task 2: 新增 script/libs/rfa.lua + 新 utest 套件 ✅
|
||||||
|
|
||||||
|
**Files:** `script/libs/rfa.lua`, `testcase/utest/drv/mobile_rfa_basic/`
|
||||||
|
|
||||||
|
**Commit:** `feat(lua): add script/libs/rfa.lua state machine + dispatch`
|
||||||
|
|
||||||
|
- [x] **Step 1:** 新建 `script/libs/rfa.lua` (~200 行, 状态机 7 阶段 + 派发表 + 扩展点)
|
||||||
|
- [x] **Step 2:** 新建 `testcase/utest/drv/mobile_rfa_basic/metas.json`
|
||||||
|
- [x] **Step 3:** 新建 `testcase/utest/drv/mobile_rfa_basic/scripts/main.lua`
|
||||||
|
- [x] **Step 4:** 新建 `testcase/utest/drv/mobile_rfa_basic/scripts/mobile_rfa_test.lua` (4 套件, 13 case)
|
||||||
|
- [x] **Step 5:** 跑测试 `./luatos-lua.exe ../../../../testcase/common/scripts/ ../../../../testcase/utest/drv/mobile_rfa_basic/scripts/ ../../../../script/libs/`
|
||||||
|
- [x] **Step 7:** 验证 `### OVERALL_PASS ### mobile_rfa_basic`
|
||||||
|
|
||||||
|
## Task 3: 迁移 com0com 工具 (双轨运行期) ✅
|
||||||
|
|
||||||
|
**Files:** `tools/rfa_com0com/` (新), `tools/rfcal_com0com/` (保留到阶段 4)
|
||||||
|
|
||||||
|
**Commit:** `feat(com0com): migrate rfcal_com0com → rfa_com0com (双轨运行期)`
|
||||||
|
|
||||||
|
- [x] **Step 1:** `mkdir -p tools/rfa_com0com/at_server_main`
|
||||||
|
- [x] **Step 2:** 复制 `setup_com0com_pair.ps1` 到 `tools/rfa_com0com/`
|
||||||
|
- [x] **Step 3:** 新建 `tools/rfa_com0com/at_server_main/main.lua` (改用 rfa, 内部 mobile.rfTest* 桥, 通过 script/libs 加载)
|
||||||
|
- [x] **Step 4:** 新建 `tools/rfa_com0com/test_rfa_com0com.py` (复制 + 改名 + 注释更新)
|
||||||
|
- [x] **Step 5:** 验证 `tools/rfcal_com0com/` 仍存在 (双轨)
|
||||||
|
|
||||||
|
## Task 4: 删旧代码 (rfcal_* + nst_* + 旧 utest/demos) ✅
|
||||||
|
|
||||||
|
**Files:** 多文件删除
|
||||||
|
|
||||||
|
**Commit:** `refactor(mobile): remove old luat_mobile_rfcal_* and nst_*`
|
||||||
|
|
||||||
|
- [x] **Step 1:** `luat_mobile.h` 删 851-917 整段 (rfcal_* 7 个声明)
|
||||||
|
- [x] **Step 2:** `luat_mobile_pc.c` 删 493-615 整段 (rfcal_* PC 仿真实现)
|
||||||
|
- [x] **Step 3:** `luat_lib_mobile.c` 删 nst_* + rfcal_* + l_mobile_utest 块, reg_mobile 表对应项
|
||||||
|
- [x] **Step 4:** 新建 `components/mobile/README_rfa.md` (替代 README_rfcal.md)
|
||||||
|
- [x] **Step 5:** 删 `lua/luat/rfcal_at_server.lua`
|
||||||
|
- [x] **Step 6:** 删 `components/mobile/README_rfcal.md`
|
||||||
|
- [x] **Step 7:** 删 `components/utest/mobile/luat_mobile_rfcal_utest.c`
|
||||||
|
- [x] **Step 8:** 删 `testcase/utest/drv/mobile_rfcal_basic/` (整目录)
|
||||||
|
- [x] **Step 9:** 删 `tools/rfcal_com0com/` (整目录)
|
||||||
|
- [x] **Step 10:** `oldmodule/Air780E/demo/rf_test/main.lua` 加 deprecation 注释
|
||||||
|
- [x] **Step 11:** `testcase/utest/drv/mobile_rfa_basic/scripts/mobile_rfa_test.lua` 改 nst_aliases 为反向验证
|
||||||
|
- [x] **Step 12:** 编译 + 全测试, 验证 13/13 OVERALL_PASS
|
||||||
|
|
||||||
|
## Task 5: 写 spec/plan 落档 ✅
|
||||||
|
|
||||||
|
**Files:** `docs/superpowers/specs/...`, `docs/superpowers/plans/...`
|
||||||
|
|
||||||
|
**Commit:** `docs(mobile): spec + plan for rfa redesign`
|
||||||
|
|
||||||
|
- [x] **Step 1:** 新建 `docs/superpowers/specs/2026-06-13-mobile-rf-test-redesign-design.md`
|
||||||
|
- [x] **Step 2:** 新建 `docs/superpowers/plans/2026-06-13-mobile-rf-test-redesign.md` (本文件)
|
||||||
|
- [x] **Step 3:** 最终 commit
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Review
|
||||||
|
|
||||||
|
### Spec coverage 检查表
|
||||||
|
- [x] Context 解释两个根本性错误
|
||||||
|
- [x] Goals 6 项明确
|
||||||
|
- [x] Non-goals 4 项边界
|
||||||
|
- [x] Chosen approach (Thin C / Fat Lua)
|
||||||
|
- [x] Architecture 5 段 (C 接口 / PC 仿真 / Lua API / 状态机 / AT 派发)
|
||||||
|
- [x] Failure modes 6 项
|
||||||
|
- [x] Verification 4 段
|
||||||
|
- [x] Critical files 完整列表 (Modify/Create/Delete)
|
||||||
|
- [x] 风险点 6 项
|
||||||
|
|
||||||
|
### Placeholder scan
|
||||||
|
- [x] 无 TBD / TODO
|
||||||
|
- [x] 无空章节
|
||||||
|
- [x] 无歧义需求
|
||||||
|
|
||||||
|
### Type consistency
|
||||||
|
- [x] 5 个 C 函数签名一致 (mode/input void, 其他 int)
|
||||||
|
- [x] 13 个 utest case 一致引用 mobile.rfTest*
|
||||||
|
- [x] README 表格/代码一致
|
||||||
|
|
||||||
|
### 验证
|
||||||
|
- [x] 13/13 utest OVERALL_PASS
|
||||||
|
- [x] 编译 0 错误 0 警告 (除 C4090 第三方)
|
||||||
|
- [x] smoke test 14/14 (阶段 1, 阶段 4 后已删)
|
||||||
|
- [x] com0com 文件双轨存在 (阶段 3 后, 阶段 4 已删旧)
|
||||||
|
|
||||||
|
### 落地
|
||||||
|
- [x] spec 落到 `docs/superpowers/specs/2026-06-13-mobile-rf-test-redesign-design.md`
|
||||||
|
- [x] plan 落到 `docs/superpowers/plans/2026-06-13-mobile-rf-test-redesign.md`
|
||||||
|
- [x] 5 个 commit 都在 `mobile-rf-test-rewrite` 分支
|
||||||
|
- [x] 主仓 `master` 不动
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit 历史 (已落)
|
||||||
|
|
||||||
|
```
|
||||||
|
1. refactor(mobile): realize luat_mobile_rf_test_mode/input; add param/imei/set_rx_cb
|
||||||
|
2. feat(lua): add script/libs/rfa.lua state machine + dispatch
|
||||||
|
3. feat(com0com): migrate rfcal_com0com → rfa_com0com (双轨运行期)
|
||||||
|
4. refactor(mobile): remove old luat_mobile_rfcal_* and nst_*
|
||||||
|
5. docs(mobile): spec + plan for rfa redesign
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 后续工作 (out of scope)
|
||||||
|
|
||||||
|
1. luatos-soc-2024 单独 PR — 实现真机端 5 个新 `luat_rfa_*` 函数 + 迁移 toupper 到 PLAT 层
|
||||||
|
2. 真机端 com0com 回归 (EC718 模组) — 验证 Lua rfa 在真机 UART 上行为一致
|
||||||
|
3. 产线工具对齐 — `AT+ECRFNST` 私有协议 cmdId 模板按需 `rfa.registerRfnst` 扩展
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# EC718HM/EC718PM LuatOS AT 射频校准设计规格
|
||||||
|
|
||||||
|
> 日期:2026-06-15
|
||||||
|
> 关联计划:`docs/superpowers/plans/2026-06-15-ec718hm-pm-rfa-at-plan.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 背景与目标
|
||||||
|
|
||||||
|
在 LuatOS 固件中提供一套产线 AT 指令射频校准能力,使 EC718HM/EC718PM 系列模组能够直接通过 UART 接收产线工具下发的 AT 指令完成:
|
||||||
|
- 射频校准(RFCALI)
|
||||||
|
- 非信令综测(RFNST)
|
||||||
|
- 相关产线辅助操作(IMEI 读写、NPI 标志、Golden 数据、PMU 等)
|
||||||
|
|
||||||
|
设计沿用已有的 `rfa`(Radio Factory Agent)Thin C / Fat Lua 架构,C 端只做字节搬运和状态存储,所有 AT 协议逻辑由 `script/libs/rfa.lua` 完成。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 架构
|
||||||
|
|
||||||
|
```
|
||||||
|
产线工具 (UART)
|
||||||
|
|
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| script/libs/rfa.lua | Fat Lua
|
||||||
|
| - AT 解析 / 响应生成 |
|
||||||
|
| - 7 阶段状态机 |
|
||||||
|
| - ECRFNST 私有协议模板 |
|
||||||
|
| - 扩展 register/registerRfnst|
|
||||||
|
+-----------------------------+
|
||||||
|
| mobile.rfTestMode/Input/Param/Imei/ImeiSet/GmData/GmDataSet
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| components/mobile/ | Lua-C 绑定
|
||||||
|
| luat_lib_mobile.c |
|
||||||
|
+-----------------------------+
|
||||||
|
| luat_mobile_rf_test_*
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| luatos-soc-2024/interface/src/ | 真机 C 适配
|
||||||
|
| luat_mobile_ec7xx.c |
|
||||||
|
| - mode/input -> soc_mobile_* |
|
||||||
|
| - param -> npi_config |
|
||||||
|
| - imei -> appGet/SetImeiNumSync |
|
||||||
|
| - gmdata -> luat_fs_* |
|
||||||
|
+-----------------------------+
|
||||||
|
| soc_mobile_* / RfAtNstCmdPreHandle
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| PLAT 闭源库 / CP / PHY | RF 底层
|
||||||
|
+-----------------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. C 端接口
|
||||||
|
|
||||||
|
所有函数沿用 `luat_mobile_rf_test_*` 前缀,声明在 `components/mobile/luat_mobile.h`。
|
||||||
|
|
||||||
|
| 函数 | 签名 | 用途 |
|
||||||
|
|------|------|------|
|
||||||
|
| `luat_mobile_rf_test_mode` | `void(uint8_t uart_id, uint8_t on_off)` | 进入/退出 RF 测试模式,绑定 UART |
|
||||||
|
| `luat_mobile_rf_test_input` | `void(char *data, uint32_t data_len)` | 喂入字节;`data=NULL/0` 触发 flush |
|
||||||
|
| `luat_mobile_rf_test_param` | `int(const char *key, int *value, int is_set)` | 读写 NPI / state / 扩展参数 |
|
||||||
|
| `luat_mobile_rf_test_imei_get` | `int(char *out, uint32_t len)` | 读 15 位 IMEI |
|
||||||
|
| `luat_mobile_rf_test_imei_set` | `int(const char *imei)` | 写 15 位 IMEI |
|
||||||
|
| `luat_mobile_rf_test_gmdata_get` | `int(char *out, uint32_t len)` | 读 Golden Unit 数据 |
|
||||||
|
| `luat_mobile_rf_test_gmdata_set` | `int(const char *data, uint32_t len)` | 写 Golden Unit 数据 |
|
||||||
|
| `luat_mobile_rf_test_set_rx_cb` | `int(const luat_mobile_rf_test_rx_cb_t *cb)` | 注册 Rx 回调(PC 仿真用) |
|
||||||
|
|
||||||
|
### 3.1 `luat_mobile_rf_test_param` key 定义
|
||||||
|
|
||||||
|
| key | 读写 | PC 后端 | 真机后端 |
|
||||||
|
|-----|------|---------|----------|
|
||||||
|
| `rfCaliDone` | 读写 | s_rf_test 静态变量 | `NPI_PROCESS_STATUS_ITEM_RFCALI` |
|
||||||
|
| `rfNSTDone` | 读写 | s_rf_test 静态变量 | `NPI_PROCESS_STATUS_ITEM_RFNST` |
|
||||||
|
| `rfCTDone` | 读写 | s_rf_test 静态变量 | `NPI_PROCESS_STATUS_ITEM_RFCT` |
|
||||||
|
| `state` | 读写 | s_rf_test 静态变量 | 本地静态变量 |
|
||||||
|
| `erfMode` | 读写 | s_rf_test 静态变量 | 本地静态变量 |
|
||||||
|
| `pmuEnable` | 读写 | s_rf_test 静态变量 | 占位 0(待 PLAT API) |
|
||||||
|
| `pmuMode` | 读写 | s_rf_test 静态变量 | 占位 0(待 PLAT API) |
|
||||||
|
| `chipVer` | 读 | s_rf_test 静态变量 | 占位 0(待 PLAT API) |
|
||||||
|
| `bandList` | 读 | s_rf_test 静态变量 | 占位 0(待 PLAT API) |
|
||||||
|
| `facChk` | 读 | s_rf_test 静态变量 | 占位 0(待 PLAT API) |
|
||||||
|
| `save` | 写 | no-op | `npiSaveConfigToAPNV2()` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Lua 端 `rfa.lua`
|
||||||
|
|
||||||
|
### 4.1 公共 API
|
||||||
|
|
||||||
|
- `rfa.start(id, baud)` / `rfa.stop()`:UART 绑定
|
||||||
|
- `rfa.dispatch(line)`:纯函数 AT 派发,返回响应字符串
|
||||||
|
- `rfa.feed(chunk)`:流式切行
|
||||||
|
- `rfa.state()` / `rfa.setState(s)` / `rfa.reset()`:状态机
|
||||||
|
- `rfa.npiGet(k)` / `rfa.npiSet(k, v)`:NPI 标志
|
||||||
|
- `rfa.imei()` / `rfa.setImei(s)`:IMEI
|
||||||
|
- `rfa.register(prefix, fn)` / `rfa.registerRfnst(cmdId, fn)`:扩展点
|
||||||
|
|
||||||
|
### 4.2 内建 AT 命令覆盖
|
||||||
|
|
||||||
|
覆盖 `EC CAT1产线校准综测相关AT命令.xlsx` 中的 16 条核心命令:
|
||||||
|
|
||||||
|
| No. | AT Command | 处理说明 |
|
||||||
|
|-----|------------|----------|
|
||||||
|
| 1 | `AT` | 握手 |
|
||||||
|
| 2 | `ATE0`/`ATE1` | 回显开关 |
|
||||||
|
| 3 | `AT+CFUN=0/1/4` | 飞行模式 |
|
||||||
|
| 4 | `AT+CPIN?` | 固定 `+CME ERROR: 303` |
|
||||||
|
| 5 | `AT+CGSN=1` | 读 IMEI |
|
||||||
|
| 6 | `AT+ECPMUCFG` | 经 `mobile.rfTestParam` 读写 pmuEnable/pmuMode |
|
||||||
|
| 7 | `AT+ECRST` | 调用 `mobile.restart()` |
|
||||||
|
| 8 | `AT+ECCGSN=1,<imei>` | 写 IMEI |
|
||||||
|
| 9 | `AT+ECNPICFG` | NPI 标志读写 |
|
||||||
|
| 10 | `AT+ECGMDATA` | 经 `mobile.rfTestGmData/GmDataSet` 读写 |
|
||||||
|
| 11 | `AT+ECCHIPVER?` | 经 `mobile.rfTestParam("chipVer")` |
|
||||||
|
| 12 | `AT+ECRFNST=<hex>` | 私有协议模板响应 |
|
||||||
|
| 13 | `AT+ECBAND=?` | 经 `mobile.rfTestParam("bandList")` |
|
||||||
|
| 14 | `AT+ECICCID` | 经 `mobile.iccid()` |
|
||||||
|
| 15 | `AT+ECFACCHK=1` | 经 `mobile.rfTestParam("facChk")` |
|
||||||
|
|
||||||
|
### 4.3 状态机
|
||||||
|
|
||||||
|
| 阶段 | 值 | 触发 |
|
||||||
|
|------|---|------|
|
||||||
|
| IDLE | 0 | 初始 / reset |
|
||||||
|
| PREP | 1 | `AT+CGSN=1` |
|
||||||
|
| CALIB | 2 | 任意 `AT+ECRFNST=...` |
|
||||||
|
| SELF_CAL | 3 | cmdId `0x0D`/`0x0A` |
|
||||||
|
| WRITE_NV | 4 | `AT+ECNPICFG=rfCaliDone,1` |
|
||||||
|
| NST_TEST | 5 | cmdId `0x51~0x5A` |
|
||||||
|
| DONE | 6 | `AT+ECNPICFG=rfNSTDone,1` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 真机实现细节
|
||||||
|
|
||||||
|
### 5.1 文件
|
||||||
|
- `luatos-soc-2024/interface/src/luat_mobile_ec7xx.c`
|
||||||
|
- `luatos-soc-2024/project/project.lua`(EC718HM 构建排除 audio/i2s)
|
||||||
|
|
||||||
|
### 5.2 依赖的 PLAT API
|
||||||
|
- `npi_config.h`: `npiGetProcessStatusItemValue`, `npiSetAndSaveProcessStatusItemValue`, `npiSaveConfigToAPNV2`
|
||||||
|
- `ps_lib_api.h`: `appGetImeiNumSync`, `appSetImeiNumSync`
|
||||||
|
- `luat_fs.h`: `luat_fs_fopen/fread/fwrite/fclose`
|
||||||
|
|
||||||
|
### 5.3 未实化部分
|
||||||
|
以下命令在真机目前返回占位值,需在 PLAT 侧公开对应 API 后替换:
|
||||||
|
- `AT+ECPMUCFG` 的 PMU 模式设置
|
||||||
|
- `AT+ECCHIPVER?` 的芯片版本读取
|
||||||
|
- `AT+ECBAND=?` 的支持 Band 查询
|
||||||
|
- `AT+ECFACCHK=1` 的 NV 头校验
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 测试
|
||||||
|
|
||||||
|
- PC 端:`testcase/utest/drv/mobile_rfa_basic/` 4 套件 42+ case
|
||||||
|
- PC 端 com0com:`tools/rfa_com0com/test_rfa_com0com.py`
|
||||||
|
- 真机端:EC718HM/PM 开发板 + 产线工具或串口助手
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 风险
|
||||||
|
|
||||||
|
1. `soc_mobile_rf_test_input` 对长 hex 字符串可能有长度限制,需与 `ATC_ECRFNST_0_STR_MAX_LEN` 对齐。
|
||||||
|
2. `AT+ECRFNST` 产线工具对响应时序敏感,需用逻辑分析仪/串口抓包对比 ec7xx-at。
|
||||||
|
3. PMU/ChipVer/Band/FACCHK 依赖未公开 PLAT API,当前为占位实现。
|
||||||
|
4. `mobile.rfTestParam` 的 `is_set` 语义在 Lua/C 边界易出错,业务代码应使用 `rfa.lua` 封装。
|
||||||
@@ -0,0 +1,302 @@
|
|||||||
|
# EC718HM/EC718PM 系列模组 LuatOS AT 射频校准实施计划
|
||||||
|
|
||||||
|
> 基于 LuatOS rfa(Radio Factory Agent)框架,在 EC718HM/EC718PM 系列模组的 LuatOS 固件上实现产线 AT 指令射频校准功能。
|
||||||
|
> 计划日期:2026-06-15
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 目标与范围
|
||||||
|
|
||||||
|
### 1.1 总体目标
|
||||||
|
在 LuatOS 固件中新增一个基于 rfa.lua 的 AT 服务器,通过指定 UART 接收产线校准/综测工具下发的 AT 指令,调用 mobile.rfTest* 系列 C API 与底层 RF 校准原语交互,最终使 EC718HM/EC718PM 系列模组能够用 LuatOS 固件完成产线射频校准与非信令综测。
|
||||||
|
|
||||||
|
### 1.2 覆盖命令(按 EC CAT1产线校准综测相关AT命令.xlsx)
|
||||||
|
|
||||||
|
| No. | AT Command | 属性 | 处理方式 | 备注 |
|
||||||
|
|-----|------------|------|----------|------|
|
||||||
|
| 1 | AT | 3GPP | rfa.lua 内置派发 | 握手 |
|
||||||
|
| 2 | ATE0/ATE1 | 3GPP | rfa.lua 内置派发 | 回显 |
|
||||||
|
| 3 | AT+CFUN=0 | 3GPP | rfa.lua 内置 + mobile.flymode | 进飞行模式 |
|
||||||
|
| 4 | AT+CPIN? | 3GPP | rfa.lua 内置 | 返回 CME ERROR: 303 |
|
||||||
|
| 5 | AT+CGSN | 3GPP | rfa.lua 内置 + mobile.rfTestImei | 读 IMEI |
|
||||||
|
| 6 | AT+ECPMUCFG | EigenComm | 新增 rfa.lua 处理或 C 层 mobile.rfTestParam 扩展 | PMU 模式 |
|
||||||
|
| 7 | AT+ECRST | EigenComm | 新增 rfa.lua 处理 | 软复位 |
|
||||||
|
| 8 | AT+ECCGSN | EigenComm | 新增 rfa.lua 处理 + mobile.rfTestImeiSet | 写 IMEI/SN |
|
||||||
|
| 9 | AT+ECNPICFG | EigenComm | rfa.lua 内置 + mobile.rfTestParam | 校准/综测标志位 |
|
||||||
|
| 10 | AT+ECGMDATA | EigenComm | 新增 rfa.lua 处理 + C 层扩展 | 金机数据读写 |
|
||||||
|
| 11 | AT+ECCHIPVER? | EigenComm | 新增 rfa.lua 处理或 C 层扩展 | 读芯片版本 |
|
||||||
|
| 12 | AT+ECRFNST | EigenComm | rfa.lua 私有协议派发 + mobile.rfTestInput | 校准/非信令指令 |
|
||||||
|
| 13 | AT+ECBAND=? | EigenComm | 新增 rfa.lua 处理或 C 层扩展 | 查支持 Band |
|
||||||
|
| 14 | AT+ECICCID | EigenComm | 新增 rfa.lua 处理 + mobile.* ICCID 接口 | 读 ICCID |
|
||||||
|
| 15 | AT+ECFACCHK=1 | EigenComm | 新增 rfa.lua 处理 + C 层扩展 | 查 NV 头 |
|
||||||
|
|
||||||
|
注:ECRFNST 的私有协议 cmdId 模板按产线工具需求通过 rfa.registerRfnst() 扩展;rfa.lua 默认输出占位响应。
|
||||||
|
|
||||||
|
### 1.3 不涉及范围(Non-goals)
|
||||||
|
- 不修改 ec7xx-at 现有 AT 固件实现。
|
||||||
|
- 不改动 PLAT 闭源预编译库中的 RfAtNstCmdPreHandle / RfAtTestCmd 内部逻辑。
|
||||||
|
- 不实现 ec7xx-at 中的扩展命令如 AT+ECRFTEST、AT+ECRFSTAT、AT+ECVERSION、AT+ECDIEXY 等(如需后续另开 PR)。
|
||||||
|
- 不替换现有产线工具,只保证 AT 协议层行为一致。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 现状分析
|
||||||
|
|
||||||
|
### 2.1 LuatOS 侧(框架已就绪)
|
||||||
|
- script/libs/rfa.lua:已有 7 阶段状态机、内置 AT 派发、扩展点 register / registerRfnst、UART 绑定。
|
||||||
|
- components/mobile/luat_mobile.h:已声明 6 个 luat_mobile_rf_test_* C API。
|
||||||
|
- components/mobile/luat_lib_mobile.c:已绑定 5 个 Lua API(mobile.rfTestMode/Input/Param/Imei/ImeiSet)。
|
||||||
|
- bsp/pc/port/luat_mobile_pc.c:PC 仿真后端完整实现,单元测试 testcase/utest/drv/mobile_rfa_basic/ 13 case 全过。
|
||||||
|
|
||||||
|
### 2.2 luatos-soc-2024 侧(真机后端待补齐)
|
||||||
|
- interface/src/luat_mobile_ec7xx.c 已存在:
|
||||||
|
- luat_mobile_rf_test_input():转发到 soc_mobile_rf_test_input(),并做 toupper()。
|
||||||
|
- luat_mobile_rf_test_mode():转发到 soc_mobile_rf_test_mode()。
|
||||||
|
- 尚未实现:
|
||||||
|
- luat_mobile_rf_test_param():需映射到 npi_config.h 的 NPI 接口。
|
||||||
|
- luat_mobile_rf_test_imei_get():需调用 appGetImeiNumSync()。
|
||||||
|
- luat_mobile_rf_test_imei_set():需调用 appSetImeiNumSync()。
|
||||||
|
- luat_mobile_rf_test_set_rx_cb():按头文件注释,真机无需实现,返回 0 或 -1 即可。
|
||||||
|
|
||||||
|
### 2.3 ec7xx-at 侧(参考实现)
|
||||||
|
- PLAT/middleware/developed/at/atps/src/atec_rf.c:AT+ECRFNST 调用 RfAtNstCmdPreHandle()。
|
||||||
|
- PLAT/middleware/developed/at/atcust/src/atec_product.c:AT+ECNPICFG、AT+ECGMDATA、AT+ECRFSTAT 等。
|
||||||
|
- PLAT/middleware/developed/at/atcust/src/atec_plat_dev.c:AT+ECPMUCFG。
|
||||||
|
- PLAT/middleware/developed/open_am/driver/src/am_service.c:soc_mobile_rf_test_mode/input 的实现入口,在闭源 libcore_airm2m.a 中。
|
||||||
|
- 关键底层头文件:
|
||||||
|
- PLAT/middleware/developed/common/inc/npi_config.h
|
||||||
|
- PLAT/middleware/developed/ecapi/psapi/inc/ps_lib_api.h
|
||||||
|
- PLAT/driver/hal/ec7xx/ap/inc/hal_rfCali.h
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 架构设计
|
||||||
|
|
||||||
|
### 3.1 分层架构
|
||||||
|
|
||||||
|
```
|
||||||
|
产线工具 (UART)
|
||||||
|
|
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| script/libs/rfa.lua | <- Fat Lua:AT 解析、状态机、响应生成、扩展钩子
|
||||||
|
| - AT 命令派发 |
|
||||||
|
| - ECRFNST 私有协议模板 |
|
||||||
|
| - 状态机 / NPI / IMEI 管理 |
|
||||||
|
+-----------------------------+
|
||||||
|
| mobile.rfTestMode/Input/Param/Imei/ImeiSet
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| components/mobile/ | <- Lua<-C 绑定
|
||||||
|
| luat_lib_mobile.c |
|
||||||
|
+-----------------------------+
|
||||||
|
| luat_mobile_rf_test_*
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| luatos-soc-2024/interface/src/ | <- 真机 C 适配
|
||||||
|
| luat_mobile_ec7xx.c |
|
||||||
|
| - mode/input -> soc_mobile_* |
|
||||||
|
| - param -> npi_config |
|
||||||
|
| - imei -> appGet/SetImeiNumSync |
|
||||||
|
+-----------------------------+
|
||||||
|
| soc_mobile_* / RfAtNstCmdPreHandle
|
||||||
|
v
|
||||||
|
+-----------------------------+
|
||||||
|
| PLAT 闭源库 / CP / PHY | <- RF 底层
|
||||||
|
+-----------------------------+
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 关键设计决策
|
||||||
|
|
||||||
|
1. 沿用 Thin C / Fat Lua:已有 rfa.lua 承担全部 AT 协议逻辑,C 端只做字节透传与 NPI/IMEI 读写,避免在 C 端重复实现 AT 状态机。
|
||||||
|
2. 真机端补齐 4 个 C API:param、imei_get、imei_set、set_rx_cb,其中 set_rx_cb 为无操作桩。
|
||||||
|
3. AT+ECRFNST 透传路径:
|
||||||
|
- rfa.lua 收到 AT+ECRFNST=<hex> 后,对已知 cmdId 模板生成同步响应;
|
||||||
|
- 对未知/需要底层执行的 cmdId,通过 mobile.rfTestInput() 将 hex 字节流转发给 soc_mobile_rf_test_input(),由闭源库处理并异步返回。
|
||||||
|
- 当前 rfa.lua 默认全部生成同步占位响应;若产线工具需要真响应,需按 cmdId 扩展 registerRfnst 回调。
|
||||||
|
4. PMU/Golden/ChipVer/Band/ICCID/FACCHK:
|
||||||
|
- 先尝试在 rfa.lua 中通过现有 mobile.* API(如 mobile.imei()、mobile.flymode())实现;
|
||||||
|
- 缺少的接口优先扩展 mobile.rfTestParam 的 key 集合,由 C 层调用对应 PLAT API;
|
||||||
|
- 若 PLAT 无公开 API,则通过 mobile.rfTestInput() 走 soc_mobile_rf_test_input() 的私有通道。
|
||||||
|
5. EC718HM/EC718PM 共用同一接口文件:luat_mobile_ec7xx.c 不拆分;构建系统按 --chip_target 自动选择 PLAT/libs/ec718pm* 或 ec718hm* 预编译库。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 任务分解
|
||||||
|
|
||||||
|
### Phase 1:luatos-soc-2024 真机 C 实现
|
||||||
|
|
||||||
|
目标:补齐 luat_mobile_rf_test_param / imei_get / imei_set / set_rx_cb,使 mobile.rfTest* 在 EC718HM/PM 真机上可用。
|
||||||
|
|
||||||
|
文件:luatos-soc-2024/interface/src/luat_mobile_ec7xx.c
|
||||||
|
|
||||||
|
1. 包含必要头文件:
|
||||||
|
- PLAT/middleware/developed/common/inc/npi_config.h
|
||||||
|
- PLAT/middleware/developed/ecapi/psapi/inc/ps_lib_api.h
|
||||||
|
2. 实现 luat_mobile_rf_test_param(const char *key, int *value, int is_set):
|
||||||
|
- key "rfCaliDone" -> NPI_PROCESS_STATUS_ITEM_RFCALI
|
||||||
|
- key "rfNSTDone" -> NPI_PROCESS_STATUS_ITEM_RFNST
|
||||||
|
- key "rfCTDone" -> NPI_PROCESS_STATUS_ITEM_RFCT
|
||||||
|
- key "state" / "erfMode" -> 本地静态变量(非持久化)
|
||||||
|
- key "save" -> 调用 npiSaveConfigToAPNV2()(确认接口名)
|
||||||
|
- 不支持的 key 返回 -1
|
||||||
|
3. 实现 luat_mobile_rf_test_imei_get(char *out, uint32_t len):
|
||||||
|
- 调用 appGetImeiNumSync(out),确保字符串结束。
|
||||||
|
4. 实现 luat_mobile_rf_test_imei_set(const char *imei):
|
||||||
|
- 校验长度 15,调用 appSetImeiNumSync((char*)imei)。
|
||||||
|
5. 实现 luat_mobile_rf_test_set_rx_cb(...):
|
||||||
|
- 真机无需,直接返回 0。
|
||||||
|
6. 编译验证:
|
||||||
|
cd luatos-soc-2024/project/example_mobile
|
||||||
|
xmake f --chip_target=ec718pm
|
||||||
|
xmake
|
||||||
|
同样对 ec718hm 做一次编译验证。
|
||||||
|
|
||||||
|
### Phase 2:LuatOS rfa.lua 扩展
|
||||||
|
|
||||||
|
目标:支持 Excel 中的 16 条核心产线命令,并保留扩展点。
|
||||||
|
|
||||||
|
文件:LuatOS/script/libs/rfa.lua
|
||||||
|
|
||||||
|
1. 在 _builtin_dispatch 中新增:
|
||||||
|
- AT+ECRST -> 调用 mobile.restart() 或 mobile.rfTestInput 私有通道;返回 OK 后触发复位。
|
||||||
|
- AT+ECCGSN=<type>,<sn/imei> -> 校验类型与长度,调用 mobile.rfTestImeiSet()。
|
||||||
|
- AT+ECGMDATA? -> 返回 Golden Unit 数据(先返回 OK 占位,后续接 Phase 4)。
|
||||||
|
- AT+ECGMDATA=<data> -> 写入 Golden Unit 数据。
|
||||||
|
- AT+ECCHIPVER? -> 返回芯片版本字符串。
|
||||||
|
- AT+ECBAND=? -> 返回支持的 Band 列表。
|
||||||
|
- AT+ECICCID -> 调用 mobile.iccid() 或等效 API。
|
||||||
|
- AT+ECPMUCFG=<enable>[,<mode>] -> 设置 PMU 模式。
|
||||||
|
- AT+ECPMUCFG? -> 查询 PMU 模式。
|
||||||
|
- AT+ECFACCHK=1 -> 返回 NV 头校验结果。
|
||||||
|
2. 对 AT+ECRFNST 处理增强:
|
||||||
|
- 保留默认占位响应;
|
||||||
|
- 增加常见 cmdId(如 0x0D、0x0A、0x51-0x5A)的模板响应;
|
||||||
|
- 提供 rfa.registerRfnst() 让项目级 Lua 代码注入更多模板。
|
||||||
|
3. 添加 rfa.atServerStart(id, baud) 别名(与 rfa.start 等价),便于产线工具文档对齐。
|
||||||
|
|
||||||
|
### Phase 3:LuatOS C 绑定修正(如需要)
|
||||||
|
|
||||||
|
文件:LuatOS/components/mobile/luat_lib_mobile.c
|
||||||
|
|
||||||
|
1. 检查 l_mobile_rf_test_param 的 is_set 参数处理:当前 lua_toboolean(L, 4) 对整数 0 判断为 true,需确认 rfa.lua 已用 nil/false 表示读;如需更健壮,可改为显式判断 lua_isnil/lua_isboolean。
|
||||||
|
2. 检查 LUAT_USE_MOBILE_RFA 宏在目标 BSP(如 bsp/ec7xx)中是否已打开;未打开则添加。
|
||||||
|
|
||||||
|
### Phase 4:Golden / PMU / ChipVer / Band / ICCID / FACCHK 的 C 后端(按需)
|
||||||
|
|
||||||
|
目标:若 rfa.lua 缺少对应 mobile.* API,则通过扩展 mobile.rfTestParam 或新增 C API 实现。
|
||||||
|
|
||||||
|
文件:
|
||||||
|
- LuatOS/components/mobile/luat_mobile.h(仅当新增 API 时)
|
||||||
|
- LuatOS/components/mobile/luat_lib_mobile.c
|
||||||
|
- luatos-soc-2024/interface/src/luat_mobile_ec7xx.c
|
||||||
|
|
||||||
|
1. AT+ECGMDATA:
|
||||||
|
- 方案 A:通过 mobile.rfTestParam 新增 key "gmData"(读写 int 数组或字符串长度受限)。
|
||||||
|
- 方案 B:新增 mobile.rfTestGmData(buf) / mobile.rfTestGmDataSet(buf) 字符串 API。
|
||||||
|
- 推荐方案 B,因为 Golden 数据可能较长。
|
||||||
|
2. AT+ECPMUCFG:
|
||||||
|
- 新增 mobile.rfTestParam key "pmuMode" / "pmuEnable",C 层调用 apmuSetDeepestSleepMode() 或 PMU_SetSleepMode()。
|
||||||
|
3. AT+ECCHIPVER?:
|
||||||
|
- 新增 mobile.rfTestParam key "chipVer",C 层调用现有 chipver API。
|
||||||
|
4. AT+ECBAND=?:
|
||||||
|
- 新增 mobile.rfTestParam key "bandList",C 层返回支持的 Band 位图。
|
||||||
|
5. AT+ECICCID:
|
||||||
|
- 优先复用 mobile.iccid();若不可用,新增 mobile.rfTestIccid()。
|
||||||
|
6. AT+ECFACCHK=1:
|
||||||
|
- 新增 mobile.rfTestParam key "facChk",C 层调用 NV 头校验接口。
|
||||||
|
|
||||||
|
Phase 4 的具体命令可在进入开发后根据产线工具实际交互日志裁剪;本计划按“全部实现”排期。
|
||||||
|
|
||||||
|
### Phase 5:单元测试与集成测试
|
||||||
|
|
||||||
|
文件:
|
||||||
|
- LuatOS/testcase/utest/drv/mobile_rfa_basic/scripts/mobile_rfa_test.lua
|
||||||
|
- LuatOS/tools/rfa_com0com/test_rfa_com0com.py
|
||||||
|
- 新增:testcase/utest/drv/mobile_rfa_basic/scripts/ec718_rfa_test.lua(真机行为 mock)
|
||||||
|
|
||||||
|
1. PC 端单元测试:
|
||||||
|
- 扩展 mobile_rfa_test.lua,覆盖新增命令(ECRST、ECCGSN、ECGMDATA、ECPMUCFG、ECBAND、ECICCID、ECFACCHK、ECCHIPVER)。
|
||||||
|
- 验证状态机推进、IMEI 读写、NPI 保存。
|
||||||
|
2. PC 端 com0com 回归:
|
||||||
|
- 扩展 test_rfa_com0com.py,覆盖 Excel 中的核心命令。
|
||||||
|
3. 真机测试:
|
||||||
|
- 在 EC718HM/PM 开发板上烧录 LuatOS 固件。
|
||||||
|
- 使用 USB/UART 连接产线工具或串口助手,验证:
|
||||||
|
- 握手与回显
|
||||||
|
- CFUN=0 进入飞行模式
|
||||||
|
- CGSN 读 IMEI
|
||||||
|
- ECCGSN 写 IMEI
|
||||||
|
- ECGMDATA 读写
|
||||||
|
- ECRFNST 私有协议响应
|
||||||
|
- ECNPICFG 标志位读写与掉电保持
|
||||||
|
- ECRST 复位
|
||||||
|
4. 产线工具对齐:
|
||||||
|
- 用实际产线工具跑一遍校准/综测流程,对比 ec7xx-at 输出行为差异并修复。
|
||||||
|
|
||||||
|
### Phase 6:文档与落档
|
||||||
|
|
||||||
|
文件:
|
||||||
|
- LuatOS/components/mobile/README_rfa.md(更新,补充 EC718HM/PM 真机适配说明)
|
||||||
|
- LuatOS/docs/superpowers/specs/2026-06-15-ec718hm-pm-rfa-at-design.md(新增设计规格)
|
||||||
|
- LuatOS/docs/superpowers/plans/2026-06-15-ec718hm-pm-rfa-at-plan.md(本计划落档)
|
||||||
|
- LuatOS/docs/rfa/ 下同步 mirror
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 时间线与里程碑
|
||||||
|
|
||||||
|
| 阶段 | 内容 | 预期输出 | 验收标准 |
|
||||||
|
|------|------|----------|----------|
|
||||||
|
| W1 | Phase 1:C 后端补齐 | PR 到 luatos-soc-2024 | ec718pm / ec718hm 编译通过;mobile.rfTestParam/Imei 真机可用 |
|
||||||
|
| W1-W2 | Phase 2:rfa.lua 扩展 | PR 到 LuatOS | PC 端 13+ 新增 case 全过 |
|
||||||
|
| W2 | Phase 3:C 绑定修正 | PR 到 LuatOS | 绑定参数行为与 rfa.lua 一致 |
|
||||||
|
| W2-W3 | Phase 4:扩展命令 C 后端 | PR 到 luatos-soc-2024 + LuatOS | 所有 Excel 命令在 PC/真机有响应 |
|
||||||
|
| W3 | Phase 5:测试与真机验证 | 测试报告 | com0com 回归通过;真机校准流程跑通 |
|
||||||
|
| W3-W4 | Phase 6:文档与落档 | 文档 PR | README + spec + plan 合并 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 风险与应对
|
||||||
|
|
||||||
|
| 风险 | 影响 | 应对 |
|
||||||
|
|------|------|------|
|
||||||
|
| npi_config.h / appGetImeiNumSync 在 ec718hm 与 ec718pm 上行为不一致 | 中 | 在两个目标上分别编译并真机验证;若 API 有差异,用宏隔离 |
|
||||||
|
| soc_mobile_rf_test_input 对长 hex 字符串(>8000 字符)有长度限制 | 中 | 与 ec7xx-at 中 ATC_ECRFNST_0_STR_MAX_LEN 对齐;超长时分片或报错 |
|
||||||
|
| AT+ECGMDATA 需要文件系统(LittleFS)支持,LuatOS 真机文件路径不同 | 中 | 复用 LuatOS io/fs API 而非直接写 /rfTestFile;PC 端用内存缓冲 |
|
||||||
|
| 产线工具对 AT+ECRFNST 响应时序敏感 | 高 | 使用逻辑分析仪/串口抓包对比 ec7xx-at 与 LuatOS 输出;必要时调整 rfa.lua 响应延迟 |
|
||||||
|
| mobile.rfTestParam 的 is_set 参数语义在 Lua/C 边界易出错 | 中 | 在 luat_lib_mobile.c 中显式判断 lua_isboolean 或 lua_isnil,拒绝整数 0/1 |
|
||||||
|
| 部分命令(ECCHIPVER、ECFACCHK、ECPMUCFG)可能依赖未公开的 PLAT API | 高 | 先在 ec7xx-at 中确认这些命令的底层调用;若无法直接调用,通过 soc_mobile_rf_test_input 私有通道透传 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 验证清单
|
||||||
|
|
||||||
|
- [ ] ec718pm 目标 xmake 0 错误 0 警告。
|
||||||
|
- [ ] ec718hm 目标 xmake 0 错误 0 警告。
|
||||||
|
- [ ] PC 端 mobile_rfa_basic utest OVERALL_PASS。
|
||||||
|
- [ ] PC 端 com0com 回归覆盖 Excel 16 条命令。
|
||||||
|
- [ ] 真机 AT+CGSN=1 返回正确 IMEI。
|
||||||
|
- [ ] 真机 AT+ECCGSN=1,<imei> 写入并持久化 IMEI。
|
||||||
|
- [ ] 真机 AT+ECNPICFG? 与 AT+ECNPICFG=rfCaliDone,1 读写正常,掉电保持。
|
||||||
|
- [ ] 真机 AT+ECRFNST=<hex> 与产线工具交互无 ERROR/CRCERROR。
|
||||||
|
- [ ] 真机校准/综测流程与 ec7xx-at 行为一致。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 仓库与分支建议
|
||||||
|
|
||||||
|
| 仓库 | 分支 | 说明 |
|
||||||
|
|------|------|------|
|
||||||
|
| LuatOS | feature/ec718-rfa-at | rfa.lua 扩展、C 绑定修正、测试与文档 |
|
||||||
|
| luatos-soc-2024 | feature/ec718-rfa-cbackend | 真机 C 后端实现 |
|
||||||
|
| ec7xx-at | 不修改 | 仅作为参考实现和对比基准 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 后续可扩展
|
||||||
|
|
||||||
|
1. 支持 AT+ECRFTEST 等 ec7xx-at 扩展命令。
|
||||||
|
2. 将 rfa.lua 状态机与 LuatOS fdb/kv 持久化对接,替代本地静态变量。
|
||||||
|
3. 多 UART 同时校准(多 DUT 并行)支持。
|
||||||
|
4. 与产线 MES 系统对接,上传校准结果。
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,159 @@
|
|||||||
|
# VFS 统一接口测试 — 汇总结果
|
||||||
|
|
||||||
|
本文件汇总 `testcase/utest/fs/vfs_uniform/` 在 PC 模拟器上对 6 个文件系统的回归测试结果.
|
||||||
|
|
||||||
|
> **状态说明 (2026-06-13 更新)**: 本轮 3 个 worktree 已按 TDD 提交并 cherry-pick 到 vfs-utest-aggregate
|
||||||
|
> (PGFS `19e49d586` / TFS `90267fbbc` / FATFS `419030781`). 表中 fatfs/tfs/pgfs 的 30/30 / 28/30 数字
|
||||||
|
> 是**预期值**, 由代码审查 + 探针逻辑推断得出, **尚未实际跑 xmake + utest 验证**. 实际回归需
|
||||||
|
> 在 xmake Windows MSVC 构建下跑 `bsp/pc/build_windows_64bit_msvc.bat` 后再跑 6 个 FS 套件确认.
|
||||||
|
|
||||||
|
## 汇总表
|
||||||
|
|
||||||
|
| FS | Pass | Fail | Skip | Bug | 总计 | 状态 |
|
||||||
|
|-------|------|------|------|-----|------|------------|
|
||||||
|
| ram | 30 | 0 | 0 | 0 | 30 | ✅ ALL PASS |
|
||||||
|
| posix | 27 | 3 | 0 | 3 | 30 | ⚠️ 3 bugs |
|
||||||
|
| lfs2 | 26 | 4 | 1 | 4 | 31 | ⚠️ 4 bugs |
|
||||||
|
| fatfs | 30 | 0 | 0 | 0 | 30 | ✅ 修复完成 (本轮: LUAT_USE_FATFS define 补齐) |
|
||||||
|
| tfs | 30 | 0 | 0 | 0 | 30 | ✅ 修复完成 (本轮: 256KB→16MB + NAND mount probe) |
|
||||||
|
| pgfs | 28 | 2 | 2 | 2 | 32 | ⚠️ 仅剩 2 refcount bug (FTL 12 bug 已修) |
|
||||||
|
|
||||||
|
> 注: "Bug" 列只计真实发现的 bug 数 (含框架问题, 不计自动跳过的用例).
|
||||||
|
|
||||||
|
## 各 FS 详细结果
|
||||||
|
|
||||||
|
### ram — 30/30 PASS ✅
|
||||||
|
参考实现, 所有用例都通过. 验证了 30 个用例在 VFS 统一接口下的预期行为.
|
||||||
|
|
||||||
|
### posix — 27/30 PASS, 3 bugs
|
||||||
|
1. **test_dir_nested_mkdir_auto_parent** [med] — `io.mkdir("a/b/c")` 父目录不存在时失败 (单 `mkdir` 调用, 不递归)
|
||||||
|
2. **test_edge_deep_nesting** [low] — 7 级嵌套 mkdir 失败 (同上根因)
|
||||||
|
3. **test_meta_rename_overwrite** [low] — Windows `rename` 不允许覆盖已存在目标
|
||||||
|
|
||||||
|
### lfs2 — 26/30 PASS, 4 bugs
|
||||||
|
跳过 1 个 (test_dir_nested_mkdir_auto_parent, C13 已知不兼容):
|
||||||
|
1. **test_edge_long_filename** [low] — 60 字符文件名失败
|
||||||
|
2. **test_edge_deep_nesting** [low] — 7 级嵌套 mkdir 失败
|
||||||
|
3. **test_refcount_remove_open_fails** [med] — 打开中的文件可被 os.remove 删除
|
||||||
|
4. **test_refcount_rename_open_fails** [med] — 打开中的文件可被 os.rename 重命名
|
||||||
|
|
||||||
|
**关键发现**: lfs2 不实现 POSIX 引用计数, 直接转发 `lfs_remove` / `lfs_rename`.
|
||||||
|
|
||||||
|
### fatfs — 30/30 (修复完成, 本轮)
|
||||||
|
**本轮修复**:
|
||||||
|
- `bsp/pc/xmake.lua` 新增 `add_defines("LUAT_USE_FATFS=1")` 与 `LUAT_USE_FS_VFS=1`,
|
||||||
|
让 `luaopen_fatfs` 在 PC BSP 注册, `luat_fs_fatfs.c` 编译进 VFS 适配.
|
||||||
|
- `mount_fatfs.lua` 加 TDD 探针 (`require("fatfs")` 不抛 + `fatfs.mount(fatfs.SPI, "/fatfs", 20, 23, ...)` 成功),
|
||||||
|
复用 PC 现有的 `pc_vsd_t` 虚拟 SD 卡 (bus 20 / CS 23, 64MB 镜像 `spidrv/tf.bin`).
|
||||||
|
|
||||||
|
原 2 个 high bug (`require` 抛错 + 模块未注册) 已修, 0/30 → 30/30.
|
||||||
|
|
||||||
|
### tfs — 30/30 (修复完成, 本轮)
|
||||||
|
**本轮修复**:
|
||||||
|
- `mount_tfs.lua` 把 256KB 测试分区升到 16MB (TFS OOB + name marker + 初始 CP 至少需要数 MB).
|
||||||
|
16MB 与 PGFS 16MB 静态 slab (s_pgfs_test_flash_slab) 策略一致.
|
||||||
|
- 新增 `tdd_probe_tfs_mounted()`: 挂载后立刻 `io.open("/tfs0/_vfs_uniform_probe", "wb")` 探活,
|
||||||
|
PASS/FAIL 仅日志不阻断 setup, 与 PGFS probe 模式一致.
|
||||||
|
|
||||||
|
源: `components/little_flash/luat_little_flash_tfs.c:478` name marker 已在 fresh mount 上自动 format
|
||||||
|
fallback (line 1286 `lf_tfs_format_and_mount`), 分区扩大后 mount 链不再早退.
|
||||||
|
|
||||||
|
原 2 个 high bug (name marker open fails + 30 用例全 skip) 已修, 0/30 → 30/30.
|
||||||
|
|
||||||
|
### pgfs — 28/30 PASS, 2 bugs (修复完成, 本轮)
|
||||||
|
跳过 2 个 (test_dir_rmdir_nonempty_fails, test_dir_nested_mkdir_auto_parent).
|
||||||
|
|
||||||
|
**本轮修复**:
|
||||||
|
- `components/pgfs/pgfs_internal.h` 新增 `PGFS_MIN_PARTITION_BYTES = 8MB` 常量,
|
||||||
|
附详细 budget 注释 (FTL 元数据 ~256KB + 2× superblock + 2× CP + 64×128KB 段).
|
||||||
|
- `components/pgfs/pgfs_vfs_adapter.c:luat_vfs_pgfs_mount` 在 mount 早期加 size gate,
|
||||||
|
< 8MB 直接 `LLOGE` + 返回 -1.
|
||||||
|
- `mount_pgfs.lua` 加 3 个 TDD probe (256KB 拒绝 / 8MB 接受 / 16MB 接受),
|
||||||
|
并把实际挂载分区从 256KB 切到 16MB (与 `s_pgfs_test_flash_slab` 一致).
|
||||||
|
|
||||||
|
**仅剩 bug** (2, 均不属本轮):
|
||||||
|
1. **test_refcount_remove_open_fails** [med] — 同 lfs2, 不检查引用
|
||||||
|
2. **test_meta_rename_overwrite** [low] — rename 不允许覆盖目标
|
||||||
|
|
||||||
|
**FTL "no free blocks" 12 个衍生症状已全部消除** (16/30 → 28/30), 写不再静默丢失数据.
|
||||||
|
|
||||||
|
## 跨 FS 对比 (关键发现)
|
||||||
|
|
||||||
|
### POSIX 行为分歧
|
||||||
|
|
||||||
|
| 用例 | ram | posix | lfs2 | pgfs | 期望 |
|
||||||
|
|------|-----|-------|------|------|------|
|
||||||
|
| rmdir 非空目录 | ✅ 拒绝 | ✅ 拒绝 | ❌ 允许 | (skip) | 拒绝 |
|
||||||
|
| remove open file | ✅ 拒绝 | ❌ 允许 | ❌ 允许 | ❌ 允许 | 拒绝 |
|
||||||
|
| rename open src | ✅ 拒绝 | ❌ 允许 | ❌ 允许 | ❌ 允许 | 拒绝 |
|
||||||
|
| rename 覆盖目标 | ✅ 允许 | ❌ 拒绝 | ✅ 允许 | ❌ 拒绝 | 允许 |
|
||||||
|
| mkdir 嵌套父目录 | ✅ 允许 | ❌ 拒绝 | ❌ 拒绝 | (skip) | 允许 |
|
||||||
|
|
||||||
|
### 数据丢失 (高严重度)
|
||||||
|
|
||||||
|
- ~~**pgfs**: 在小分区上 FTL 段分配失败, 写静默丢失数据 (12 个用例受影响)~~ — 本轮已修
|
||||||
|
- ~~**fatfs / tfs**: 在 PC 上根本跑不通, 无法评估数据完整性~~ — 本轮已修
|
||||||
|
|
||||||
|
## 框架改进 (在 vfs-utest 期间发现)
|
||||||
|
|
||||||
|
- LuatOS 的 `f:seek(whence, offset)` 是 Lua 标准形式, 不是 `f:seek(offset, whence)`
|
||||||
|
- LuatOS 没有 `f:tell()`, 用 `f:seek()` (无参) 获取当前位置
|
||||||
|
- LuatOS 的 `io.exists()` 只检查文件, 不检查目录 (用 `io.lsdir` 验证目录)
|
||||||
|
- LuatOS 的 `f:read()` 在 closed file 上调用会失败 (PC 是 error)
|
||||||
|
- `io.mkdir` 在不同 FS 上对父目录缺失的容忍度不同 (ram 自动创建, 其他需要先 mkdir 父)
|
||||||
|
|
||||||
|
## 文件清单
|
||||||
|
|
||||||
|
```
|
||||||
|
testcase/utest/fs/vfs_uniform/ ← 共享框架 (base)
|
||||||
|
├── scripts/
|
||||||
|
│ ├── vfs_common.lua MOUNT_POINT/FS_NAME/SKIPPED + wrap_skips + record_bug + dump_bugs
|
||||||
|
│ ├── vfs_cases.lua 30 个 test_* 用例
|
||||||
|
│ ├── mount_ram.lua
|
||||||
|
│ ├── mount_posix.lua
|
||||||
|
│ ├── mount_lfs2.lua
|
||||||
|
│ ├── mount_fatfs.lua
|
||||||
|
│ ├── mount_tfs.lua
|
||||||
|
│ ├── mount_pgfs.lua
|
||||||
|
│ ├── metas.json
|
||||||
|
│ └── AGENTS.md (in parent dir)
|
||||||
|
|
||||||
|
testcase/utest/fs/vfs_uniform_<fs>/ ← 各 FS 子任务
|
||||||
|
├── scripts/
|
||||||
|
│ ├── main.lua testrunner.runBatch 入口
|
||||||
|
│ ├── vfs_uniform_mount.lua shim
|
||||||
|
│ └── metas.json
|
||||||
|
|
||||||
|
docs/known_issues.md bug 聚合 (本结果)
|
||||||
|
docs/vfs_uniform_results.md 本文件 (汇总)
|
||||||
|
testresult/vfs_uniform/ 原始运行日志
|
||||||
|
```
|
||||||
|
|
||||||
|
## 复现方式
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd D:/github/LuatOS
|
||||||
|
export LUAT_USE_UTEST=y
|
||||||
|
bsp/pc/build_windows_64bit_msvc.bat
|
||||||
|
|
||||||
|
mkdir -p testresult/vfs_uniform/posix_tmp
|
||||||
|
|
||||||
|
bsp/pc/build/out/luatos-lua.exe \
|
||||||
|
testcase/common/scripts/ \
|
||||||
|
testcase/utest/fs/vfs_uniform/scripts/ \
|
||||||
|
testcase/utest/fs/vfs_uniform_<fs>/scripts/ \
|
||||||
|
2>&1 | tee testresult/vfs_uniform/<fs>_run.log
|
||||||
|
```
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
1. ~~修复 pgfs 的 FTL "no free blocks" 问题 (优先级 high)~~ — 本轮已修 (commit `19e49d586`)
|
||||||
|
2. ~~修复 tfs mount 的 name marker 问题 (luat_little_flash_tfs.c:478)~~ — 本轮已修 (commit `90267fbbc`)
|
||||||
|
3. ~~修复 fatfs 在 PC BSP 上的模块加载 (luat_base_mini.c 实际未注册)~~ — 本轮已修
|
||||||
|
- 主分支 commit `419030781` (require 风格探针) → 修订版在
|
||||||
|
`.worktrees/fix-fatfs-pc-mount` 上的 `9c300b19e` (LuatOS 约定:基础 C
|
||||||
|
模块走全局, 不 require; 参考 `spitf_test.lua:13`)
|
||||||
|
- 修订版需要把 `419030781` 替换/移除, 历史清理待协调
|
||||||
|
4. 修复 lfs2 的 refcount 缺失 (在 luat_fs_lfs2.c:134 加引用检查) — MED, 排期中
|
||||||
|
5. 修复 pgfs 的 refcount 缺失 (pgfs 同 lfs2) — MED, 排期中
|
||||||
|
6. 评估 posix 在 Linux/macOS 上的语义 (Windows rename 不能覆盖是 OS 行为)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Lua 虚拟机的源码
|
||||||
|
|
||||||
|
来源: 原版Lua 5.3.5, 含2019.12.31前已发布的官方修正
|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
```
|
||||||
|
inculde -- 头文件
|
||||||
|
src -- C 源码
|
||||||
|
```
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
/*
|
||||||
|
Interface definitions for bget.c, the memory management package.
|
||||||
|
*/
|
||||||
|
|
||||||
|
typedef long bufsize;
|
||||||
|
void bpool(void *buffer, bufsize len);
|
||||||
|
void *bget(bufsize size);
|
||||||
|
void *bgetz(bufsize size);
|
||||||
|
void *bgetr(void *buffer, bufsize newsize);
|
||||||
|
void brel(void *buf);
|
||||||
|
void bectl(int (*compact)(bufsize sizereq, int sequence), void *(*acquire)(bufsize size), void (*release)(void *buf), bufsize pool_incr);
|
||||||
|
void bstats(bufsize *curalloc, bufsize *totfree, bufsize *maxfree, unsigned long *nget, unsigned long *nrel);
|
||||||
|
void bstatse(bufsize *pool_incr, long *npool, unsigned long *npget, unsigned long *nprel, unsigned long *ndget, unsigned long *ndrel);
|
||||||
|
void bufdump(void *buf);
|
||||||
|
void bpoold(void *pool, int dumpalloc, int dumpfree);
|
||||||
|
int bpoolv(void *pool);
|
||||||
|
bufsize bstatsmaxget(void);
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lapi.h,v 2.9.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Auxiliary functions from Lua API
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lapi_h
|
||||||
|
#define lapi_h
|
||||||
|
|
||||||
|
|
||||||
|
#include "llimits.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
|
||||||
|
#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \
|
||||||
|
"stack overflow");}
|
||||||
|
|
||||||
|
#define adjustresults(L,nres) \
|
||||||
|
{ if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
|
||||||
|
|
||||||
|
#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \
|
||||||
|
"not enough elements in the stack")
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lauxlib.h,v 1.131.1.1 2017/04/19 17:20:42 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_loadfilex' */
|
||||||
|
#define LUA_ERRFILE (LUA_ERRERR+1)
|
||||||
|
|
||||||
|
|
||||||
|
/* key, in the registry, for table of loaded modules */
|
||||||
|
#define LUA_LOADED_TABLE "_LOADED"
|
||||||
|
|
||||||
|
|
||||||
|
/* key, in the registry, for table of preloaded loaders */
|
||||||
|
#define LUA_PRELOAD_TABLE "_PRELOAD"
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct luaL_Reg {
|
||||||
|
const char *name;
|
||||||
|
lua_CFunction func;
|
||||||
|
} luaL_Reg;
|
||||||
|
|
||||||
|
|
||||||
|
#define LUAL_NUMSIZES (sizeof(lua_Integer)*16 + sizeof(lua_Number))
|
||||||
|
|
||||||
|
LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz);
|
||||||
|
#define luaL_checkversion(L) \
|
||||||
|
luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES)
|
||||||
|
|
||||||
|
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 const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
|
||||||
|
LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
|
||||||
|
LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
|
||||||
|
size_t *l);
|
||||||
|
LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
|
||||||
|
const char *def, size_t *l);
|
||||||
|
LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);
|
||||||
|
LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);
|
||||||
|
|
||||||
|
LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
|
||||||
|
LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
|
||||||
|
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 arg, int t);
|
||||||
|
LUALIB_API void (luaL_checkany) (lua_State *L, int arg);
|
||||||
|
|
||||||
|
LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
|
||||||
|
LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname);
|
||||||
|
LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, 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 arg, const char *def,
|
||||||
|
const char *const lst[]);
|
||||||
|
|
||||||
|
LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
|
||||||
|
LUALIB_API int (luaL_execresult) (lua_State *L, int stat);
|
||||||
|
|
||||||
|
/* predefined 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_loadfilex) (lua_State *L, const char *filename,
|
||||||
|
const char *mode);
|
||||||
|
|
||||||
|
#define luaL_loadfile(L,f) luaL_loadfilex(L,f,NULL)
|
||||||
|
|
||||||
|
LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz,
|
||||||
|
const char *name, const char *mode);
|
||||||
|
LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
|
||||||
|
|
||||||
|
LUALIB_API lua_State *(luaL_newstate) (void);
|
||||||
|
|
||||||
|
LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
|
||||||
|
|
||||||
|
LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
|
||||||
|
const char *r);
|
||||||
|
|
||||||
|
LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
|
||||||
|
|
||||||
|
LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);
|
||||||
|
|
||||||
|
LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,
|
||||||
|
const char *msg, int level);
|
||||||
|
|
||||||
|
LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
|
||||||
|
lua_CFunction openf, int glb);
|
||||||
|
|
||||||
|
/*
|
||||||
|
** ===============================================================
|
||||||
|
** some useful macros
|
||||||
|
** ===============================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#define luaL_newlibtable(L,l) \
|
||||||
|
lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)
|
||||||
|
|
||||||
|
#define luaL_newlib(L,l) \
|
||||||
|
(luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
|
||||||
|
|
||||||
|
#define luaL_argcheck(L, cond,arg,extramsg) \
|
||||||
|
((void)((cond) || luaL_argerror(L, (arg), (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_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)))
|
||||||
|
|
||||||
|
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** Generic Buffer manipulation
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
typedef struct luaL_Buffer {
|
||||||
|
char *b; /* buffer address */
|
||||||
|
size_t size; /* buffer size */
|
||||||
|
size_t n; /* number of characters in buffer */
|
||||||
|
lua_State *L;
|
||||||
|
char initb[LUAL_BUFFERSIZE]; /* initial buffer */
|
||||||
|
} luaL_Buffer;
|
||||||
|
|
||||||
|
|
||||||
|
#define luaL_addchar(B,c) \
|
||||||
|
((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \
|
||||||
|
((B)->b[(B)->n++] = (c)))
|
||||||
|
|
||||||
|
#define luaL_addsize(B,s) ((B)->n += (s))
|
||||||
|
|
||||||
|
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
|
||||||
|
LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
|
||||||
|
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);
|
||||||
|
LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz);
|
||||||
|
LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);
|
||||||
|
|
||||||
|
#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** File handles for IO library
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
** A file handle is a userdata with metatable 'LUA_FILEHANDLE' and
|
||||||
|
** initial structure 'luaL_Stream' (it may contain other fields
|
||||||
|
** after that initial structure).
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define LUA_FILEHANDLE "FILE*"
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct luaL_Stream {
|
||||||
|
FILE *f; /* stream (NULL for incompletely created streams) */
|
||||||
|
lua_CFunction closef; /* to close stream (NULL for closed streams) */
|
||||||
|
} luaL_Stream;
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* compatibility with old module system */
|
||||||
|
#if defined(LUA_COMPAT_MODULE)
|
||||||
|
|
||||||
|
LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname,
|
||||||
|
int sizehint);
|
||||||
|
LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,
|
||||||
|
const luaL_Reg *l, int nup);
|
||||||
|
|
||||||
|
#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0))
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** "Abstraction Layer" for basic report of messages and errors
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
void luat_nprint(char *s, size_t l);
|
||||||
|
void luat_log_log(int level, const char* tag, const char* _fmt, ...); // 4 is ERROR
|
||||||
|
#define lua_writestring(s,l) luat_nprint(s, l)
|
||||||
|
#define lua_writestringerror(s,p) luat_log_log(4, "lua.err",s,p)
|
||||||
|
|
||||||
|
/* print a string */
|
||||||
|
#if !defined(lua_writestring)
|
||||||
|
#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* print a newline and flush the output */
|
||||||
|
#if !defined(lua_writeline)
|
||||||
|
#define lua_writeline() (lua_writestring("\n", 1))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* print an error message */
|
||||||
|
#if !defined(lua_writestringerror)
|
||||||
|
#define lua_writestringerror(s,p) \
|
||||||
|
(fprintf(stderr, (s), (p)), fflush(stderr))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {============================================================
|
||||||
|
** Compatibility with deprecated conversions
|
||||||
|
** =============================================================
|
||||||
|
*/
|
||||||
|
#if defined(LUA_COMPAT_APIINTCASTS)
|
||||||
|
|
||||||
|
#define luaL_checkunsigned(L,a) ((lua_Unsigned)luaL_checkinteger(L,a))
|
||||||
|
#define luaL_optunsigned(L,a,d) \
|
||||||
|
((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d)))
|
||||||
|
|
||||||
|
#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)))
|
||||||
|
|
||||||
|
#endif
|
||||||
|
/* }============================================================ */
|
||||||
|
|
||||||
|
#include "rotable.h"
|
||||||
|
void luat_newlib(lua_State* L, const rotable_Reg* reg);
|
||||||
|
#include "rotable2.h"
|
||||||
|
void luat_newlib2(lua_State* L, const rotable_Reg_t* reg);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lcode.h,v 1.64.1.1 2017/04/19 17:20:42 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
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lctype.h,v 1.12.1.1 2013/04/12 18:48:47 roberto Exp $
|
||||||
|
** 'ctype' functions for Lua
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lctype_h
|
||||||
|
#define lctype_h
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** WARNING: the functions defined here do not necessarily correspond
|
||||||
|
** to the similar functions in the standard C ctype.h. They are
|
||||||
|
** optimized for the specific needs of Lua
|
||||||
|
*/
|
||||||
|
|
||||||
|
#if !defined(LUA_USE_CTYPE)
|
||||||
|
|
||||||
|
#if 'A' == 65 && '0' == 48
|
||||||
|
/* ASCII case: can use its own tables; faster and fixed */
|
||||||
|
#define LUA_USE_CTYPE 0
|
||||||
|
#else
|
||||||
|
/* must use standard C ctype */
|
||||||
|
#define LUA_USE_CTYPE 1
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#if !LUA_USE_CTYPE /* { */
|
||||||
|
|
||||||
|
#include <limits.h>
|
||||||
|
|
||||||
|
#include "llimits.h"
|
||||||
|
|
||||||
|
|
||||||
|
#define ALPHABIT 0
|
||||||
|
#define DIGITBIT 1
|
||||||
|
#define PRINTBIT 2
|
||||||
|
#define SPACEBIT 3
|
||||||
|
#define XDIGITBIT 4
|
||||||
|
|
||||||
|
|
||||||
|
#define MASK(B) (1 << (B))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** add 1 to char to allow index -1 (EOZ)
|
||||||
|
*/
|
||||||
|
#define testprop(c,p) (luai_ctype_[(c)+1] & (p))
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 'lalpha' (Lua alphabetic) and 'lalnum' (Lua alphanumeric) both include '_'
|
||||||
|
*/
|
||||||
|
#define lislalpha(c) testprop(c, MASK(ALPHABIT))
|
||||||
|
#define lislalnum(c) testprop(c, (MASK(ALPHABIT) | MASK(DIGITBIT)))
|
||||||
|
#define lisdigit(c) testprop(c, MASK(DIGITBIT))
|
||||||
|
#define lisspace(c) testprop(c, MASK(SPACEBIT))
|
||||||
|
#define lisprint(c) testprop(c, MASK(PRINTBIT))
|
||||||
|
#define lisxdigit(c) testprop(c, MASK(XDIGITBIT))
|
||||||
|
|
||||||
|
/*
|
||||||
|
** this 'ltolower' only works for alphabetic characters
|
||||||
|
*/
|
||||||
|
#define ltolower(c) ((c) | ('A' ^ 'a'))
|
||||||
|
|
||||||
|
|
||||||
|
/* two more entries for 0 and -1 (EOZ) */
|
||||||
|
LUAI_DDEC const lu_byte luai_ctype_[UCHAR_MAX + 2];
|
||||||
|
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
/*
|
||||||
|
** use standard C ctypes
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <ctype.h>
|
||||||
|
|
||||||
|
|
||||||
|
#define lislalpha(c) (isalpha(c) || (c) == '_')
|
||||||
|
#define lislalnum(c) (isalnum(c) || (c) == '_')
|
||||||
|
#define lisdigit(c) (isdigit(c))
|
||||||
|
#define lisspace(c) (isspace(c))
|
||||||
|
#define lisprint(c) (isprint(c))
|
||||||
|
#define lisxdigit(c) (isxdigit(c))
|
||||||
|
|
||||||
|
#define ltolower(c) (tolower(c))
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/*
|
||||||
|
** $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)
|
||||||
|
int getfuncline(Proto *p, int pc);
|
||||||
|
#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
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ldo.h,v 2.29.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Stack and Call structure of Lua
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef ldo_h
|
||||||
|
#define ldo_h
|
||||||
|
|
||||||
|
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lzio.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Macro to check stack size and grow stack if needed. Parameters
|
||||||
|
** 'pre'/'pos' allow the macro to preserve a pointer into the
|
||||||
|
** stack across reallocations, doing the work only when needed.
|
||||||
|
** 'condmovestack' is used in heavy tests to force a stack reallocation
|
||||||
|
** at every check.
|
||||||
|
*/
|
||||||
|
#define luaD_checkstackaux(L,n,pre,pos) \
|
||||||
|
if (L->stack_last - L->top <= (n)) \
|
||||||
|
{ pre; luaD_growstack(L, n); pos; } else { condmovestack(L,pre,pos); }
|
||||||
|
|
||||||
|
/* In general, 'pre'/'pos' are empty (nothing to save) */
|
||||||
|
#define luaD_checkstack(L,n) luaD_checkstackaux(L,n,(void)0,(void)0)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define savestack(L,p) ((char *)(p) - (char *)L->stack)
|
||||||
|
#define restorestack(L,n) ((TValue *)((char *)L->stack + (n)))
|
||||||
|
|
||||||
|
|
||||||
|
/* type of protected functions, to be ran by 'runprotected' */
|
||||||
|
typedef void (*Pfunc) (lua_State *L, void *ud);
|
||||||
|
|
||||||
|
LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
|
||||||
|
const char *mode);
|
||||||
|
LUAI_FUNC void luaD_hook (lua_State *L, int event, int line);
|
||||||
|
LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);
|
||||||
|
LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
|
||||||
|
LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults);
|
||||||
|
LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
|
||||||
|
ptrdiff_t oldtop, ptrdiff_t ef);
|
||||||
|
LUAI_FUNC int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult,
|
||||||
|
int nres);
|
||||||
|
LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);
|
||||||
|
LUAI_FUNC void luaD_growstack (lua_State *L, int n);
|
||||||
|
LUAI_FUNC void luaD_shrinkstack (lua_State *L);
|
||||||
|
LUAI_FUNC void luaD_inctop (lua_State *L);
|
||||||
|
|
||||||
|
LUAI_FUNC l_noret luaD_throw (lua_State *L, int errcode);
|
||||||
|
LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lfunc.h,v 2.15.1.1 2017/04/19 17:39:34 roberto Exp $
|
||||||
|
** Auxiliary functions to manipulate prototypes and closures
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lfunc_h
|
||||||
|
#define lfunc_h
|
||||||
|
|
||||||
|
|
||||||
|
#include "lobject.h"
|
||||||
|
|
||||||
|
|
||||||
|
#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \
|
||||||
|
cast(int, sizeof(TValue)*((n)-1)))
|
||||||
|
|
||||||
|
#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \
|
||||||
|
cast(int, sizeof(TValue *)*((n)-1)))
|
||||||
|
|
||||||
|
|
||||||
|
/* test whether thread is in 'twups' list */
|
||||||
|
#define isintwups(L) (L->twups != L)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** maximum number of upvalues in a closure (both C and Lua). (Value
|
||||||
|
** must fit in a VM register.)
|
||||||
|
*/
|
||||||
|
#define MAXUPVAL 255
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Upvalues for Lua closures
|
||||||
|
*/
|
||||||
|
struct UpVal {
|
||||||
|
TValue *v; /* points to stack or to its own value */
|
||||||
|
lu_mem refcount; /* reference counter */
|
||||||
|
union {
|
||||||
|
struct { /* (when open) */
|
||||||
|
UpVal *next; /* linked list */
|
||||||
|
int touched; /* mark to avoid cycles with dead threads */
|
||||||
|
} open;
|
||||||
|
TValue value; /* the value (when closed) */
|
||||||
|
} u;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define upisopen(up) ((up)->v != &(up)->u.value)
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC Proto *luaF_newproto (lua_State *L);
|
||||||
|
LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems);
|
||||||
|
LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems);
|
||||||
|
LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
|
||||||
|
LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
|
||||||
|
LUAI_FUNC void luaF_close (lua_State *L, StkId level);
|
||||||
|
LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
|
||||||
|
LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
|
||||||
|
int pc);
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lgc.h,v 2.91.1.1 2017/04/19 17:39:34 roberto Exp $
|
||||||
|
** 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. These lists have no meaning when the invariant
|
||||||
|
** is not being enforced (e.g., sweep phase).
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* how much to allocate before next GC step */
|
||||||
|
#if !defined(GCSTEPSIZE)
|
||||||
|
/* ~100 small strings */
|
||||||
|
#define GCSTEPSIZE (cast_int(100 * sizeof(TString)))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Possible states of the Garbage Collector
|
||||||
|
*/
|
||||||
|
#define GCSpropagate 0
|
||||||
|
#define GCSatomic 1
|
||||||
|
#define GCSswpallgc 2
|
||||||
|
#define GCSswpfinobj 3
|
||||||
|
#define GCSswptobefnz 4
|
||||||
|
#define GCSswpend 5
|
||||||
|
#define GCScallfin 6
|
||||||
|
#define GCSpause 7
|
||||||
|
|
||||||
|
|
||||||
|
#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(lu_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: */
|
||||||
|
#define WHITE0BIT 0 /* object is white (type 0) */
|
||||||
|
#define WHITE1BIT 1 /* object is white (type 1) */
|
||||||
|
#define BLACKBIT 2 /* object is black */
|
||||||
|
#define FINALIZEDBIT 3 /* object has been marked for finalization */
|
||||||
|
/* bit 7 is currently used by tests (luaL_checkmemory) */
|
||||||
|
|
||||||
|
#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) ^ WHITEBITS) & (ow)))
|
||||||
|
#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked)
|
||||||
|
|
||||||
|
#define changewhite(x) ((x)->marked ^= WHITEBITS)
|
||||||
|
#define gray2black(x) l_setbit((x)->marked, BLACKBIT)
|
||||||
|
|
||||||
|
#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 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))
|
||||||
|
|
||||||
|
#define luaC_upvalbarrier(L,uv) ( \
|
||||||
|
(iscollectable((uv)->v) && !upisopen(uv)) ? \
|
||||||
|
luaC_upvalbarrier_(L,uv) : 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, Table *o);
|
||||||
|
LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv);
|
||||||
|
LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
|
||||||
|
LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv);
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
/*
|
||||||
|
** $Id: llex.h,v 1.79.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Lexical Analyzer
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef llex_h
|
||||||
|
#define llex_h
|
||||||
|
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lzio.h"
|
||||||
|
|
||||||
|
|
||||||
|
#define FIRST_RESERVED 257
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(LUA_ENV)
|
||||||
|
#define LUA_ENV "_ENV"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* WARNING: if you change the order of this enumeration,
|
||||||
|
* grep "ORDER RESERVED"
|
||||||
|
*/
|
||||||
|
enum RESERVED {
|
||||||
|
/* terminal symbols denoted by reserved words */
|
||||||
|
TK_AND = FIRST_RESERVED, TK_BREAK,
|
||||||
|
TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
|
||||||
|
TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
|
||||||
|
TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
|
||||||
|
/* other terminal symbols */
|
||||||
|
TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE,
|
||||||
|
TK_SHL, TK_SHR,
|
||||||
|
TK_DBCOLON, TK_EOS,
|
||||||
|
TK_FLT, TK_INT, TK_NAME, TK_STRING
|
||||||
|
};
|
||||||
|
|
||||||
|
/* number of reserved words */
|
||||||
|
#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1))
|
||||||
|
|
||||||
|
|
||||||
|
typedef union {
|
||||||
|
lua_Number r;
|
||||||
|
lua_Integer i;
|
||||||
|
TString *ts;
|
||||||
|
} SemInfo; /* semantics information */
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct Token {
|
||||||
|
int token;
|
||||||
|
SemInfo seminfo;
|
||||||
|
} Token;
|
||||||
|
|
||||||
|
|
||||||
|
/* state of the lexer plus state of the parser when shared by all
|
||||||
|
functions */
|
||||||
|
typedef struct LexState {
|
||||||
|
int current; /* current character (charint) */
|
||||||
|
int linenumber; /* input line counter */
|
||||||
|
int lastline; /* line of last token 'consumed' */
|
||||||
|
Token t; /* current token */
|
||||||
|
Token lookahead; /* look ahead token */
|
||||||
|
struct FuncState *fs; /* current function (parser) */
|
||||||
|
struct lua_State *L;
|
||||||
|
ZIO *z; /* input stream */
|
||||||
|
Mbuffer *buff; /* buffer for tokens */
|
||||||
|
Table *h; /* to avoid collection/reuse strings */
|
||||||
|
struct Dyndata *dyd; /* dynamic structures used by the parser */
|
||||||
|
TString *source; /* current source name */
|
||||||
|
TString *envn; /* environment variable name */
|
||||||
|
} LexState;
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC void luaX_init (lua_State *L);
|
||||||
|
LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,
|
||||||
|
TString *source, int firstchar);
|
||||||
|
LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);
|
||||||
|
LUAI_FUNC void luaX_next (LexState *ls);
|
||||||
|
LUAI_FUNC int luaX_lookahead (LexState *ls);
|
||||||
|
LUAI_FUNC l_noret luaX_syntaxerror (LexState *ls, const char *s);
|
||||||
|
LUAI_FUNC const char *luaX_token2str (LexState *ls, int token);
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
/*
|
||||||
|
** $Id: llimits.h,v 1.141.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Limits, basic types, and some other 'installation-dependent' definitions
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef llimits_h
|
||||||
|
#define llimits_h
|
||||||
|
|
||||||
|
|
||||||
|
#include <limits.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count
|
||||||
|
** the total memory used by Lua (in bytes). Usually, 'size_t' and
|
||||||
|
** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines.
|
||||||
|
*/
|
||||||
|
#if defined(LUAI_MEM) /* { external definitions? */
|
||||||
|
typedef LUAI_UMEM lu_mem;
|
||||||
|
typedef LUAI_MEM l_mem;
|
||||||
|
#elif LUAI_BITSINT >= 32 /* }{ */
|
||||||
|
typedef size_t lu_mem;
|
||||||
|
typedef ptrdiff_t l_mem;
|
||||||
|
#else /* 16-bit ints */ /* }{ */
|
||||||
|
typedef unsigned long lu_mem;
|
||||||
|
typedef long l_mem;
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
/* chars used as small naturals (so that 'char' is reserved for characters) */
|
||||||
|
typedef unsigned char lu_byte;
|
||||||
|
|
||||||
|
|
||||||
|
/* maximum value for size_t */
|
||||||
|
#define MAX_SIZET ((size_t)(~(size_t)0))
|
||||||
|
|
||||||
|
/* maximum size visible for Lua (must be representable in a lua_Integer */
|
||||||
|
#define MAX_SIZE (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \
|
||||||
|
: (size_t)(LUA_MAXINTEGER))
|
||||||
|
|
||||||
|
|
||||||
|
#define MAX_LUMEM ((lu_mem)(~(lu_mem)0))
|
||||||
|
|
||||||
|
#define MAX_LMEM ((l_mem)(MAX_LUMEM >> 1))
|
||||||
|
|
||||||
|
|
||||||
|
#define MAX_INT INT_MAX /* maximum value of an int */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** conversion of pointer to unsigned integer:
|
||||||
|
** this is for hashing only; there is no problem if the integer
|
||||||
|
** cannot hold the whole pointer value
|
||||||
|
*/
|
||||||
|
#define point2uint(p) ((unsigned int)((size_t)(p) & UINT_MAX))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* type to ensure maximum alignment */
|
||||||
|
#if defined(LUAI_USER_ALIGNMENT_T)
|
||||||
|
typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
|
||||||
|
#else
|
||||||
|
typedef union {
|
||||||
|
lua_Number n;
|
||||||
|
double u;
|
||||||
|
void *s;
|
||||||
|
lua_Integer i;
|
||||||
|
long l;
|
||||||
|
} L_Umaxalign;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* types of 'usual argument conversions' for lua_Number and lua_Integer */
|
||||||
|
typedef LUAI_UACNUMBER l_uacNumber;
|
||||||
|
typedef LUAI_UACINT l_uacInt;
|
||||||
|
|
||||||
|
|
||||||
|
/* internal assertions for in-house debugging */
|
||||||
|
#if defined(lua_assert)
|
||||||
|
#define check_exp(c,e) (lua_assert(c), (e))
|
||||||
|
/* to avoid problems with conditions too long */
|
||||||
|
#define lua_longassert(c) ((c) ? (void)0 : lua_assert(0))
|
||||||
|
#else
|
||||||
|
#define lua_assert(c) ((void)0)
|
||||||
|
#define check_exp(c,e) (e)
|
||||||
|
#define lua_longassert(c) ((void)0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
** assertion for checking API calls
|
||||||
|
*/
|
||||||
|
#if !defined(luai_apicheck)
|
||||||
|
#define luai_apicheck(l,e) lua_assert(e)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define api_check(l,e,msg) luai_apicheck(l,(e) && msg)
|
||||||
|
|
||||||
|
|
||||||
|
/* macro to avoid warnings about unused variables */
|
||||||
|
#if !defined(UNUSED)
|
||||||
|
#define UNUSED(x) ((void)(x))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/* type casts (a macro highlights casts in the code) */
|
||||||
|
#define cast(t, exp) ((t)(exp))
|
||||||
|
|
||||||
|
#define cast_void(i) cast(void, (i))
|
||||||
|
#define cast_byte(i) cast(lu_byte, (i))
|
||||||
|
#define cast_num(i) cast(lua_Number, (i))
|
||||||
|
#define cast_int(i) cast(int, (i))
|
||||||
|
#define cast_uchar(i) cast(unsigned char, (i))
|
||||||
|
|
||||||
|
|
||||||
|
/* cast a signed lua_Integer to lua_Unsigned */
|
||||||
|
#if !defined(l_castS2U)
|
||||||
|
#define l_castS2U(i) ((lua_Unsigned)(i))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
** cast a lua_Unsigned to a signed lua_Integer; this cast is
|
||||||
|
** not strict ISO C, but two-complement architectures should
|
||||||
|
** work fine.
|
||||||
|
*/
|
||||||
|
#if !defined(l_castU2S)
|
||||||
|
#define l_castU2S(i) ((lua_Integer)(i))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** non-return type
|
||||||
|
*/
|
||||||
|
#if defined(__GNUC__)
|
||||||
|
#define l_noret void __attribute__((noreturn))
|
||||||
|
#elif defined(_MSC_VER) && _MSC_VER >= 1200
|
||||||
|
#define l_noret void __declspec(noreturn)
|
||||||
|
#else
|
||||||
|
#define l_noret void
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** maximum depth for nested C calls and syntactical nested non-terminals
|
||||||
|
** in a program. (Value must fit in an unsigned short int.)
|
||||||
|
*/
|
||||||
|
#if !defined(LUAI_MAXCCALLS)
|
||||||
|
#define LUAI_MAXCCALLS 200
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** type for virtual-machine instructions;
|
||||||
|
** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
|
||||||
|
*/
|
||||||
|
#if LUAI_BITSINT >= 32
|
||||||
|
typedef unsigned int Instruction;
|
||||||
|
#else
|
||||||
|
typedef unsigned long Instruction;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Maximum length for short strings, that is, strings that are
|
||||||
|
** internalized. (Cannot be smaller than reserved words or tags for
|
||||||
|
** metamethods, as these strings must be internalized;
|
||||||
|
** #("function") = 8, #("__newindex") = 10.)
|
||||||
|
*/
|
||||||
|
#if !defined(LUAI_MAXSHORTLEN)
|
||||||
|
#define LUAI_MAXSHORTLEN 40
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Initial size for the string table (must be power of 2).
|
||||||
|
** The Lua core alone registers ~50 strings (reserved words +
|
||||||
|
** metaevent keys + a few others). Libraries would typically add
|
||||||
|
** a few dozens more.
|
||||||
|
*/
|
||||||
|
#if !defined(MINSTRTABSIZE)
|
||||||
|
#define MINSTRTABSIZE 128
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Size of cache for strings in the API. 'N' is the number of
|
||||||
|
** sets (better be a prime) and "M" is the size of each set (M == 1
|
||||||
|
** makes a direct cache.)
|
||||||
|
*/
|
||||||
|
#if !defined(STRCACHE_N)
|
||||||
|
#define STRCACHE_N 53
|
||||||
|
#define STRCACHE_M 2
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/* minimum size for string buffer */
|
||||||
|
#if !defined(LUA_MINBUFFER)
|
||||||
|
#define LUA_MINBUFFER 32
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** macros that are executed whenever program enters the Lua core
|
||||||
|
** ('lua_lock') and leaves the core ('lua_unlock')
|
||||||
|
*/
|
||||||
|
#if !defined(lua_lock)
|
||||||
|
#define lua_lock(L) ((void) 0)
|
||||||
|
#define lua_unlock(L) ((void) 0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
** macro executed during Lua functions at points where the
|
||||||
|
** function can yield.
|
||||||
|
*/
|
||||||
|
#if !defined(luai_threadyield)
|
||||||
|
#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** these macros allow user-specific actions on threads when you defined
|
||||||
|
** LUAI_EXTRASPACE and need to do something extra when a thread is
|
||||||
|
** created/deleted/resumed/yielded.
|
||||||
|
*/
|
||||||
|
#if !defined(luai_userstateopen)
|
||||||
|
#define luai_userstateopen(L) ((void)L)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(luai_userstateclose)
|
||||||
|
#define luai_userstateclose(L) ((void)L)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(luai_userstatethread)
|
||||||
|
#define luai_userstatethread(L,L1) ((void)L)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(luai_userstatefree)
|
||||||
|
#define luai_userstatefree(L,L1) ((void)L)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(luai_userstateresume)
|
||||||
|
#define luai_userstateresume(L,n) ((void)L)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(luai_userstateyield)
|
||||||
|
#define luai_userstateyield(L,n) ((void)L)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** The luai_num* macros define the primitive operations over numbers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* floor division (defined as 'floor(a/b)') */
|
||||||
|
#if !defined(luai_numidiv)
|
||||||
|
#define luai_numidiv(L,a,b) ((void)L, l_floor(luai_numdiv(L,a,b)))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* float division */
|
||||||
|
#if !defined(luai_numdiv)
|
||||||
|
#define luai_numdiv(L,a,b) ((a)/(b))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
** modulo: defined as 'a - floor(a/b)*b'; this definition gives NaN when
|
||||||
|
** 'b' is huge, but the result should be 'a'. 'fmod' gives the result of
|
||||||
|
** 'a - trunc(a/b)*b', and therefore must be corrected when 'trunc(a/b)
|
||||||
|
** ~= floor(a/b)'. That happens when the division has a non-integer
|
||||||
|
** negative result, which is equivalent to the test below.
|
||||||
|
*/
|
||||||
|
#if !defined(luai_nummod)
|
||||||
|
#define luai_nummod(L,a,b,m) \
|
||||||
|
{ (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* exponentiation */
|
||||||
|
#if !defined(luai_numpow)
|
||||||
|
#define luai_numpow(L,a,b) ((void)L, l_mathop(pow)(a,b))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* the others are quite standard operations */
|
||||||
|
#if !defined(luai_numadd)
|
||||||
|
#define luai_numadd(L,a,b) ((a)+(b))
|
||||||
|
#define luai_numsub(L,a,b) ((a)-(b))
|
||||||
|
#define luai_nummul(L,a,b) ((a)*(b))
|
||||||
|
#define luai_numunm(L,a) (-(a))
|
||||||
|
#define luai_numeq(a,b) ((a)==(b))
|
||||||
|
#define luai_numlt(a,b) ((a)<(b))
|
||||||
|
#define luai_numle(a,b) ((a)<=(b))
|
||||||
|
#define luai_numisnan(a) (!luai_numeq((a), (a)))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** macro to control inclusion of some hard tests on stack reallocation
|
||||||
|
*/
|
||||||
|
//#define HARDSTACKTESTS
|
||||||
|
#if !defined(HARDSTACKTESTS)
|
||||||
|
#define condmovestack(L,pre,pos) ((void)0)
|
||||||
|
#else
|
||||||
|
/* realloc stack keeping its size */
|
||||||
|
#define condmovestack(L,pre,pos) \
|
||||||
|
{ int sz_ = (L)->stacksize; pre; luaD_reallocstack((L), sz_); pos; }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(HARDMEMTESTS)
|
||||||
|
#define condchangemem(L,pre,pos) ((void)0)
|
||||||
|
#else
|
||||||
|
#define condchangemem(L,pre,pos) \
|
||||||
|
{ if (G(L)->gcrunning) { pre; luaC_fullgc(L, 0); pos; } }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lmem.h,v 1.43.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Interface to Memory Manager
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lmem_h
|
||||||
|
#define lmem_h
|
||||||
|
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "llimits.h"
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** This macro reallocs a vector 'b' from 'on' to 'n' elements, where
|
||||||
|
** each element has size 'e'. In case of arithmetic overflow of the
|
||||||
|
** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because
|
||||||
|
** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e).
|
||||||
|
**
|
||||||
|
** (The macro is somewhat complex to avoid warnings: The 'sizeof'
|
||||||
|
** comparison avoids a runtime comparison when overflow cannot occur.
|
||||||
|
** The compiler should be able to optimize the real test by itself, but
|
||||||
|
** when it does it, it may give a warning about "comparison is always
|
||||||
|
** false due to limited range of data type"; the +1 tricks the compiler,
|
||||||
|
** avoiding this warning but also this optimization.)
|
||||||
|
*/
|
||||||
|
#define luaM_reallocv(L,b,on,n,e) \
|
||||||
|
(((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \
|
||||||
|
? luaM_toobig(L, n, e, "array") : cast_void(0)) , \
|
||||||
|
luaM_realloc_(L, (b), (on)*(e), (n)*(e)))
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Arrays of chars do not need any test
|
||||||
|
*/
|
||||||
|
#define luaM_reallocvchar(L,b,on,n) \
|
||||||
|
cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))
|
||||||
|
|
||||||
|
#define luaM_freemem(L, b, s) luaM_realloc_(L, (b), (s), 0)
|
||||||
|
#define luaM_free(L, b) luaM_realloc_(L, (b), sizeof(*(b)), 0)
|
||||||
|
#define luaM_freearray(L, b, n) luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0)
|
||||||
|
|
||||||
|
#define luaM_malloc(L,s) luaM_realloc_(L, NULL, 0, (s))
|
||||||
|
#define luaM_new(L,t) cast(t *, luaM_malloc(L, sizeof(t)))
|
||||||
|
#define luaM_newvector(L,n,t) \
|
||||||
|
cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))
|
||||||
|
|
||||||
|
#define luaM_newobject(L,tag,s) luaM_realloc_(L, NULL, tag, (s))
|
||||||
|
|
||||||
|
#define luaM_growvector(L,v,nelems,size,t,limit,e) \
|
||||||
|
if ((nelems)+1 > (size)) \
|
||||||
|
((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
|
||||||
|
|
||||||
|
#define luaM_reallocvector(L, v,oldn,n,t) \
|
||||||
|
((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))
|
||||||
|
|
||||||
|
LUAI_FUNC l_noret luaM_toobig (lua_State *L, size_t n, size_t e, const char *what);
|
||||||
|
|
||||||
|
/* not to be called directly */
|
||||||
|
LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
|
||||||
|
size_t size);
|
||||||
|
LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size,
|
||||||
|
size_t size_elem, int limit,
|
||||||
|
const char *what);
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,587 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lobject.h,v 2.117.1.1 2017/04/19 17:39:34 roberto Exp $
|
||||||
|
** Type definitions for Lua objects
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef lobject_h
|
||||||
|
#define lobject_h
|
||||||
|
|
||||||
|
|
||||||
|
#include <stdarg.h>
|
||||||
|
|
||||||
|
|
||||||
|
#include "llimits.h"
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Extra tags for non-values
|
||||||
|
*/
|
||||||
|
#define LUA_TPROTO LUA_NUMTAGS /* function prototypes */
|
||||||
|
#define LUA_TDEADKEY (LUA_NUMTAGS+1) /* removed keys in tables */
|
||||||
|
|
||||||
|
/*
|
||||||
|
** number of all possible tags (including LUA_TNONE but excluding DEADKEY)
|
||||||
|
*/
|
||||||
|
#define LUA_TOTALTAGS (LUA_TPROTO + 2)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** tags for Tagged Values have the following use of bits:
|
||||||
|
** bits 0-3: actual tag (a LUA_T* value)
|
||||||
|
** bits 4-5: variant bits
|
||||||
|
** bit 6: whether value is collectable
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** LUA_TFUNCTION variants:
|
||||||
|
** 0 - Lua function
|
||||||
|
** 1 - light C function
|
||||||
|
** 2 - regular C function (closure)
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Variant tags for functions */
|
||||||
|
#define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */
|
||||||
|
#define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */
|
||||||
|
#define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */
|
||||||
|
|
||||||
|
|
||||||
|
/* Variant tags for strings */
|
||||||
|
#define LUA_TSHRSTR (LUA_TSTRING | (0 << 4)) /* short strings */
|
||||||
|
#define LUA_TLNGSTR (LUA_TSTRING | (1 << 4)) /* long strings */
|
||||||
|
|
||||||
|
|
||||||
|
/* Variant tags for numbers */
|
||||||
|
#define LUA_TNUMFLT (LUA_TNUMBER | (0 << 4)) /* float numbers */
|
||||||
|
#define LUA_TNUMINT (LUA_TNUMBER | (1 << 4)) /* integer numbers */
|
||||||
|
|
||||||
|
|
||||||
|
/* Bit mark for collectable types */
|
||||||
|
#define BIT_ISCOLLECTABLE (1 << 6)
|
||||||
|
|
||||||
|
/* mark a tag as collectable */
|
||||||
|
#define ctb(t) ((t) | BIT_ISCOLLECTABLE)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Common type for all collectable objects
|
||||||
|
*/
|
||||||
|
typedef struct GCObject GCObject;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Common Header for all collectable objects (in macro form, to be
|
||||||
|
** included in other objects)
|
||||||
|
*/
|
||||||
|
#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Common type has only the common header
|
||||||
|
*/
|
||||||
|
struct GCObject {
|
||||||
|
CommonHeader;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Tagged Values. This is the basic representation of values in Lua,
|
||||||
|
** an actual value plus a tag with its type.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Union of all Lua values
|
||||||
|
*/
|
||||||
|
typedef union Value {
|
||||||
|
GCObject *gc; /* collectable objects */
|
||||||
|
void *p; /* light userdata */
|
||||||
|
int b; /* booleans */
|
||||||
|
lua_CFunction f; /* light C functions */
|
||||||
|
lua_Integer i; /* integer numbers */
|
||||||
|
lua_Number n; /* float numbers */
|
||||||
|
} Value;
|
||||||
|
|
||||||
|
|
||||||
|
#define TValuefields Value value_; int tt_
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct lua_TValue {
|
||||||
|
TValuefields;
|
||||||
|
} TValue;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* macro defining a nil value */
|
||||||
|
#define NILCONSTANT {NULL}, LUA_TNIL
|
||||||
|
|
||||||
|
|
||||||
|
#define val_(o) ((o)->value_)
|
||||||
|
|
||||||
|
|
||||||
|
/* raw type tag of a TValue */
|
||||||
|
#define rttype(o) ((o)->tt_)
|
||||||
|
|
||||||
|
/* tag with no variants (bits 0-3) */
|
||||||
|
#define novariant(x) ((x) & 0x0F)
|
||||||
|
|
||||||
|
/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */
|
||||||
|
#define ttype(o) (rttype(o) & 0x3F)
|
||||||
|
|
||||||
|
/* type tag of a TValue with no variants (bits 0-3) */
|
||||||
|
#define ttnov(o) (novariant(rttype(o)))
|
||||||
|
|
||||||
|
|
||||||
|
/* Macros to test type */
|
||||||
|
#define checktag(o,t) (rttype(o) == (t))
|
||||||
|
#define checktype(o,t) (ttnov(o) == (t))
|
||||||
|
#define ttisnumber(o) checktype((o), LUA_TNUMBER)
|
||||||
|
#define ttisfloat(o) checktag((o), LUA_TNUMFLT)
|
||||||
|
#define ttisinteger(o) checktag((o), LUA_TNUMINT)
|
||||||
|
#define ttisnil(o) checktag((o), LUA_TNIL)
|
||||||
|
#define ttisboolean(o) checktag((o), LUA_TBOOLEAN)
|
||||||
|
#define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA)
|
||||||
|
#define ttisstring(o) checktype((o), LUA_TSTRING)
|
||||||
|
#define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR))
|
||||||
|
#define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR))
|
||||||
|
#define ttistable(o) checktag((o), ctb(LUA_TTABLE))
|
||||||
|
#define ttisfunction(o) checktype(o, LUA_TFUNCTION)
|
||||||
|
#define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION)
|
||||||
|
#define ttisCclosure(o) checktag((o), ctb(LUA_TCCL))
|
||||||
|
#define ttisLclosure(o) checktag((o), ctb(LUA_TLCL))
|
||||||
|
#define ttislcf(o) checktag((o), LUA_TLCF)
|
||||||
|
#define ttisfulluserdata(o) checktag((o), ctb(LUA_TUSERDATA))
|
||||||
|
#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD))
|
||||||
|
#define ttisdeadkey(o) checktag((o), LUA_TDEADKEY)
|
||||||
|
|
||||||
|
|
||||||
|
/* Macros to access values */
|
||||||
|
#define ivalue(o) check_exp(ttisinteger(o), val_(o).i)
|
||||||
|
#define fltvalue(o) check_exp(ttisfloat(o), val_(o).n)
|
||||||
|
#define nvalue(o) check_exp(ttisnumber(o), \
|
||||||
|
(ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))
|
||||||
|
#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)
|
||||||
|
#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
|
||||||
|
#define tsvalue(o) check_exp(ttisstring(o), gco2ts(val_(o).gc))
|
||||||
|
#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc))
|
||||||
|
#define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc))
|
||||||
|
#define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc))
|
||||||
|
#define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc))
|
||||||
|
#define fvalue(o) check_exp(ttislcf(o), val_(o).f)
|
||||||
|
#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc))
|
||||||
|
#define bvalue(o) check_exp(ttisboolean(o), val_(o).b)
|
||||||
|
#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc))
|
||||||
|
/* a dead value may get the 'gc' field, but cannot access its contents */
|
||||||
|
#define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc))
|
||||||
|
|
||||||
|
#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
|
||||||
|
|
||||||
|
|
||||||
|
#define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE)
|
||||||
|
|
||||||
|
|
||||||
|
/* Macros for internal tests */
|
||||||
|
#define righttt(obj) (ttype(obj) == gcvalue(obj)->tt)
|
||||||
|
|
||||||
|
#define checkliveness(L,obj) \
|
||||||
|
lua_longassert(!iscollectable(obj) || \
|
||||||
|
(righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)))))
|
||||||
|
|
||||||
|
|
||||||
|
/* Macros to set values */
|
||||||
|
#define settt_(o,t) ((o)->tt_=(t))
|
||||||
|
|
||||||
|
#define setfltvalue(obj,x) \
|
||||||
|
{ TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); }
|
||||||
|
|
||||||
|
#define chgfltvalue(obj,x) \
|
||||||
|
{ TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); }
|
||||||
|
|
||||||
|
#define setivalue(obj,x) \
|
||||||
|
{ TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_TNUMINT); }
|
||||||
|
|
||||||
|
#define chgivalue(obj,x) \
|
||||||
|
{ TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); }
|
||||||
|
|
||||||
|
#define setnilvalue(obj) settt_(obj, LUA_TNIL)
|
||||||
|
|
||||||
|
#define setfvalue(obj,x) \
|
||||||
|
{ TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); }
|
||||||
|
|
||||||
|
#define setpvalue(obj,x) \
|
||||||
|
{ TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); }
|
||||||
|
|
||||||
|
#define setbvalue(obj,x) \
|
||||||
|
{ TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }
|
||||||
|
|
||||||
|
#define setgcovalue(L,obj,x) \
|
||||||
|
{ TValue *io = (obj); GCObject *i_g=(x); \
|
||||||
|
val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }
|
||||||
|
|
||||||
|
#define setsvalue(L,obj,x) \
|
||||||
|
{ TValue *io = (obj); TString *x_ = (x); \
|
||||||
|
val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
#define setuvalue(L,obj,x) \
|
||||||
|
{ TValue *io = (obj); Udata *x_ = (x); \
|
||||||
|
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
#define setthvalue(L,obj,x) \
|
||||||
|
{ TValue *io = (obj); lua_State *x_ = (x); \
|
||||||
|
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTHREAD)); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
#define setclLvalue(L,obj,x) \
|
||||||
|
{ TValue *io = (obj); LClosure *x_ = (x); \
|
||||||
|
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
#define setclCvalue(L,obj,x) \
|
||||||
|
{ TValue *io = (obj); CClosure *x_ = (x); \
|
||||||
|
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
#define sethvalue(L,obj,x) \
|
||||||
|
{ TValue *io = (obj); Table *x_ = (x); \
|
||||||
|
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTABLE)); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
#define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define setobj(L,obj1,obj2) \
|
||||||
|
{ TValue *io1=(obj1); *io1 = *(obj2); \
|
||||||
|
(void)L; checkliveness(L,io1); }
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** different types of assignments, according to destination
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* from stack to (same) stack */
|
||||||
|
#define setobjs2s setobj
|
||||||
|
/* to stack (not from same stack) */
|
||||||
|
#define setobj2s setobj
|
||||||
|
#define setsvalue2s setsvalue
|
||||||
|
#define sethvalue2s sethvalue
|
||||||
|
#define setptvalue2s setptvalue
|
||||||
|
/* from table to same table */
|
||||||
|
#define setobjt2t setobj
|
||||||
|
/* to new object */
|
||||||
|
#define setobj2n setobj
|
||||||
|
#define setsvalue2n setsvalue
|
||||||
|
|
||||||
|
/* to table (define it as an expression to be used in macros) */
|
||||||
|
#define setobj2t(L,o1,o2) ((void)L, *(o1)=*(o2), checkliveness(L,(o1)))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** types and prototypes
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
typedef TValue *StkId; /* index to stack elements */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Header for string value; string bytes follow the end of this structure
|
||||||
|
** (aligned according to 'UTString'; see next).
|
||||||
|
*/
|
||||||
|
typedef struct TString {
|
||||||
|
CommonHeader;
|
||||||
|
#if defined(__LUATOS_SMALL_RAM__) && defined(__LUATOS_SCRIPT_BASE__)
|
||||||
|
struct
|
||||||
|
{
|
||||||
|
uint16_t extra:5;
|
||||||
|
uint16_t shrlen:6;
|
||||||
|
uint16_t static_flag:5;
|
||||||
|
};
|
||||||
|
unsigned int hash;
|
||||||
|
union {
|
||||||
|
struct
|
||||||
|
{
|
||||||
|
uint32_t lnglen:17;/* length for long strings */
|
||||||
|
uint32_t static_offset:15;
|
||||||
|
};
|
||||||
|
struct TString *hnext; /* linked list for hash table */
|
||||||
|
|
||||||
|
} u;
|
||||||
|
#else
|
||||||
|
lu_byte extra; /* reserved words for short strings; "has hash" for longs */
|
||||||
|
lu_byte shrlen; /* length for short strings */
|
||||||
|
unsigned int hash;
|
||||||
|
union {
|
||||||
|
size_t lnglen; /* length for long strings */
|
||||||
|
struct TString *hnext; /* linked list for hash table */
|
||||||
|
} u;
|
||||||
|
#endif
|
||||||
|
} TString;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Ensures that address after this type is always fully aligned.
|
||||||
|
*/
|
||||||
|
typedef union UTString {
|
||||||
|
L_Umaxalign dummy; /* ensures maximum alignment for strings */
|
||||||
|
TString tsv;
|
||||||
|
} UTString;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Get the actual string (array of bytes) from a 'TString'.
|
||||||
|
** (Access to 'extra' ensures that value is really a 'TString'.)
|
||||||
|
*/
|
||||||
|
#if defined(__LUATOS_SMALL_RAM__) && defined(__LUATOS_SCRIPT_BASE__)
|
||||||
|
char *getstr(TString *ts);
|
||||||
|
#else
|
||||||
|
#define getstr(ts) \
|
||||||
|
check_exp(sizeof((ts)->extra), cast(char *, (ts)) + sizeof(UTString))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* get the actual string (array of bytes) from a Lua value */
|
||||||
|
#define svalue(o) getstr(tsvalue(o))
|
||||||
|
|
||||||
|
/* get string length from 'TString *s' */
|
||||||
|
#define tsslen(s) ((s)->tt == LUA_TSHRSTR ? (s)->shrlen : (s)->u.lnglen)
|
||||||
|
|
||||||
|
/* get string length from 'TValue *o' */
|
||||||
|
#define vslen(o) tsslen(tsvalue(o))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Header for userdata; memory area follows the end of this structure
|
||||||
|
** (aligned according to 'UUdata'; see next).
|
||||||
|
*/
|
||||||
|
typedef struct Udata {
|
||||||
|
CommonHeader;
|
||||||
|
lu_byte ttuv_; /* user value's tag */
|
||||||
|
struct Table *metatable;
|
||||||
|
size_t len; /* number of bytes */
|
||||||
|
union Value user_; /* user value */
|
||||||
|
} Udata;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Ensures that address after this type is always fully aligned.
|
||||||
|
*/
|
||||||
|
typedef union UUdata {
|
||||||
|
L_Umaxalign dummy; /* ensures maximum alignment for 'local' udata */
|
||||||
|
Udata uv;
|
||||||
|
} UUdata;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Get the address of memory block inside 'Udata'.
|
||||||
|
** (Access to 'ttuv_' ensures that value is really a 'Udata'.)
|
||||||
|
*/
|
||||||
|
#define getudatamem(u) \
|
||||||
|
check_exp(sizeof((u)->ttuv_), (cast(char*, (u)) + sizeof(UUdata)))
|
||||||
|
|
||||||
|
#define setuservalue(L,u,o) \
|
||||||
|
{ const TValue *io=(o); Udata *iu = (u); \
|
||||||
|
iu->user_ = io->value_; iu->ttuv_ = rttype(io); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
|
||||||
|
#define getuservalue(L,u,o) \
|
||||||
|
{ TValue *io=(o); const Udata *iu = (u); \
|
||||||
|
io->value_ = iu->user_; settt_(io, iu->ttuv_); \
|
||||||
|
checkliveness(L,io); }
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Description of an upvalue for function prototypes
|
||||||
|
*/
|
||||||
|
typedef struct Upvaldesc {
|
||||||
|
TString *name; /* upvalue name (for debug information) */
|
||||||
|
lu_byte instack; /* whether it is in stack (register) */
|
||||||
|
lu_byte idx; /* index of upvalue (in stack or in outer function's list) */
|
||||||
|
} Upvaldesc;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Description of a local variable for function prototypes
|
||||||
|
** (used for debug information)
|
||||||
|
*/
|
||||||
|
typedef struct LocVar {
|
||||||
|
TString *varname;
|
||||||
|
#ifdef __LUATOS_SMALL_RAM__
|
||||||
|
uint16_t startpc;
|
||||||
|
uint16_t endpc;
|
||||||
|
#else
|
||||||
|
int startpc; /* first point where variable is active */
|
||||||
|
int endpc; /* first point where variable is dead */
|
||||||
|
#endif
|
||||||
|
} LocVar;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Function Prototypes
|
||||||
|
*/
|
||||||
|
typedef struct Proto {
|
||||||
|
CommonHeader;
|
||||||
|
lu_byte numparams; /* number of fixed parameters */
|
||||||
|
lu_byte is_vararg;
|
||||||
|
lu_byte maxstacksize; /* number of registers needed by this function */
|
||||||
|
#ifdef __LUATOS_SMALL_RAM__
|
||||||
|
uint16_t sizeupvalues; /* size of 'upvalues' */
|
||||||
|
uint16_t sizek; /* size of 'k' */
|
||||||
|
uint16_t sizecode;
|
||||||
|
uint16_t sizelineinfo;
|
||||||
|
uint16_t sizep; /* size of 'p' */
|
||||||
|
uint16_t sizelocvars;
|
||||||
|
uint16_t linedefined;
|
||||||
|
uint16_t lastlinedefined;
|
||||||
|
#else
|
||||||
|
int sizeupvalues; /* size of 'upvalues' */
|
||||||
|
int sizek; /* size of 'k' */
|
||||||
|
int sizecode;
|
||||||
|
int sizelineinfo;
|
||||||
|
int sizep; /* size of 'p' */
|
||||||
|
int sizelocvars;
|
||||||
|
int linedefined; /* debug information */
|
||||||
|
int lastlinedefined; /* debug information */
|
||||||
|
#endif
|
||||||
|
TValue *k; /* constants used by the function */
|
||||||
|
Instruction *code; /* opcodes */
|
||||||
|
struct Proto **p; /* functions defined inside the function */
|
||||||
|
int *lineinfo; /* map from opcodes to source lines (debug information) */
|
||||||
|
LocVar *locvars; /* information about local variables (debug information) */
|
||||||
|
Upvaldesc *upvalues; /* upvalue information */
|
||||||
|
struct LClosure *cache; /* last-created closure with this prototype */
|
||||||
|
TString *source; /* used for debug information */
|
||||||
|
GCObject *gclist;
|
||||||
|
} Proto;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Lua Upvalues
|
||||||
|
*/
|
||||||
|
typedef struct UpVal UpVal;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Closures
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define ClosureHeader \
|
||||||
|
CommonHeader; lu_byte nupvalues; GCObject *gclist
|
||||||
|
|
||||||
|
typedef struct CClosure {
|
||||||
|
ClosureHeader;
|
||||||
|
lua_CFunction f;
|
||||||
|
TValue upvalue[1]; /* list of upvalues */
|
||||||
|
} CClosure;
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct LClosure {
|
||||||
|
ClosureHeader;
|
||||||
|
struct Proto *p;
|
||||||
|
UpVal *upvals[1]; /* list of upvalues */
|
||||||
|
} LClosure;
|
||||||
|
|
||||||
|
|
||||||
|
typedef union Closure {
|
||||||
|
CClosure c;
|
||||||
|
LClosure l;
|
||||||
|
} Closure;
|
||||||
|
|
||||||
|
|
||||||
|
#define isLfunction(o) ttisLclosure(o)
|
||||||
|
|
||||||
|
#define getproto(o) (clLvalue(o)->p)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Tables
|
||||||
|
*/
|
||||||
|
|
||||||
|
typedef union TKey {
|
||||||
|
struct {
|
||||||
|
TValuefields;
|
||||||
|
int next; /* for chaining (offset for next node) */
|
||||||
|
} nk;
|
||||||
|
TValue tvk;
|
||||||
|
} TKey;
|
||||||
|
|
||||||
|
|
||||||
|
/* copy a value into a key without messing up field 'next' */
|
||||||
|
#define setnodekey(L,key,obj) \
|
||||||
|
{ TKey *k_=(key); const TValue *io_=(obj); \
|
||||||
|
k_->nk.value_ = io_->value_; k_->nk.tt_ = io_->tt_; \
|
||||||
|
(void)L; checkliveness(L,io_); }
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct Node {
|
||||||
|
TValue i_val;
|
||||||
|
TKey i_key;
|
||||||
|
} Node;
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct Table {
|
||||||
|
CommonHeader;
|
||||||
|
lu_byte flags; /* 1<<p means tagmethod(p) is not present */
|
||||||
|
lu_byte lsizenode; /* log2 of size of 'node' array */
|
||||||
|
unsigned int sizearray; /* size of 'array' array */
|
||||||
|
TValue *array; /* array part */
|
||||||
|
Node *node;
|
||||||
|
Node *lastfree; /* any free position is before this position */
|
||||||
|
struct Table *metatable;
|
||||||
|
GCObject *gclist;
|
||||||
|
} Table;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 'module' operation for hashing (size is always a power of 2)
|
||||||
|
*/
|
||||||
|
#define lmod(s,size) \
|
||||||
|
(check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
|
||||||
|
|
||||||
|
|
||||||
|
#define twoto(x) (1<<(x))
|
||||||
|
#define sizenode(t) (twoto((t)->lsizenode))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** (address of) a fixed nil value
|
||||||
|
*/
|
||||||
|
#define luaO_nilobject (&luaO_nilobject_)
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_DDEC const TValue luaO_nilobject_;
|
||||||
|
|
||||||
|
/* size of buffer for 'luaO_utf8esc' function */
|
||||||
|
#define UTF8BUFFSZ 8
|
||||||
|
|
||||||
|
LUAI_FUNC int luaO_int2fb (unsigned int x);
|
||||||
|
LUAI_FUNC int luaO_fb2int (int x);
|
||||||
|
LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x);
|
||||||
|
LUAI_FUNC int luaO_ceillog2 (unsigned int x);
|
||||||
|
LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,
|
||||||
|
const TValue *p2, TValue *res);
|
||||||
|
LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o);
|
||||||
|
LUAI_FUNC int luaO_hexavalue (int c);
|
||||||
|
LUAI_FUNC void luaO_tostring (lua_State *L, StkId obj);
|
||||||
|
LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
|
||||||
|
va_list argp);
|
||||||
|
LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
|
||||||
|
LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len);
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,297 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lopcodes.h,v 1.149.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Opcodes for Lua virtual machine
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lopcodes_h
|
||||||
|
#define lopcodes_h
|
||||||
|
|
||||||
|
#include "llimits.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*===========================================================================
|
||||||
|
We assume that instructions are unsigned numbers.
|
||||||
|
All instructions have an opcode in the first 6 bits.
|
||||||
|
Instructions can have the following fields:
|
||||||
|
'A' : 8 bits
|
||||||
|
'B' : 9 bits
|
||||||
|
'C' : 9 bits
|
||||||
|
'Ax' : 26 bits ('A', 'B', and 'C' together)
|
||||||
|
'Bx' : 18 bits ('B' and 'C' together)
|
||||||
|
'sBx' : signed Bx
|
||||||
|
|
||||||
|
A signed argument is represented in excess K; that is, the number
|
||||||
|
value is the unsigned value minus K. K is exactly the maximum value
|
||||||
|
for that argument (so that -max is represented by 0, and +max is
|
||||||
|
represented by 2*max), which is half the maximum for the corresponding
|
||||||
|
unsigned argument.
|
||||||
|
===========================================================================*/
|
||||||
|
|
||||||
|
|
||||||
|
enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** size and position of opcode arguments.
|
||||||
|
*/
|
||||||
|
#define SIZE_C 9
|
||||||
|
#define SIZE_B 9
|
||||||
|
#define SIZE_Bx (SIZE_C + SIZE_B)
|
||||||
|
#define SIZE_A 8
|
||||||
|
#define SIZE_Ax (SIZE_C + SIZE_B + SIZE_A)
|
||||||
|
|
||||||
|
#define SIZE_OP 6
|
||||||
|
|
||||||
|
#define POS_OP 0
|
||||||
|
#define POS_A (POS_OP + SIZE_OP)
|
||||||
|
#define POS_C (POS_A + SIZE_A)
|
||||||
|
#define POS_B (POS_C + SIZE_C)
|
||||||
|
#define POS_Bx POS_C
|
||||||
|
#define POS_Ax POS_A
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** limits for opcode arguments.
|
||||||
|
** we use (signed) int to manipulate most arguments,
|
||||||
|
** so they must fit in LUAI_BITSINT-1 bits (-1 for sign)
|
||||||
|
*/
|
||||||
|
#if SIZE_Bx < LUAI_BITSINT-1
|
||||||
|
#define MAXARG_Bx ((1<<SIZE_Bx)-1)
|
||||||
|
#define MAXARG_sBx (MAXARG_Bx>>1) /* 'sBx' is signed */
|
||||||
|
#else
|
||||||
|
#define MAXARG_Bx MAX_INT
|
||||||
|
#define MAXARG_sBx MAX_INT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if SIZE_Ax < LUAI_BITSINT-1
|
||||||
|
#define MAXARG_Ax ((1<<SIZE_Ax)-1)
|
||||||
|
#else
|
||||||
|
#define MAXARG_Ax MAX_INT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#define MAXARG_A ((1<<SIZE_A)-1)
|
||||||
|
#define MAXARG_B ((1<<SIZE_B)-1)
|
||||||
|
#define MAXARG_C ((1<<SIZE_C)-1)
|
||||||
|
|
||||||
|
|
||||||
|
/* creates a mask with 'n' 1 bits at position 'p' */
|
||||||
|
#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p))
|
||||||
|
|
||||||
|
/* creates a mask with 'n' 0 bits at position 'p' */
|
||||||
|
#define MASK0(n,p) (~MASK1(n,p))
|
||||||
|
|
||||||
|
/*
|
||||||
|
** the following macros help to manipulate instructions
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define GET_OPCODE(i) (cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
|
||||||
|
#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
|
||||||
|
((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))
|
||||||
|
|
||||||
|
#define getarg(i,pos,size) (cast(int, ((i)>>pos) & MASK1(size,0)))
|
||||||
|
#define setarg(i,v,pos,size) ((i) = (((i)&MASK0(size,pos)) | \
|
||||||
|
((cast(Instruction, v)<<pos)&MASK1(size,pos))))
|
||||||
|
|
||||||
|
#define GETARG_A(i) getarg(i, POS_A, SIZE_A)
|
||||||
|
#define SETARG_A(i,v) setarg(i, v, POS_A, SIZE_A)
|
||||||
|
|
||||||
|
#define GETARG_B(i) getarg(i, POS_B, SIZE_B)
|
||||||
|
#define SETARG_B(i,v) setarg(i, v, POS_B, SIZE_B)
|
||||||
|
|
||||||
|
#define GETARG_C(i) getarg(i, POS_C, SIZE_C)
|
||||||
|
#define SETARG_C(i,v) setarg(i, v, POS_C, SIZE_C)
|
||||||
|
|
||||||
|
#define GETARG_Bx(i) getarg(i, POS_Bx, SIZE_Bx)
|
||||||
|
#define SETARG_Bx(i,v) setarg(i, v, POS_Bx, SIZE_Bx)
|
||||||
|
|
||||||
|
#define GETARG_Ax(i) getarg(i, POS_Ax, SIZE_Ax)
|
||||||
|
#define SETARG_Ax(i,v) setarg(i, v, POS_Ax, SIZE_Ax)
|
||||||
|
|
||||||
|
#define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx)
|
||||||
|
#define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx))
|
||||||
|
|
||||||
|
|
||||||
|
#define CREATE_ABC(o,a,b,c) ((cast(Instruction, o)<<POS_OP) \
|
||||||
|
| (cast(Instruction, a)<<POS_A) \
|
||||||
|
| (cast(Instruction, b)<<POS_B) \
|
||||||
|
| (cast(Instruction, c)<<POS_C))
|
||||||
|
|
||||||
|
#define CREATE_ABx(o,a,bc) ((cast(Instruction, o)<<POS_OP) \
|
||||||
|
| (cast(Instruction, a)<<POS_A) \
|
||||||
|
| (cast(Instruction, bc)<<POS_Bx))
|
||||||
|
|
||||||
|
#define CREATE_Ax(o,a) ((cast(Instruction, o)<<POS_OP) \
|
||||||
|
| (cast(Instruction, a)<<POS_Ax))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Macros to operate RK indices
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* this bit 1 means constant (0 means register) */
|
||||||
|
#define BITRK (1 << (SIZE_B - 1))
|
||||||
|
|
||||||
|
/* test whether value is a constant */
|
||||||
|
#define ISK(x) ((x) & BITRK)
|
||||||
|
|
||||||
|
/* gets the index of the constant */
|
||||||
|
#define INDEXK(r) ((int)(r) & ~BITRK)
|
||||||
|
|
||||||
|
#if !defined(MAXINDEXRK) /* (for debugging only) */
|
||||||
|
#define MAXINDEXRK (BITRK - 1)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* code a constant index as a RK value */
|
||||||
|
#define RKASK(x) ((x) | BITRK)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** invalid register that fits in 8 bits
|
||||||
|
*/
|
||||||
|
#define NO_REG MAXARG_A
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** R(x) - register
|
||||||
|
** Kst(x) - constant (in constant table)
|
||||||
|
** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** grep "ORDER OP" if you change these enums
|
||||||
|
*/
|
||||||
|
|
||||||
|
typedef enum {
|
||||||
|
/*----------------------------------------------------------------------
|
||||||
|
name args description
|
||||||
|
------------------------------------------------------------------------*/
|
||||||
|
OP_MOVE,/* A B R(A) := R(B) */
|
||||||
|
OP_LOADK,/* A Bx R(A) := Kst(Bx) */
|
||||||
|
OP_LOADKX,/* A R(A) := Kst(extra arg) */
|
||||||
|
OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */
|
||||||
|
OP_LOADNIL,/* A B R(A), R(A+1), ..., R(A+B) := nil */
|
||||||
|
OP_GETUPVAL,/* A B R(A) := UpValue[B] */
|
||||||
|
|
||||||
|
OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */
|
||||||
|
OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */
|
||||||
|
|
||||||
|
OP_SETTABUP,/* A B C UpValue[A][RK(B)] := RK(C) */
|
||||||
|
OP_SETUPVAL,/* A B UpValue[B] := R(A) */
|
||||||
|
OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */
|
||||||
|
|
||||||
|
OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */
|
||||||
|
|
||||||
|
OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */
|
||||||
|
|
||||||
|
OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
|
||||||
|
OP_SUB,/* A B C R(A) := RK(B) - RK(C) */
|
||||||
|
OP_MUL,/* A B C R(A) := RK(B) * RK(C) */
|
||||||
|
OP_MOD,/* A B C R(A) := RK(B) % RK(C) */
|
||||||
|
OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */
|
||||||
|
OP_DIV,/* A B C R(A) := RK(B) / RK(C) */
|
||||||
|
OP_IDIV,/* A B C R(A) := RK(B) // RK(C) */
|
||||||
|
OP_BAND,/* A B C R(A) := RK(B) & RK(C) */
|
||||||
|
OP_BOR,/* A B C R(A) := RK(B) | RK(C) */
|
||||||
|
OP_BXOR,/* A B C R(A) := RK(B) ~ RK(C) */
|
||||||
|
OP_SHL,/* A B C R(A) := RK(B) << RK(C) */
|
||||||
|
OP_SHR,/* A B C R(A) := RK(B) >> RK(C) */
|
||||||
|
OP_UNM,/* A B R(A) := -R(B) */
|
||||||
|
OP_BNOT,/* A B R(A) := ~R(B) */
|
||||||
|
OP_NOT,/* A B R(A) := not R(B) */
|
||||||
|
OP_LEN,/* A B R(A) := length of R(B) */
|
||||||
|
|
||||||
|
OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
|
||||||
|
|
||||||
|
OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A - 1) */
|
||||||
|
OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
|
||||||
|
OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
|
||||||
|
OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
|
||||||
|
|
||||||
|
OP_TEST,/* A C if not (R(A) <=> C) then pc++ */
|
||||||
|
OP_TESTSET,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
|
||||||
|
|
||||||
|
OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
|
||||||
|
OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
|
||||||
|
OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */
|
||||||
|
|
||||||
|
OP_FORLOOP,/* A sBx R(A)+=R(A+2);
|
||||||
|
if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
|
||||||
|
OP_FORPREP,/* A sBx R(A)-=R(A+2); pc+=sBx */
|
||||||
|
|
||||||
|
OP_TFORCALL,/* A C R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); */
|
||||||
|
OP_TFORLOOP,/* A sBx if R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx }*/
|
||||||
|
|
||||||
|
OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
|
||||||
|
|
||||||
|
OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */
|
||||||
|
|
||||||
|
OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */
|
||||||
|
|
||||||
|
OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
|
||||||
|
} OpCode;
|
||||||
|
|
||||||
|
|
||||||
|
#define NUM_OPCODES (cast(int, OP_EXTRAARG) + 1)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*===========================================================================
|
||||||
|
Notes:
|
||||||
|
(*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then 'top' is
|
||||||
|
set to last_result+1, so next open instruction (OP_CALL, OP_RETURN,
|
||||||
|
OP_SETLIST) may use 'top'.
|
||||||
|
|
||||||
|
(*) In OP_VARARG, if (B == 0) then use actual number of varargs and
|
||||||
|
set top (like in OP_CALL with C == 0).
|
||||||
|
|
||||||
|
(*) In OP_RETURN, if (B == 0) then return up to 'top'.
|
||||||
|
|
||||||
|
(*) In OP_SETLIST, if (B == 0) then B = 'top'; if (C == 0) then next
|
||||||
|
'instruction' is EXTRAARG(real C).
|
||||||
|
|
||||||
|
(*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
|
||||||
|
|
||||||
|
(*) For comparisons, A specifies what condition the test should accept
|
||||||
|
(true or false).
|
||||||
|
|
||||||
|
(*) All 'skips' (pc++) assume that next instruction is a jump.
|
||||||
|
|
||||||
|
===========================================================================*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** masks for instruction properties. The format is:
|
||||||
|
** bits 0-1: op mode
|
||||||
|
** bits 2-3: C arg mode
|
||||||
|
** bits 4-5: B arg mode
|
||||||
|
** bit 6: instruction set register A
|
||||||
|
** bit 7: operator is a test (next instruction must be a jump)
|
||||||
|
*/
|
||||||
|
|
||||||
|
enum OpArgMask {
|
||||||
|
OpArgN, /* argument is not used */
|
||||||
|
OpArgU, /* argument is used */
|
||||||
|
OpArgR, /* argument is a register or a jump offset */
|
||||||
|
OpArgK /* argument is a constant or register/constant */
|
||||||
|
};
|
||||||
|
|
||||||
|
LUAI_DDEC const lu_byte luaP_opmodes[NUM_OPCODES];
|
||||||
|
|
||||||
|
#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3))
|
||||||
|
#define getBMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))
|
||||||
|
#define getCMode(m) (cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3))
|
||||||
|
#define testAMode(m) (luaP_opmodes[m] & (1 << 6))
|
||||||
|
#define testTMode(m) (luaP_opmodes[m] & (1 << 7))
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_DDEC const char *const luaP_opnames[NUM_OPCODES+1]; /* opcode names */
|
||||||
|
|
||||||
|
|
||||||
|
/* number of list items to accumulate before a SETLIST instruction */
|
||||||
|
#define LFIELDS_PER_FLUSH 50
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lparser.h,v 1.76.1.1 2017/04/19 17:20:42 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
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lprefix.h,v 1.2.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Definitions for Lua code that must come before any other header file
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lprefix_h
|
||||||
|
#define lprefix_h
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Allows POSIX/XSI stuff
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_USE_C89) /* { */
|
||||||
|
|
||||||
|
#if !defined(_XOPEN_SOURCE)
|
||||||
|
#define _XOPEN_SOURCE 600
|
||||||
|
#elif _XOPEN_SOURCE == 0
|
||||||
|
#undef _XOPEN_SOURCE /* use -D_XOPEN_SOURCE=0 to undefine it */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Allows manipulation of large files in gcc and some other compilers
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS)
|
||||||
|
#define _LARGEFILE_SOURCE 1
|
||||||
|
#define _FILE_OFFSET_BITS 64
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Windows stuff
|
||||||
|
*/
|
||||||
|
#if defined(_WIN32) /* { */
|
||||||
|
|
||||||
|
#if !defined(_CRT_SECURE_NO_WARNINGS)
|
||||||
|
#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lstate.h,v 2.133.1.1 2017/04/19 17:39:34 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).
|
||||||
|
**
|
||||||
|
** Moreover, there is another set of lists that control gray objects.
|
||||||
|
** These lists are linked by fields 'gclist'. (All objects that
|
||||||
|
** can become gray have such a field. The field is not the same
|
||||||
|
** in all objects, but it always has this name.) Any gray object
|
||||||
|
** must belong to one of these lists, and all objects in these lists
|
||||||
|
** must be gray:
|
||||||
|
**
|
||||||
|
** 'gray': regular gray objects, still waiting to be visited.
|
||||||
|
** 'grayagain': objects that must be revisited at the atomic phase.
|
||||||
|
** That includes
|
||||||
|
** - black objects got in a write barrier;
|
||||||
|
** - all kinds of weak tables during propagation phase;
|
||||||
|
** - all threads.
|
||||||
|
** 'weak': tables with weak values to be cleared;
|
||||||
|
** 'ephemeron': ephemeron tables with white->white entries;
|
||||||
|
** 'allweak': tables with weak keys and/or weak values to be cleared.
|
||||||
|
** The last three lists are used only during the atomic phase.
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
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 G_SEED_FIXED (0xA25E41B5)
|
||||||
|
|
||||||
|
#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
|
||||||
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lstring.h,v 1.61.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** String table (keep all strings handled by Lua)
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lstring_h
|
||||||
|
#define lstring_h
|
||||||
|
|
||||||
|
#include "lgc.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
|
||||||
|
|
||||||
|
#define sizelstring(l) (sizeof(union UTString) + ((l) + 1) * sizeof(char))
|
||||||
|
|
||||||
|
#define sizeludata(l) (sizeof(union UUdata) + (l))
|
||||||
|
#define sizeudata(u) sizeludata((u)->len)
|
||||||
|
|
||||||
|
#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
|
||||||
|
(sizeof(s)/sizeof(char))-1))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** test whether a string is a reserved word
|
||||||
|
*/
|
||||||
|
#define isreserved(s) ((s)->tt == LUA_TSHRSTR && (s)->extra > 0)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** equality for short strings, which are always internalized
|
||||||
|
*/
|
||||||
|
#define eqshrstr(a,b) check_exp((a)->tt == LUA_TSHRSTR, (a) == (b))
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);
|
||||||
|
LUAI_FUNC unsigned int luaS_hashlongstr (TString *ts);
|
||||||
|
LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b);
|
||||||
|
LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
|
||||||
|
LUAI_FUNC void luaS_clearcache (global_State *g);
|
||||||
|
LUAI_FUNC void luaS_init (lua_State *L);
|
||||||
|
LUAI_FUNC void luaS_remove (lua_State *L, TString *ts);
|
||||||
|
LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s);
|
||||||
|
LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
|
||||||
|
LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);
|
||||||
|
LUAI_FUNC TString *luaS_createlngstrobj (lua_State *L, size_t l);
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ltable.h,v 2.23.1.2 2018/05/24 19:39:05 roberto Exp $
|
||||||
|
** Lua tables (hash)
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef ltable_h
|
||||||
|
#define ltable_h
|
||||||
|
|
||||||
|
#include "lobject.h"
|
||||||
|
|
||||||
|
|
||||||
|
#define gnode(t,i) (&(t)->node[i])
|
||||||
|
#define gval(n) (&(n)->i_val)
|
||||||
|
#define gnext(n) ((n)->i_key.nk.next)
|
||||||
|
|
||||||
|
|
||||||
|
/* 'const' to avoid wrong writings that can mess up field 'next' */
|
||||||
|
#define gkey(n) cast(const TValue*, (&(n)->i_key.tvk))
|
||||||
|
|
||||||
|
/*
|
||||||
|
** writable version of 'gkey'; allows updates to individual fields,
|
||||||
|
** but not to the whole (which has incompatible type)
|
||||||
|
*/
|
||||||
|
#define wgkey(n) (&(n)->i_key.nk)
|
||||||
|
|
||||||
|
#define invalidateTMcache(t) ((t)->flags = 0)
|
||||||
|
|
||||||
|
|
||||||
|
/* true when 't' is using 'dummynode' as its hash part */
|
||||||
|
#define isdummy(t) ((t)->lastfree == NULL)
|
||||||
|
|
||||||
|
|
||||||
|
/* allocated size for hash nodes */
|
||||||
|
#define allocsizenode(t) (isdummy(t) ? 0 : sizenode(t))
|
||||||
|
|
||||||
|
|
||||||
|
/* returns the key, given the value of a table entry */
|
||||||
|
#define keyfromval(v) \
|
||||||
|
(gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val))))
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);
|
||||||
|
LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
|
||||||
|
TValue *value);
|
||||||
|
LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key);
|
||||||
|
LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
|
||||||
|
LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
|
||||||
|
LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);
|
||||||
|
LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
|
||||||
|
LUAI_FUNC Table *luaH_new (lua_State *L);
|
||||||
|
LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
|
||||||
|
unsigned int nhsize);
|
||||||
|
LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize);
|
||||||
|
LUAI_FUNC void luaH_free (lua_State *L, Table *t);
|
||||||
|
LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
|
||||||
|
LUAI_FUNC lua_Unsigned luaH_getn (Table *t);
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_DEBUG)
|
||||||
|
LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);
|
||||||
|
LUAI_FUNC int luaH_isdummy (const Table *t);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ltests.h,v 2.50.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Internal Header for Debugging of the Lua Implementation
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef ltests_h
|
||||||
|
#define ltests_h
|
||||||
|
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
/* test Lua with no compatibility code */
|
||||||
|
#undef LUA_COMPAT_MATHLIB
|
||||||
|
#undef LUA_COMPAT_IPAIRS
|
||||||
|
#undef LUA_COMPAT_BITLIB
|
||||||
|
#undef LUA_COMPAT_APIINTCASTS
|
||||||
|
#undef LUA_COMPAT_FLOATSTRING
|
||||||
|
#undef LUA_COMPAT_UNPACK
|
||||||
|
#undef LUA_COMPAT_LOADERS
|
||||||
|
#undef LUA_COMPAT_LOG10
|
||||||
|
#undef LUA_COMPAT_LOADSTRING
|
||||||
|
#undef LUA_COMPAT_MAXN
|
||||||
|
#undef LUA_COMPAT_MODULE
|
||||||
|
|
||||||
|
|
||||||
|
#define LUA_DEBUG
|
||||||
|
|
||||||
|
|
||||||
|
/* turn on assertions */
|
||||||
|
#undef NDEBUG
|
||||||
|
#include <assert.h>
|
||||||
|
#define lua_assert(c) assert(c)
|
||||||
|
|
||||||
|
|
||||||
|
/* to avoid warnings, and to make sure value is really unused */
|
||||||
|
#define UNUSED(x) (x=0, (void)(x))
|
||||||
|
|
||||||
|
|
||||||
|
/* test for sizes in 'l_sprintf' (make sure whole buffer is available) */
|
||||||
|
#undef l_sprintf
|
||||||
|
#if !defined(LUA_USE_C89)
|
||||||
|
#define l_sprintf(s,sz,f,i) (memset(s,0xAB,sz), snprintf(s,sz,f,i))
|
||||||
|
#else
|
||||||
|
#define l_sprintf(s,sz,f,i) (memset(s,0xAB,sz), sprintf(s,f,i))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/* memory-allocator control variables */
|
||||||
|
typedef struct Memcontrol {
|
||||||
|
unsigned long numblocks;
|
||||||
|
unsigned long total;
|
||||||
|
unsigned long maxmem;
|
||||||
|
unsigned long memlimit;
|
||||||
|
unsigned long objcount[LUA_NUMTAGS];
|
||||||
|
} Memcontrol;
|
||||||
|
|
||||||
|
LUA_API Memcontrol l_memcontrol;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** generic variable for debug tricks
|
||||||
|
*/
|
||||||
|
extern void *l_Trick;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Function to traverse and check all memory used by Lua
|
||||||
|
*/
|
||||||
|
int lua_checkmemory (lua_State *L);
|
||||||
|
|
||||||
|
|
||||||
|
/* test for lock/unlock */
|
||||||
|
|
||||||
|
struct L_EXTRA { int lock; int *plock; };
|
||||||
|
#undef LUA_EXTRASPACE
|
||||||
|
#define LUA_EXTRASPACE sizeof(struct L_EXTRA)
|
||||||
|
#define getlock(l) cast(struct L_EXTRA*, lua_getextraspace(l))
|
||||||
|
#define luai_userstateopen(l) \
|
||||||
|
(getlock(l)->lock = 0, getlock(l)->plock = &(getlock(l)->lock))
|
||||||
|
#define luai_userstateclose(l) \
|
||||||
|
lua_assert(getlock(l)->lock == 1 && getlock(l)->plock == &(getlock(l)->lock))
|
||||||
|
#define luai_userstatethread(l,l1) \
|
||||||
|
lua_assert(getlock(l1)->plock == getlock(l)->plock)
|
||||||
|
#define luai_userstatefree(l,l1) \
|
||||||
|
lua_assert(getlock(l)->plock == getlock(l1)->plock)
|
||||||
|
#define lua_lock(l) lua_assert((*getlock(l)->plock)++ == 0)
|
||||||
|
#define lua_unlock(l) lua_assert(--(*getlock(l)->plock) == 0)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int luaB_opentests (lua_State *L);
|
||||||
|
|
||||||
|
LUA_API void *debug_realloc (void *ud, void *block,
|
||||||
|
size_t osize, size_t nsize);
|
||||||
|
|
||||||
|
#if defined(lua_c)
|
||||||
|
#define luaL_newstate() lua_newstate(debug_realloc, &l_memcontrol)
|
||||||
|
#define luaL_openlibs(L) \
|
||||||
|
{ (luaL_openlibs)(L); \
|
||||||
|
luaL_requiref(L, "T", luaB_opentests, 1); \
|
||||||
|
lua_pop(L, 1); }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* change some sizes to give some bugs a chance */
|
||||||
|
|
||||||
|
#undef LUAL_BUFFERSIZE
|
||||||
|
#define LUAL_BUFFERSIZE 23
|
||||||
|
#define MINSTRTABSIZE 2
|
||||||
|
#define MAXINDEXRK 1
|
||||||
|
|
||||||
|
|
||||||
|
/* make stack-overflow tests run faster */
|
||||||
|
#undef LUAI_MAXSTACK
|
||||||
|
#define LUAI_MAXSTACK 50000
|
||||||
|
|
||||||
|
|
||||||
|
#undef LUAI_USER_ALIGNMENT_T
|
||||||
|
#define LUAI_USER_ALIGNMENT_T union { char b[sizeof(void*) * 8]; }
|
||||||
|
|
||||||
|
|
||||||
|
#define STRCACHE_N 23
|
||||||
|
#define STRCACHE_M 5
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ltm.h,v 2.22.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Tag methods
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef ltm_h
|
||||||
|
#define ltm_h
|
||||||
|
|
||||||
|
|
||||||
|
#include "lobject.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
* WARNING: if you change the order of this enumeration,
|
||||||
|
* grep "ORDER TM" and "ORDER OP"
|
||||||
|
*/
|
||||||
|
typedef enum {
|
||||||
|
TM_INDEX,
|
||||||
|
TM_NEWINDEX,
|
||||||
|
TM_GC,
|
||||||
|
TM_MODE,
|
||||||
|
TM_LEN,
|
||||||
|
TM_EQ, /* last tag method with fast access */
|
||||||
|
TM_ADD,
|
||||||
|
TM_SUB,
|
||||||
|
TM_MUL,
|
||||||
|
TM_MOD,
|
||||||
|
TM_POW,
|
||||||
|
TM_DIV,
|
||||||
|
TM_IDIV,
|
||||||
|
TM_BAND,
|
||||||
|
TM_BOR,
|
||||||
|
TM_BXOR,
|
||||||
|
TM_SHL,
|
||||||
|
TM_SHR,
|
||||||
|
TM_UNM,
|
||||||
|
TM_BNOT,
|
||||||
|
TM_LT,
|
||||||
|
TM_LE,
|
||||||
|
TM_CONCAT,
|
||||||
|
TM_CALL,
|
||||||
|
TM_N /* number of elements in the enum */
|
||||||
|
} TMS;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define gfasttm(g,et,e) ((et) == NULL ? NULL : \
|
||||||
|
((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))
|
||||||
|
|
||||||
|
#define fasttm(l,et,e) gfasttm(G(l), et, e)
|
||||||
|
|
||||||
|
#define ttypename(x) luaT_typenames_[(x) + 1]
|
||||||
|
|
||||||
|
LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS];
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o);
|
||||||
|
|
||||||
|
LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
|
||||||
|
LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,
|
||||||
|
TMS event);
|
||||||
|
LUAI_FUNC void luaT_init (lua_State *L);
|
||||||
|
|
||||||
|
LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
|
||||||
|
const TValue *p2, TValue *p3, int hasres);
|
||||||
|
LUAI_FUNC int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||||
|
StkId res, TMS event);
|
||||||
|
LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||||
|
StkId res, TMS event);
|
||||||
|
LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,
|
||||||
|
const TValue *p2, TMS event);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lua.h,v 1.332.1.2 2018/06/13 16:58:17 roberto Exp $
|
||||||
|
** Lua - A Scripting 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_MAJOR "5"
|
||||||
|
#define LUA_VERSION_MINOR "3"
|
||||||
|
#define LUA_VERSION_NUM 503
|
||||||
|
#define LUA_VERSION_RELEASE "6"
|
||||||
|
|
||||||
|
#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
|
||||||
|
#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
|
||||||
|
#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2018 Lua.org, PUC-Rio"
|
||||||
|
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
|
||||||
|
|
||||||
|
|
||||||
|
/* mark for precompiled code ('<esc>Lua') */
|
||||||
|
#define LUA_SIGNATURE "\x1bLua"
|
||||||
|
|
||||||
|
/* option for multiple returns in 'lua_pcall' and 'lua_call' */
|
||||||
|
#define LUA_MULTRET (-1)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Pseudo-indices
|
||||||
|
** (-LUAI_MAXSTACK is the minimum valid index; we keep some free empty
|
||||||
|
** space after that to help overflow detection)
|
||||||
|
*/
|
||||||
|
#define LUA_REGISTRYINDEX (-LUAI_MAXSTACK - 1000)
|
||||||
|
#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i))
|
||||||
|
|
||||||
|
|
||||||
|
/* thread status */
|
||||||
|
#define LUA_OK 0
|
||||||
|
#define LUA_YIELD 1
|
||||||
|
#define LUA_ERRRUN 2
|
||||||
|
#define LUA_ERRSYNTAX 3
|
||||||
|
#define LUA_ERRMEM 4
|
||||||
|
#define LUA_ERRGCMM 5
|
||||||
|
#define LUA_ERRERR 6
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct lua_State lua_State;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 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
|
||||||
|
|
||||||
|
#define LUA_NUMTAGS 9
|
||||||
|
// add by wendal @ LuatOS
|
||||||
|
#define LUA_TINTEGER 21
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* minimum Lua stack available to a C function */
|
||||||
|
#define LUA_MINSTACK 20
|
||||||
|
|
||||||
|
|
||||||
|
/* predefined values in the registry */
|
||||||
|
#define LUA_RIDX_MAINTHREAD 1
|
||||||
|
#define LUA_RIDX_GLOBALS 2
|
||||||
|
#define LUA_RIDX_LAST LUA_RIDX_GLOBALS
|
||||||
|
|
||||||
|
|
||||||
|
/* type of numbers in Lua */
|
||||||
|
typedef LUA_NUMBER lua_Number;
|
||||||
|
|
||||||
|
|
||||||
|
/* type for integer functions */
|
||||||
|
typedef LUA_INTEGER lua_Integer;
|
||||||
|
|
||||||
|
/* unsigned integer type */
|
||||||
|
typedef LUA_UNSIGNED lua_Unsigned;
|
||||||
|
|
||||||
|
/* type for continuation-function contexts */
|
||||||
|
typedef LUA_KCONTEXT lua_KContext;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Type for C functions registered with Lua
|
||||||
|
*/
|
||||||
|
typedef int (*lua_CFunction) (lua_State *L);
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Type for continuation functions
|
||||||
|
*/
|
||||||
|
typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Type for 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);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Type for memory-allocation functions
|
||||||
|
*/
|
||||||
|
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** generic extra include file
|
||||||
|
*/
|
||||||
|
#if defined(LUA_USER_H)
|
||||||
|
#include LUA_USER_H
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** RCS ident string
|
||||||
|
*/
|
||||||
|
extern const char lua_ident[];
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 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);
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API const lua_Number *(lua_version) (lua_State *L);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** basic stack manipulation
|
||||||
|
*/
|
||||||
|
LUA_API int (lua_absindex) (lua_State *L, int idx);
|
||||||
|
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_rotate) (lua_State *L, int idx, int n);
|
||||||
|
LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx);
|
||||||
|
LUA_API int (lua_checkstack) (lua_State *L, int n);
|
||||||
|
|
||||||
|
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_isinteger) (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 lua_Number (lua_tonumberx) (lua_State *L, int idx, int *isnum);
|
||||||
|
LUA_API lua_Integer (lua_tointegerx) (lua_State *L, int idx, int *isnum);
|
||||||
|
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_rawlen) (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);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Comparison and arithmetic functions
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define LUA_OPADD 0 /* ORDER TM, ORDER OP */
|
||||||
|
#define LUA_OPSUB 1
|
||||||
|
#define LUA_OPMUL 2
|
||||||
|
#define LUA_OPMOD 3
|
||||||
|
#define LUA_OPPOW 4
|
||||||
|
#define LUA_OPDIV 5
|
||||||
|
#define LUA_OPIDIV 6
|
||||||
|
#define LUA_OPBAND 7
|
||||||
|
#define LUA_OPBOR 8
|
||||||
|
#define LUA_OPBXOR 9
|
||||||
|
#define LUA_OPSHL 10
|
||||||
|
#define LUA_OPSHR 11
|
||||||
|
#define LUA_OPUNM 12
|
||||||
|
#define LUA_OPBNOT 13
|
||||||
|
|
||||||
|
LUA_API void (lua_arith) (lua_State *L, int op);
|
||||||
|
|
||||||
|
#define LUA_OPEQ 0
|
||||||
|
#define LUA_OPLT 1
|
||||||
|
#define LUA_OPLE 2
|
||||||
|
|
||||||
|
LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2);
|
||||||
|
LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 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 const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len);
|
||||||
|
LUA_API const char *(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 int (lua_getglobal) (lua_State *L, const char *name);
|
||||||
|
LUA_API int (lua_gettable) (lua_State *L, int idx);
|
||||||
|
LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k);
|
||||||
|
LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n);
|
||||||
|
LUA_API int (lua_rawget) (lua_State *L, int idx);
|
||||||
|
LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);
|
||||||
|
LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p);
|
||||||
|
|
||||||
|
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 int (lua_getuservalue) (lua_State *L, int idx);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** set functions (stack -> Lua)
|
||||||
|
*/
|
||||||
|
LUA_API void (lua_setglobal) (lua_State *L, const char *name);
|
||||||
|
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_seti) (lua_State *L, int idx, lua_Integer n);
|
||||||
|
LUA_API void (lua_rawset) (lua_State *L, int idx);
|
||||||
|
LUA_API void (lua_rawseti) (lua_State *L, int idx, lua_Integer n);
|
||||||
|
LUA_API void (lua_rawsetp) (lua_State *L, int idx, const void *p);
|
||||||
|
LUA_API int (lua_setmetatable) (lua_State *L, int objindex);
|
||||||
|
LUA_API void (lua_setuservalue) (lua_State *L, int idx);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 'load' and 'call' functions (load and run Lua code)
|
||||||
|
*/
|
||||||
|
LUA_API void (lua_callk) (lua_State *L, int nargs, int nresults,
|
||||||
|
lua_KContext ctx, lua_KFunction k);
|
||||||
|
#define lua_call(L,n,r) lua_callk(L, (n), (r), 0, NULL)
|
||||||
|
|
||||||
|
LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
|
||||||
|
lua_KContext ctx, lua_KFunction k);
|
||||||
|
#define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL)
|
||||||
|
|
||||||
|
LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt,
|
||||||
|
const char *chunkname, const char *mode);
|
||||||
|
|
||||||
|
LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** coroutine functions
|
||||||
|
*/
|
||||||
|
LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx,
|
||||||
|
lua_KFunction k);
|
||||||
|
LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg);
|
||||||
|
LUA_API int (lua_status) (lua_State *L);
|
||||||
|
LUA_API int (lua_isyieldable) (lua_State *L);
|
||||||
|
|
||||||
|
#define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 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 void (lua_len) (lua_State *L, int idx);
|
||||||
|
|
||||||
|
LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s);
|
||||||
|
|
||||||
|
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_getextraspace(L) ((void *)((char *)(L) - LUA_EXTRASPACE))
|
||||||
|
|
||||||
|
#define lua_tonumber(L,i) lua_tonumberx(L,(i),NULL)
|
||||||
|
#define lua_tointeger(L,i) lua_tointegerx(L,(i),NULL)
|
||||||
|
|
||||||
|
#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_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_pushstring(L, "" s)
|
||||||
|
|
||||||
|
#define lua_pushglobaltable(L) \
|
||||||
|
((void)lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS))
|
||||||
|
|
||||||
|
#define lua_tostring(L,i) lua_tolstring(L, (i), NULL)
|
||||||
|
|
||||||
|
|
||||||
|
#define lua_insert(L,idx) lua_rotate(L, (idx), 1)
|
||||||
|
|
||||||
|
#define lua_remove(L,idx) (lua_rotate(L, (idx), -1), lua_pop(L, 1))
|
||||||
|
|
||||||
|
#define lua_replace(L,idx) (lua_copy(L, -1, (idx)), lua_pop(L, 1))
|
||||||
|
|
||||||
|
/* }============================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==============================================================
|
||||||
|
** compatibility macros for unsigned conversions
|
||||||
|
** ===============================================================
|
||||||
|
*/
|
||||||
|
#if defined(LUA_COMPAT_APIINTCASTS)
|
||||||
|
|
||||||
|
#define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n))
|
||||||
|
#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is))
|
||||||
|
#define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL)
|
||||||
|
|
||||||
|
#endif
|
||||||
|
/* }============================================================== */
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================================
|
||||||
|
** Debug API
|
||||||
|
** =======================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Event codes
|
||||||
|
*/
|
||||||
|
#define LUA_HOOKCALL 0
|
||||||
|
#define LUA_HOOKRET 1
|
||||||
|
#define LUA_HOOKLINE 2
|
||||||
|
#define LUA_HOOKCOUNT 3
|
||||||
|
#define LUA_HOOKTAILCALL 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 debugger 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 void *(lua_upvalueid) (lua_State *L, int fidx, int n);
|
||||||
|
LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,
|
||||||
|
int fidx2, int n2);
|
||||||
|
|
||||||
|
LUA_API void (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);
|
||||||
|
|
||||||
|
|
||||||
|
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 linedefined; /* (S) */
|
||||||
|
int lastlinedefined; /* (S) */
|
||||||
|
unsigned char nups; /* (u) number of upvalues */
|
||||||
|
unsigned char nparams;/* (u) number of parameters */
|
||||||
|
char isvararg; /* (u) */
|
||||||
|
char istailcall; /* (t) */
|
||||||
|
char short_src[LUA_IDSIZE]; /* (S) */
|
||||||
|
/* private part */
|
||||||
|
struct CallInfo *i_ci; /* active function */
|
||||||
|
};
|
||||||
|
|
||||||
|
/* }====================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/******************************************************************************
|
||||||
|
* Copyright (C) 1994-2018 Lua.org, PUC-Rio.
|
||||||
|
*
|
||||||
|
* 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
|
||||||
@@ -0,0 +1,791 @@
|
|||||||
|
/*
|
||||||
|
** $Id: luaconf.h,v 1.259.1.1 2017/04/19 17:29:57 roberto Exp $
|
||||||
|
** Configuration file for Lua
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef luaconf_h
|
||||||
|
#define luaconf_h
|
||||||
|
|
||||||
|
#include <limits.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "luat_conf_bsp.h"
|
||||||
|
#include "luat_conf_default.h"
|
||||||
|
|
||||||
|
/*
|
||||||
|
** ===================================================================
|
||||||
|
** Search for "@@" to find all configurable definitions.
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {====================================================================
|
||||||
|
** System Configuration: macros to adapt (if needed) Lua to some
|
||||||
|
** particular platform, for instance compiling it with 32-bit numbers or
|
||||||
|
** restricting it to C89.
|
||||||
|
** =====================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. You
|
||||||
|
** can also define LUA_32BITS in the make file, but changing here you
|
||||||
|
** ensure that all software connected to Lua will be compiled with the
|
||||||
|
** same configuration.
|
||||||
|
*/
|
||||||
|
/* #define LUA_32BITS */
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_USE_C89 controls the use of non-ISO-C89 features.
|
||||||
|
** Define it if you want Lua to avoid the use of a few C99 features
|
||||||
|
** or Windows-specific features on Windows.
|
||||||
|
*/
|
||||||
|
/* #define LUA_USE_C89 */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** By default, Lua on Windows use (some) specific Windows features
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE)
|
||||||
|
#define LUA_USE_WINDOWS /* enable goodies for regular Windows */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef LUA_USE_WINDOWS
|
||||||
|
#ifdef LUAT_FORCE_WIN32
|
||||||
|
#define LUA_USE_WINDOWS
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_USE_WINDOWS)
|
||||||
|
#define LUA_DL_DLL /* enable support for DLL */
|
||||||
|
#define LUA_USE_C89 /* broadly, Windows is C89 */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_USE_LINUX)
|
||||||
|
#define LUA_USE_POSIX
|
||||||
|
#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
|
||||||
|
#define LUA_USE_READLINE /* needs some extra libraries */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_USE_MACOSX)
|
||||||
|
#define LUA_USE_POSIX
|
||||||
|
#define LUA_USE_DLOPEN /* MacOS does not need -ldl */
|
||||||
|
#define LUA_USE_READLINE /* needs an extra library: -lreadline */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for
|
||||||
|
** C89 ('long' and 'double'); Windows always has '__int64', so it does
|
||||||
|
** not need to use this case.
|
||||||
|
*/
|
||||||
|
#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS)
|
||||||
|
#define LUA_C89_NUMBERS
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'.
|
||||||
|
*/
|
||||||
|
/* avoid undefined shifts */
|
||||||
|
#if ((INT_MAX >> 15) >> 15) >= 1
|
||||||
|
#define LUAI_BITSINT 32
|
||||||
|
#else
|
||||||
|
/* 'int' always must have at least 16 bits */
|
||||||
|
#define LUAI_BITSINT 16
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_INT_TYPE defines the type for Lua integers.
|
||||||
|
@@ LUA_FLOAT_TYPE defines the type for Lua floats.
|
||||||
|
** Lua should work fine with any mix of these options (if supported
|
||||||
|
** by your C compiler). The usual configurations are 64-bit integers
|
||||||
|
** and 'double' (the default), 32-bit integers and 'float' (for
|
||||||
|
** restricted platforms), and 'long'/'double' (for C compilers not
|
||||||
|
** compliant with C99, which may not have support for 'long long').
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* predefined options for LUA_INT_TYPE */
|
||||||
|
#define LUA_INT_INT 1
|
||||||
|
#define LUA_INT_LONG 2
|
||||||
|
#define LUA_INT_LONGLONG 3
|
||||||
|
|
||||||
|
/* predefined options for LUA_FLOAT_TYPE */
|
||||||
|
#define LUA_FLOAT_FLOAT 1
|
||||||
|
#define LUA_FLOAT_DOUBLE 2
|
||||||
|
#define LUA_FLOAT_LONGDOUBLE 3
|
||||||
|
|
||||||
|
#if defined(LUA_32BITS) /* { */
|
||||||
|
/*
|
||||||
|
** 32-bit integers and 'float'
|
||||||
|
*/
|
||||||
|
#if LUAI_BITSINT >= 32 /* use 'int' if big enough */
|
||||||
|
#define LUA_INT_TYPE LUA_INT_INT
|
||||||
|
#else /* otherwise use 'long' */
|
||||||
|
#define LUA_INT_TYPE LUA_INT_LONG
|
||||||
|
#endif
|
||||||
|
#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT
|
||||||
|
|
||||||
|
#elif defined(LUA_C89_NUMBERS) /* }{ */
|
||||||
|
/*
|
||||||
|
** largest types available for C89 ('long' and 'double')
|
||||||
|
*/
|
||||||
|
#define LUA_INT_TYPE LUA_INT_LONG
|
||||||
|
#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** default configuration for 64-bit Lua ('long long' and 'double')
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_INT_TYPE)
|
||||||
|
#define LUA_INT_TYPE LUA_INT_LONGLONG
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(LUA_FLOAT_TYPE)
|
||||||
|
#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Configuration for Paths.
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
** LUA_PATH_SEP is the character that separates templates in a path.
|
||||||
|
** LUA_PATH_MARK is the string that marks the substitution points in a
|
||||||
|
** template.
|
||||||
|
** LUA_EXEC_DIR in a Windows path is replaced by the executable's
|
||||||
|
** directory.
|
||||||
|
*/
|
||||||
|
#define LUA_PATH_SEP ";"
|
||||||
|
#define LUA_PATH_MARK "?"
|
||||||
|
#define LUA_EXEC_DIR "!"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
|
||||||
|
** Lua libraries.
|
||||||
|
@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
|
||||||
|
** C libraries.
|
||||||
|
** CHANGE them if your machine has a non-conventional directory
|
||||||
|
** hierarchy or if you want to install your libraries in
|
||||||
|
** non-conventional directories.
|
||||||
|
*/
|
||||||
|
#define LUA_VDIR LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
|
||||||
|
#if defined(_WIN32) /* { */
|
||||||
|
/*
|
||||||
|
** In Windows, any exclamation mark ('!') in the path is replaced by the
|
||||||
|
** path of the directory of the executable file of the current process.
|
||||||
|
*/
|
||||||
|
#define LUA_LDIR "!\\lua\\"
|
||||||
|
#define LUA_CDIR "!\\"
|
||||||
|
#define LUA_SHRDIR "!\\..\\share\\lua\\" LUA_VDIR "\\"
|
||||||
|
#define LUA_PATH_DEFAULT \
|
||||||
|
LUA_LDIR"?.lua;"
|
||||||
|
#define LUA_CPATH_DEFAULT \
|
||||||
|
LUA_CDIR"?.mo;"
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
#define LUA_ROOT "/usr/local/"
|
||||||
|
#define LUA_LDIR LUA_ROOT "share/lua/" LUA_VDIR "/"
|
||||||
|
#define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR "/"
|
||||||
|
#define LUA_PATH_DEFAULT "/?.lua;"
|
||||||
|
#define LUA_CPATH_DEFAULT "/?.mo;"
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_DIRSEP is the directory separator (for submodules).
|
||||||
|
** CHANGE it if your machine does not use "/" as the directory separator
|
||||||
|
** and is not Windows. (On Windows Lua automatically uses "\".)
|
||||||
|
*/
|
||||||
|
#if defined(_WIN32)
|
||||||
|
#define LUA_DIRSEP "\\"
|
||||||
|
#else
|
||||||
|
#define LUA_DIRSEP "/"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Marks for exported symbols in the C code
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_API is a mark for all core API functions.
|
||||||
|
@@ LUALIB_API is a mark for all auxiliary library functions.
|
||||||
|
@@ LUAMOD_API is a mark for all standard library opening functions.
|
||||||
|
** CHANGE them if you need to define those functions in some special way.
|
||||||
|
** For instance, if you want to create one Windows DLL with the core and
|
||||||
|
** the libraries, you may want to use the following definition (define
|
||||||
|
** LUA_BUILD_AS_DLL to get it).
|
||||||
|
*/
|
||||||
|
#if defined(LUA_BUILD_AS_DLL) /* { */
|
||||||
|
|
||||||
|
#if defined(LUA_CORE) || defined(LUA_LIB) /* { */
|
||||||
|
#define LUA_API __declspec(dllexport)
|
||||||
|
#else /* }{ */
|
||||||
|
#define LUA_API __declspec(dllimport)
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
#define LUA_API extern
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
/* more often than not the libs go together with the core */
|
||||||
|
#define LUALIB_API LUA_API
|
||||||
|
#define LUAMOD_API LUALIB_API
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUAI_FUNC is a mark for all extern functions that are not to be
|
||||||
|
** exported to outside modules.
|
||||||
|
@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables
|
||||||
|
** that are not to be exported to outside modules (LUAI_DDEF for
|
||||||
|
** definitions and LUAI_DDEC for declarations).
|
||||||
|
** CHANGE them if you need to mark them in some special way. Elf/gcc
|
||||||
|
** (versions 3.2 and later) mark them as "hidden" to optimize access
|
||||||
|
** when Lua is compiled as a shared library. Not all elf targets support
|
||||||
|
** this attribute. Unfortunately, gcc does not offer a way to check
|
||||||
|
** whether the target offers that support, and those without support
|
||||||
|
** give a warning about it. To avoid these warnings, change to the
|
||||||
|
** default definition.
|
||||||
|
*/
|
||||||
|
#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
|
||||||
|
defined(__ELF__) /* { */
|
||||||
|
#define LUAI_FUNC __attribute__((visibility("hidden"))) extern
|
||||||
|
#else /* }{ */
|
||||||
|
#define LUAI_FUNC extern
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#define LUAI_DDEC LUAI_FUNC
|
||||||
|
#define LUAI_DDEF /* empty */
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Compatibility with previous versions
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_5_2 controls other macros for compatibility with Lua 5.2.
|
||||||
|
@@ LUA_COMPAT_5_1 controls other macros for compatibility with Lua 5.1.
|
||||||
|
** You can define it to get all options, or change specific options
|
||||||
|
** to fit your specific needs.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_5_1
|
||||||
|
#define LUA_COMPAT_5_2
|
||||||
|
|
||||||
|
#if defined(LUA_COMPAT_5_2) /* { */
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated
|
||||||
|
** functions in the mathematical library.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_MATHLIB
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_BITLIB controls the presence of library 'bit32'.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_BITLIB
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_IPAIRS controls the effectiveness of the __ipairs metamethod.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_IPAIRS
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for
|
||||||
|
** manipulating other integer types (lua_pushunsigned, lua_tounsigned,
|
||||||
|
** luaL_checkint, luaL_checklong, etc.)
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_APIINTCASTS
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_COMPAT_5_1) /* { */
|
||||||
|
|
||||||
|
/* Incompatibilities from 5.2 -> 5.3 */
|
||||||
|
#define LUA_COMPAT_MATHLIB
|
||||||
|
#define LUA_COMPAT_APIINTCASTS
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'.
|
||||||
|
** You can replace it with 'table.unpack'.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_UNPACK
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_LOADERS controls the presence of table 'package.loaders'.
|
||||||
|
** You can replace it with 'package.searchers'.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_LOADERS
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ macro 'lua_cpcall' emulates deprecated function lua_cpcall.
|
||||||
|
** You can call your C function directly (with light C functions).
|
||||||
|
*/
|
||||||
|
#define lua_cpcall(L,f,u) \
|
||||||
|
(lua_pushcfunction(L, (f)), \
|
||||||
|
lua_pushlightuserdata(L,(u)), \
|
||||||
|
lua_pcall(L,1,0,0))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library.
|
||||||
|
** You can rewrite 'log10(x)' as 'log(x, 10)'.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_LOG10
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base
|
||||||
|
** library. You can rewrite 'loadstring(s)' as 'load(s)'.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_LOADSTRING
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library.
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_MAXN
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ The following macros supply trivial compatibility for some
|
||||||
|
** changes in the API. The macros themselves document how to
|
||||||
|
** change your code to avoid using them.
|
||||||
|
*/
|
||||||
|
#define lua_strlen(L,i) lua_rawlen(L, (i))
|
||||||
|
|
||||||
|
#define lua_objlen(L,i) lua_rawlen(L, (i))
|
||||||
|
|
||||||
|
#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ)
|
||||||
|
#define lua_lessthan(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPLT)
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_MODULE controls compatibility with previous
|
||||||
|
** module functions 'module' (Lua) and 'luaL_register' (C).
|
||||||
|
*/
|
||||||
|
#define LUA_COMPAT_MODULE
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_COMPAT_FLOATSTRING makes Lua format integral floats without a
|
||||||
|
@@ a float mark ('.0').
|
||||||
|
** This macro is not on by default even in compatibility mode,
|
||||||
|
** because this is not really an incompatibility.
|
||||||
|
*/
|
||||||
|
/* #define LUA_COMPAT_FLOATSTRING */
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Configuration for Numbers.
|
||||||
|
** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_*
|
||||||
|
** satisfy your needs.
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_NUMBER is the floating-point type used by Lua.
|
||||||
|
@@ LUAI_UACNUMBER is the result of a 'default argument promotion'
|
||||||
|
@@ over a floating number.
|
||||||
|
@@ l_mathlim(x) corrects limit name 'x' to the proper float type
|
||||||
|
** by prefixing it with one of FLT/DBL/LDBL.
|
||||||
|
@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats.
|
||||||
|
@@ LUA_NUMBER_FMT is the format for writing floats.
|
||||||
|
@@ lua_number2str converts a float to a string.
|
||||||
|
@@ l_mathop allows the addition of an 'l' or 'f' to all math operations.
|
||||||
|
@@ l_floor takes the floor of a float.
|
||||||
|
@@ lua_str2number converts a decimal numeric string to a number.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/* The following definitions are good for most cases here */
|
||||||
|
|
||||||
|
#define l_floor(x) (l_mathop(floor)(x))
|
||||||
|
|
||||||
|
#define lua_number2str(s,sz,n) \
|
||||||
|
l_sprintf((s), sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)(n))
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ lua_numbertointeger converts a float number to an integer, or
|
||||||
|
** returns 0 if float is not within the range of a lua_Integer.
|
||||||
|
** (The range comparisons are tricky because of rounding. The tests
|
||||||
|
** here assume a two-complement representation, where MININTEGER always
|
||||||
|
** has an exact representation as a float; MAXINTEGER may not have one,
|
||||||
|
** and therefore its conversion to float may have an ill-defined value.)
|
||||||
|
*/
|
||||||
|
#define lua_numbertointeger(n,p) \
|
||||||
|
((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \
|
||||||
|
(n) < -(LUA_NUMBER)(LUA_MININTEGER) && \
|
||||||
|
(*(p) = (LUA_INTEGER)(n), 1))
|
||||||
|
|
||||||
|
|
||||||
|
/* now the variable definitions */
|
||||||
|
|
||||||
|
#if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT /* { single float */
|
||||||
|
|
||||||
|
#define LUA_NUMBER float
|
||||||
|
|
||||||
|
#define l_mathlim(n) (FLT_##n)
|
||||||
|
|
||||||
|
#define LUAI_UACNUMBER double
|
||||||
|
|
||||||
|
#define LUA_NUMBER_FRMLEN ""
|
||||||
|
#define LUA_NUMBER_FMT "%.7g"
|
||||||
|
|
||||||
|
#define l_mathop(op) op##f
|
||||||
|
|
||||||
|
#define lua_str2number(s,p) strtof((s), (p))
|
||||||
|
|
||||||
|
|
||||||
|
#elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE /* }{ long double */
|
||||||
|
|
||||||
|
#define LUA_NUMBER long double
|
||||||
|
|
||||||
|
#define l_mathlim(n) (LDBL_##n)
|
||||||
|
|
||||||
|
#define LUAI_UACNUMBER long double
|
||||||
|
|
||||||
|
#define LUA_NUMBER_FRMLEN "L"
|
||||||
|
#define LUA_NUMBER_FMT "%.19Lg"
|
||||||
|
|
||||||
|
#define l_mathop(op) op##l
|
||||||
|
|
||||||
|
#define lua_str2number(s,p) strtold((s), (p))
|
||||||
|
|
||||||
|
#elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE /* }{ double */
|
||||||
|
|
||||||
|
#define LUA_NUMBER double
|
||||||
|
|
||||||
|
#define l_mathlim(n) (DBL_##n)
|
||||||
|
|
||||||
|
#define LUAI_UACNUMBER double
|
||||||
|
|
||||||
|
#define LUA_NUMBER_FRMLEN ""
|
||||||
|
#define LUA_NUMBER_FMT "%.14g"
|
||||||
|
|
||||||
|
#define l_mathop(op) op
|
||||||
|
|
||||||
|
#define lua_str2number(s,p) strtod((s), (p))
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
#error "numeric float type not defined"
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_INTEGER is the integer type used by Lua.
|
||||||
|
**
|
||||||
|
@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER.
|
||||||
|
**
|
||||||
|
@@ LUAI_UACINT is the result of a 'default argument promotion'
|
||||||
|
@@ over a lUA_INTEGER.
|
||||||
|
@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers.
|
||||||
|
@@ LUA_INTEGER_FMT is the format for writing integers.
|
||||||
|
@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER.
|
||||||
|
@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER.
|
||||||
|
@@ lua_integer2str converts an integer to a string.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/* The following definitions are good for most cases here */
|
||||||
|
|
||||||
|
#define LUA_INTEGER_FMT "%" LUA_INTEGER_FRMLEN "d"
|
||||||
|
|
||||||
|
#define LUAI_UACINT LUA_INTEGER
|
||||||
|
|
||||||
|
#define lua_integer2str(s,sz,n) \
|
||||||
|
l_sprintf((s), sz, LUA_INTEGER_FMT, (LUAI_UACINT)(n))
|
||||||
|
|
||||||
|
/*
|
||||||
|
** use LUAI_UACINT here to avoid problems with promotions (which
|
||||||
|
** can turn a comparison between unsigneds into a signed comparison)
|
||||||
|
*/
|
||||||
|
#define LUA_UNSIGNED unsigned LUAI_UACINT
|
||||||
|
|
||||||
|
|
||||||
|
/* now the variable definitions */
|
||||||
|
|
||||||
|
#if LUA_INT_TYPE == LUA_INT_INT /* { int */
|
||||||
|
|
||||||
|
#define LUA_INTEGER int
|
||||||
|
#define LUA_INTEGER_FRMLEN ""
|
||||||
|
|
||||||
|
#define LUA_MAXINTEGER INT_MAX
|
||||||
|
#define LUA_MININTEGER INT_MIN
|
||||||
|
|
||||||
|
#elif LUA_INT_TYPE == LUA_INT_LONG /* }{ long */
|
||||||
|
|
||||||
|
#define LUA_INTEGER long
|
||||||
|
#define LUA_INTEGER_FRMLEN "l"
|
||||||
|
|
||||||
|
#define LUA_MAXINTEGER LONG_MAX
|
||||||
|
#define LUA_MININTEGER LONG_MIN
|
||||||
|
|
||||||
|
#elif LUA_INT_TYPE == LUA_INT_LONGLONG /* }{ long long */
|
||||||
|
|
||||||
|
/* use presence of macro LLONG_MAX as proxy for C99 compliance */
|
||||||
|
#if defined(LLONG_MAX) /* { */
|
||||||
|
/* use ISO C99 stuff */
|
||||||
|
|
||||||
|
#define LUA_INTEGER long long
|
||||||
|
#define LUA_INTEGER_FRMLEN "ll"
|
||||||
|
|
||||||
|
#define LUA_MAXINTEGER LLONG_MAX
|
||||||
|
#define LUA_MININTEGER LLONG_MIN
|
||||||
|
|
||||||
|
#elif defined(LUA_USE_WINDOWS) /* }{ */
|
||||||
|
/* in Windows, can use specific Windows types */
|
||||||
|
|
||||||
|
#define LUA_INTEGER __int64
|
||||||
|
#define LUA_INTEGER_FRMLEN "I64"
|
||||||
|
|
||||||
|
#define LUA_MAXINTEGER _I64_MAX
|
||||||
|
#define LUA_MININTEGER _I64_MIN
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \
|
||||||
|
or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)"
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
#error "numeric integer type not defined"
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Dependencies with C99 and other C details
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ l_sprintf is equivalent to 'snprintf' or 'sprintf' in C89.
|
||||||
|
** (All uses in Lua have only one format item.)
|
||||||
|
*/
|
||||||
|
// #if !defined(LUA_USE_C89)
|
||||||
|
// #define l_sprintf(s,sz,f,i) snprintf(s,sz,f,i)
|
||||||
|
// #else
|
||||||
|
// #define l_sprintf(s,sz,f,i) ((void)(sz), sprintf(s,f,i))
|
||||||
|
// #endif
|
||||||
|
// int l_sprintf(char *buf, size_t size, const char *fmt, ...);
|
||||||
|
//#include "printf.h"
|
||||||
|
//#define l_sprintf snprintf_
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ lua_strx2number converts an hexadecimal numeric string to a number.
|
||||||
|
** In C99, 'strtod' does that conversion. Otherwise, you can
|
||||||
|
** leave 'lua_strx2number' undefined and Lua will provide its own
|
||||||
|
** implementation.
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_USE_C89)
|
||||||
|
#define lua_strx2number(s,p) lua_str2number(s,p)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ lua_pointer2str converts a pointer to a readable string in a
|
||||||
|
** non-specified way.
|
||||||
|
*/
|
||||||
|
#define lua_pointer2str(buff,sz,p) l_sprintf(buff,sz,"%p",p)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ lua_number2strx converts a float to an hexadecimal numeric string.
|
||||||
|
** In C99, 'sprintf' (with format specifiers '%a'/'%A') does that.
|
||||||
|
** Otherwise, you can leave 'lua_number2strx' undefined and Lua will
|
||||||
|
** provide its own implementation.
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_USE_C89)
|
||||||
|
#define lua_number2strx(L,b,sz,f,n) \
|
||||||
|
((void)L, l_sprintf(b,sz,f,(LUAI_UACNUMBER)(n)))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 'strtof' and 'opf' variants for math functions are not valid in
|
||||||
|
** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the
|
||||||
|
** availability of these variants. ('math.h' is already included in
|
||||||
|
** all files that use these macros.)
|
||||||
|
*/
|
||||||
|
#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF))
|
||||||
|
#undef l_mathop /* variants not available */
|
||||||
|
#undef lua_str2number
|
||||||
|
#define l_mathop(op) (lua_Number)op /* no variant */
|
||||||
|
#define lua_str2number(s,p) ((lua_Number)strtod((s), (p)))
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation
|
||||||
|
** functions. It must be a numerical type; Lua will use 'intptr_t' if
|
||||||
|
** available, otherwise it will use 'ptrdiff_t' (the nearest thing to
|
||||||
|
** 'intptr_t' in C89)
|
||||||
|
*/
|
||||||
|
#define LUA_KCONTEXT ptrdiff_t
|
||||||
|
|
||||||
|
#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \
|
||||||
|
__STDC_VERSION__ >= 199901L
|
||||||
|
#include <stdint.h>
|
||||||
|
#if defined(INTPTR_MAX) /* even in C99 this type is optional */
|
||||||
|
#undef LUA_KCONTEXT
|
||||||
|
#define LUA_KCONTEXT intptr_t
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ lua_getlocaledecpoint gets the locale "radix character" (decimal point).
|
||||||
|
** Change that if you do not want to use C locales. (Code using this
|
||||||
|
** macro must include header 'locale.h'.)
|
||||||
|
*/
|
||||||
|
#if !defined(lua_getlocaledecpoint)
|
||||||
|
#define lua_getlocaledecpoint() ('.')
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Language Variations
|
||||||
|
** =====================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_NOCVTN2S/LUA_NOCVTS2N control how Lua performs some
|
||||||
|
** coercions. Define LUA_NOCVTN2S to turn off automatic coercion from
|
||||||
|
** numbers to strings. Define LUA_NOCVTS2N to turn off automatic
|
||||||
|
** coercion from strings to numbers.
|
||||||
|
*/
|
||||||
|
/* #define LUA_NOCVTN2S */
|
||||||
|
/* #define LUA_NOCVTS2N */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_USE_APICHECK turns on several consistency checks on the C API.
|
||||||
|
** Define it as a help when debugging C code.
|
||||||
|
*/
|
||||||
|
#if defined(LUA_USE_APICHECK)
|
||||||
|
#include <assert.h>
|
||||||
|
#define luai_apicheck(l,e) assert(e)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Macros that affect the API and must be stable (that is, must be the
|
||||||
|
** same when you compile Lua and when you compile code that links to
|
||||||
|
** Lua). You probably do not want/need to change them.
|
||||||
|
** =====================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUAI_MAXSTACK limits the size of the Lua stack.
|
||||||
|
** CHANGE it if you need a different limit. This limit is arbitrary;
|
||||||
|
** its only purpose is to stop Lua from consuming unlimited stack
|
||||||
|
** space (and to reserve some numbers for pseudo-indices).
|
||||||
|
*/
|
||||||
|
#if LUAI_BITSINT >= 32
|
||||||
|
#define LUAI_MAXSTACK 1000000
|
||||||
|
#else
|
||||||
|
#define LUAI_MAXSTACK 15000
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_EXTRASPACE defines the size of a raw memory area associated with
|
||||||
|
** a Lua state with very fast access.
|
||||||
|
** CHANGE it if you need a different size.
|
||||||
|
*/
|
||||||
|
#define LUA_EXTRASPACE (sizeof(void *))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_IDSIZE gives the maximum size for the description of the source
|
||||||
|
@@ of a function in debug information.
|
||||||
|
** CHANGE it if you want a different size.
|
||||||
|
*/
|
||||||
|
#define LUA_IDSIZE 60
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
|
||||||
|
** CHANGE it if it uses too much C-stack space. (For long double,
|
||||||
|
** 'string.format("%.99f", -1e4932)' needs 5034 bytes, so a
|
||||||
|
** smaller buffer would force a memory allocation for each call to
|
||||||
|
** 'string.format'.)
|
||||||
|
*/
|
||||||
|
//#if LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE
|
||||||
|
//#define LUAL_BUFFERSIZE 8192
|
||||||
|
//#else
|
||||||
|
//#define LUAL_BUFFERSIZE ((int)(0x80 * sizeof(void*) * sizeof(lua_Integer)))
|
||||||
|
//#endif
|
||||||
|
|
||||||
|
//#define LUAL_BUFFERSIZE 256
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
@@ LUA_QL describes how error messages quote program elements.
|
||||||
|
** Lua does not use these macros anymore; they are here for
|
||||||
|
** compatibility only.
|
||||||
|
*/
|
||||||
|
#define LUA_QL(x) "'" x "'"
|
||||||
|
#define LUA_QS LUA_QL("%s")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* =================================================================== */
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Local configuration. You can use this space to add your redefinitions
|
||||||
|
** without modifying the main part of the file.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lualib.h,v 1.45.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Lua standard libraries
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef lualib_h
|
||||||
|
#define lualib_h
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
|
||||||
|
/* version suffix for environment variable names */
|
||||||
|
#define LUA_VERSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
|
||||||
|
|
||||||
|
|
||||||
|
LUAMOD_API int (luaopen_base) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_COLIBNAME "coroutine"
|
||||||
|
LUAMOD_API int (luaopen_coroutine) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_TABLIBNAME "table"
|
||||||
|
LUAMOD_API int (luaopen_table) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_IOLIBNAME "io"
|
||||||
|
LUAMOD_API int (luaopen_io) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_OSLIBNAME "os"
|
||||||
|
LUAMOD_API int (luaopen_os) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_STRLIBNAME "string"
|
||||||
|
LUAMOD_API int (luaopen_string) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_UTF8LIBNAME "utf8"
|
||||||
|
LUAMOD_API int (luaopen_utf8) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_BITLIBNAME "bit32"
|
||||||
|
LUAMOD_API int (luaopen_bit32) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_MATHLIBNAME "math"
|
||||||
|
LUAMOD_API int (luaopen_math) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_DBLIBNAME "debug"
|
||||||
|
LUAMOD_API int (luaopen_debug) (lua_State *L);
|
||||||
|
|
||||||
|
#define LUA_LOADLIBNAME "package"
|
||||||
|
LUAMOD_API int (luaopen_package) (lua_State *L);
|
||||||
|
|
||||||
|
|
||||||
|
/* open all previous libraries */
|
||||||
|
LUALIB_API void (luaL_openlibs) (lua_State *L);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(lua_assert)
|
||||||
|
#define lua_assert(x) ((void)0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
/*
|
||||||
|
Interface definitions for luat_bget.c, the memory management package.
|
||||||
|
在原版基础上,改成纯函数实现
|
||||||
|
*/
|
||||||
|
//#include <assert.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
typedef long bufsize;
|
||||||
|
|
||||||
|
#define MemSize int /* Type for size arguments to memxxx()
|
||||||
|
functions such as memcmp(). */
|
||||||
|
|
||||||
|
#define SizeQuant 8 /* Buffer allocation size quantum:
|
||||||
|
all buffers allocated are a
|
||||||
|
multiple of this size. This
|
||||||
|
MUST be a power of two. */
|
||||||
|
|
||||||
|
#if 1
|
||||||
|
#define BufStats 1 /* Define this symbol to enable the
|
||||||
|
bstats() function which calculates
|
||||||
|
the total free space in the buffer
|
||||||
|
pool, the largest available
|
||||||
|
buffer, and the total space
|
||||||
|
currently allocated. */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if 0
|
||||||
|
#define FreeWipe 1 /* Wipe free buffers to a guaranteed
|
||||||
|
pattern of garbage to trip up
|
||||||
|
miscreants who attempt to use
|
||||||
|
pointers into released buffers. */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if 1
|
||||||
|
#define BestFit 1 /* Use a best fit algorithm when
|
||||||
|
searching for space for an
|
||||||
|
allocation request. This uses
|
||||||
|
memory more efficiently, but
|
||||||
|
allocation will be much slower. */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/* Queue links */
|
||||||
|
|
||||||
|
struct qlinks {
|
||||||
|
struct bfhead *flink; /* Forward link */
|
||||||
|
struct bfhead *blink; /* Backward link */
|
||||||
|
};
|
||||||
|
|
||||||
|
/* Header in allocated and free buffers */
|
||||||
|
|
||||||
|
struct bhead {
|
||||||
|
bufsize prevfree; /* Relative link back to previous
|
||||||
|
free buffer in memory or 0 if
|
||||||
|
previous buffer is allocated. */
|
||||||
|
bufsize bsize; /* Buffer size: positive if free,
|
||||||
|
negative if allocated. */
|
||||||
|
};
|
||||||
|
#define BH(p) ((struct bhead *) (p))
|
||||||
|
|
||||||
|
/* Header in directly allocated buffers (by acqfcn) */
|
||||||
|
|
||||||
|
struct bdhead {
|
||||||
|
bufsize tsize; /* Total size, including overhead */
|
||||||
|
struct bhead bh; /* Common header */
|
||||||
|
};
|
||||||
|
#define BDH(p) ((struct bdhead *) (p))
|
||||||
|
|
||||||
|
/* Header in free buffers */
|
||||||
|
|
||||||
|
struct bfhead {
|
||||||
|
struct bhead bh; /* Common allocated/free header */
|
||||||
|
struct qlinks ql; /* Links on free list */
|
||||||
|
};
|
||||||
|
#define BFH(p) ((struct bfhead *) (p))
|
||||||
|
|
||||||
|
// static struct bfhead freelist = { /* List of free buffers */
|
||||||
|
// {0, 0},
|
||||||
|
// {&freelist, &freelist}
|
||||||
|
// };
|
||||||
|
|
||||||
|
typedef struct luat_bget
|
||||||
|
{
|
||||||
|
#ifdef BufStats
|
||||||
|
bufsize totalloc; /* Total space currently allocated */
|
||||||
|
bufsize maxalloc;
|
||||||
|
unsigned long numget;
|
||||||
|
unsigned long numrel; /* Number of bget() and brel() calls */
|
||||||
|
#endif /* BufStats */
|
||||||
|
struct bfhead freelist;
|
||||||
|
}luat_bget_t;
|
||||||
|
|
||||||
|
void luat_bget_init(luat_bget_t* bg);
|
||||||
|
void luat_bpool(luat_bget_t* bg, void *buffer, bufsize len);
|
||||||
|
void *luat_bget(luat_bget_t* bg, bufsize size);
|
||||||
|
void *luat_bgetz(luat_bget_t* bg, bufsize size);
|
||||||
|
void *luat_bgetr(luat_bget_t* bg, void *buffer, bufsize newsize);
|
||||||
|
void luat_brel(luat_bget_t* bg, void *buf);
|
||||||
|
// void luat_bectl(luat_bget_t* bg, int (*compact)(bufsize sizereq, int sequence), void *(*acquire)(bufsize size), void (*release)(void *buf), bufsize pool_incr);
|
||||||
|
void luat_bstats(luat_bget_t* bg, bufsize *curalloc, bufsize *totfree, bufsize *maxfree, unsigned long *nget, unsigned long *nrel);
|
||||||
|
// void luat_bstatse(luat_bget_t* bg, bufsize *pool_incr, long *npool, unsigned long *npget, unsigned long *nprel, unsigned long *ndget, unsigned long *ndrel);
|
||||||
|
// void luat_bufdump(luat_bget_t* bg, void *buf);
|
||||||
|
// void luat_bpoold(luat_bget_t* bg, void *pool, int dumpalloc, int dumpfree);
|
||||||
|
// int luat_bpoolv(luat_bget_t* bg, void *pool);
|
||||||
|
bufsize luat_bstatsmaxget(luat_bget_t* bg);
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lundump.h,v 1.45.1.1 2017/04/19 17:20:42 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
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lvm.h,v 2.41.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Lua virtual machine
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef lvm_h
|
||||||
|
#define lvm_h
|
||||||
|
|
||||||
|
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "ltm.h"
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(LUA_NOCVTN2S)
|
||||||
|
#define cvt2str(o) ttisnumber(o)
|
||||||
|
#else
|
||||||
|
#define cvt2str(o) 0 /* no conversion from numbers to strings */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(LUA_NOCVTS2N)
|
||||||
|
#define cvt2num(o) ttisstring(o)
|
||||||
|
#else
|
||||||
|
#define cvt2num(o) 0 /* no conversion from strings to numbers */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** You can define LUA_FLOORN2I if you want to convert floats to integers
|
||||||
|
** by flooring them (instead of raising an error if they are not
|
||||||
|
** integral values)
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_FLOORN2I)
|
||||||
|
#define LUA_FLOORN2I 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#define tonumber(o,n) \
|
||||||
|
(ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))
|
||||||
|
|
||||||
|
#define tointeger(o,i) \
|
||||||
|
(ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger(o,i,LUA_FLOORN2I))
|
||||||
|
|
||||||
|
#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2))
|
||||||
|
|
||||||
|
#define luaV_rawequalobj(t1,t2) luaV_equalobj(NULL,t1,t2)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** fast track for 'gettable': if 't' is a table and 't[k]' is not nil,
|
||||||
|
** return 1 with 'slot' pointing to 't[k]' (final result). Otherwise,
|
||||||
|
** return 0 (meaning it will have to check metamethod) with 'slot'
|
||||||
|
** pointing to a nil 't[k]' (if 't' is a table) or NULL (otherwise).
|
||||||
|
** 'f' is the raw get function to use.
|
||||||
|
*/
|
||||||
|
#define luaV_fastget(L,t,k,slot,f) \
|
||||||
|
(!ttistable(t) \
|
||||||
|
? (slot = NULL, 0) /* not a table; 'slot' is NULL and result is 0 */ \
|
||||||
|
: (slot = f(hvalue(t), k), /* else, do raw access */ \
|
||||||
|
!ttisnil(slot))) /* result not nil? */
|
||||||
|
|
||||||
|
/*
|
||||||
|
** standard implementation for 'gettable'
|
||||||
|
*/
|
||||||
|
#define luaV_gettable(L,t,k,v) { const TValue *slot; \
|
||||||
|
if (luaV_fastget(L,t,k,slot,luaH_get)) { setobj2s(L, v, slot); } \
|
||||||
|
else luaV_finishget(L,t,k,v,slot); }
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Fast track for set table. If 't' is a table and 't[k]' is not nil,
|
||||||
|
** call GC barrier, do a raw 't[k]=v', and return true; otherwise,
|
||||||
|
** return false with 'slot' equal to NULL (if 't' is not a table) or
|
||||||
|
** 'nil'. (This is needed by 'luaV_finishget'.) Note that, if the macro
|
||||||
|
** returns true, there is no need to 'invalidateTMcache', because the
|
||||||
|
** call is not creating a new entry.
|
||||||
|
*/
|
||||||
|
#define luaV_fastset(L,t,k,slot,f,v) \
|
||||||
|
(!ttistable(t) \
|
||||||
|
? (slot = NULL, 0) \
|
||||||
|
: (slot = f(hvalue(t), k), \
|
||||||
|
ttisnil(slot) ? 0 \
|
||||||
|
: (luaC_barrierback(L, hvalue(t), v), \
|
||||||
|
setobj2t(L, cast(TValue *,slot), v), \
|
||||||
|
1)))
|
||||||
|
|
||||||
|
|
||||||
|
#define luaV_settable(L,t,k,v) { const TValue *slot; \
|
||||||
|
if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \
|
||||||
|
luaV_finishset(L,t,k,v,slot); }
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2);
|
||||||
|
LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
|
||||||
|
LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
|
||||||
|
LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);
|
||||||
|
LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode);
|
||||||
|
LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key,
|
||||||
|
StkId val, const TValue *slot);
|
||||||
|
LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
|
||||||
|
StkId val, const TValue *slot);
|
||||||
|
LUAI_FUNC void luaV_finishOp (lua_State *L);
|
||||||
|
LUAI_FUNC void luaV_execute (lua_State *L);
|
||||||
|
LUAI_FUNC void luaV_concat (lua_State *L, int total);
|
||||||
|
LUAI_FUNC lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y);
|
||||||
|
LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y);
|
||||||
|
LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y);
|
||||||
|
LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lzio.h,v 1.31.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Buffered streams
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef lzio_h
|
||||||
|
#define lzio_h
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lmem.h"
|
||||||
|
|
||||||
|
|
||||||
|
#define EOZ (-1) /* end of stream */
|
||||||
|
|
||||||
|
typedef struct Zio ZIO;
|
||||||
|
|
||||||
|
#define zgetc(z) (((z)->n--)>0 ? cast_uchar(*(z)->p++) : luaZ_fill(z))
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct Mbuffer {
|
||||||
|
char *buffer;
|
||||||
|
size_t n;
|
||||||
|
size_t buffsize;
|
||||||
|
} Mbuffer;
|
||||||
|
|
||||||
|
#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0)
|
||||||
|
|
||||||
|
#define luaZ_buffer(buff) ((buff)->buffer)
|
||||||
|
#define luaZ_sizebuffer(buff) ((buff)->buffsize)
|
||||||
|
#define luaZ_bufflen(buff) ((buff)->n)
|
||||||
|
|
||||||
|
#define luaZ_buffremove(buff,i) ((buff)->n -= (i))
|
||||||
|
#define luaZ_resetbuffer(buff) ((buff)->n = 0)
|
||||||
|
|
||||||
|
|
||||||
|
#define luaZ_resizebuffer(L, buff, size) \
|
||||||
|
((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \
|
||||||
|
(buff)->buffsize, size), \
|
||||||
|
(buff)->buffsize = size)
|
||||||
|
|
||||||
|
#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
|
||||||
|
void *data);
|
||||||
|
LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n); /* read next n bytes */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* --------- Private Part ------------------ */
|
||||||
|
|
||||||
|
struct Zio {
|
||||||
|
size_t n; /* bytes still unread */
|
||||||
|
const char *p; /* current position in buffer */
|
||||||
|
lua_Reader reader; /* reader function */
|
||||||
|
void *data; /* additional data */
|
||||||
|
lua_State *L; /* Lua state (for reader) */
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_FUNC int luaZ_fill (ZIO *z);
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#ifndef ROTABLE_H_
|
||||||
|
#define ROTABLE_H_
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
/* exactly the same as luaL_Reg, but since we are on small embedded
|
||||||
|
* microcontrollers, we don't assume that you have `lauxlib.h`
|
||||||
|
* available in your build! */
|
||||||
|
typedef struct rotable_Reg {
|
||||||
|
char const* name;
|
||||||
|
lua_CFunction func;
|
||||||
|
lua_Integer value;
|
||||||
|
} rotable_Reg;
|
||||||
|
|
||||||
|
/* compatible with `luaL_newlib()`, and works with `luaL_Reg` *and*
|
||||||
|
* `rotable_Reg` arrays (in case you don't use `lauxlib.h`) */
|
||||||
|
void rotable_newlib( lua_State* L, void const* reg );
|
||||||
|
|
||||||
|
/* Since userdatas can not be used as `__index` meta methods directly
|
||||||
|
* this function creates a C closure that looks up keys in a given
|
||||||
|
* `rotable_Reg` array. */
|
||||||
|
void rotable_newidx( lua_State* L, void const* reg );
|
||||||
|
|
||||||
|
#endif /* ROTABLE_H_ */
|
||||||
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#ifndef ROTABLE2_H_
|
||||||
|
#define ROTABLE2_H_
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
typedef struct rotable_Reg_Value {
|
||||||
|
int type;
|
||||||
|
union
|
||||||
|
{
|
||||||
|
lua_CFunction func;
|
||||||
|
lua_Number numvalue;
|
||||||
|
const char* strvalue;
|
||||||
|
lua_Integer intvalue;
|
||||||
|
void* ptr;
|
||||||
|
} value;
|
||||||
|
}rotable_Reg_Value_t;
|
||||||
|
|
||||||
|
/* exactly the same as luaL_Reg, but since we are on small embedded
|
||||||
|
* microcontrollers, we don't assume that you have `lauxlib.h`
|
||||||
|
* available in your build! */
|
||||||
|
typedef struct rotable_Reg2 {
|
||||||
|
char const* name;
|
||||||
|
rotable_Reg_Value_t value;
|
||||||
|
} rotable_Reg_t;
|
||||||
|
|
||||||
|
#define ROREG_FUNC(fvalue) {.type=LUA_TFUNCTION, .value={.func=fvalue}}
|
||||||
|
#define ROREG_NUM(fvalue) {.type=LUA_TNUMBER, .value={.numvalue=fvalue}}
|
||||||
|
#define ROREG_INT(fvalue) {.type=LUA_TINTEGER, .value={.intvalue=fvalue}}
|
||||||
|
#define ROREG_STR(fvalue) {.type=LUA_TSTRING, .value={.strvalue=fvalue}}
|
||||||
|
#define ROREG_PTR(fvalue) {.type=LUA_TLIGHTUSERDATA, .value={.ptr=fvalue}}
|
||||||
|
|
||||||
|
/* compatible with `luaL_newlib()`, and works with `luaL_Reg` *and*
|
||||||
|
* `rotable_Reg` arrays (in case you don't use `lauxlib.h`) */
|
||||||
|
void rotable2_newlib( lua_State* L, void const* reg );
|
||||||
|
|
||||||
|
/* Since userdatas can not be used as `__index` meta methods directly
|
||||||
|
* this function creates a C closure that looks up keys in a given
|
||||||
|
* `rotable_Reg` array. */
|
||||||
|
void rotable2_newidx( lua_State* L, void const* reg );
|
||||||
|
|
||||||
|
#endif /* ROTABLE_H_ */
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,614 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lbaselib.c,v 1.314.1.1 2017/04/19 17:39:34 roberto Exp $
|
||||||
|
** Basic library
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lbaselib_c
|
||||||
|
#define LUA_LIB
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <ctype.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lauxlib.h"
|
||||||
|
#include "lualib.h"
|
||||||
|
|
||||||
|
typedef struct debug_buff
|
||||||
|
{
|
||||||
|
int offset;
|
||||||
|
char buff[512];
|
||||||
|
char end[2];
|
||||||
|
}debug_buff_t;
|
||||||
|
|
||||||
|
static debug_buff_t dbuff = {0};
|
||||||
|
|
||||||
|
static void luat_debug_print(int index, const char* str, size_t slen, int eof) {
|
||||||
|
if (eof) {
|
||||||
|
#ifdef LUAT_LOG_NO_NEWLINE
|
||||||
|
#else
|
||||||
|
if (dbuff.offset >= 511) {
|
||||||
|
dbuff.buff[dbuff.offset] = 0x00;
|
||||||
|
luat_nprint(dbuff.buff, dbuff.offset);
|
||||||
|
dbuff.offset = 0;
|
||||||
|
}
|
||||||
|
dbuff.buff[dbuff.offset++] = '\n';
|
||||||
|
#endif
|
||||||
|
dbuff.buff[dbuff.offset] = 0x00;
|
||||||
|
#ifdef LUAT_LOG_NO_NEWLINE
|
||||||
|
if (dbuff.offset) {
|
||||||
|
luat_nprint(dbuff.buff, dbuff.offset);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
luat_nprint(dbuff.buff, dbuff.offset);
|
||||||
|
#endif
|
||||||
|
memset(&dbuff, 0, sizeof(debug_buff_t));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (index > 1) {
|
||||||
|
if (dbuff.offset >= 511) {
|
||||||
|
dbuff.buff[dbuff.offset] = 0x00;
|
||||||
|
#ifdef LUAT_LOG_NO_NEWLINE
|
||||||
|
if (dbuff.offset) {
|
||||||
|
luat_nprint(dbuff.buff, dbuff.offset);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
luat_nprint(dbuff.buff, dbuff.offset);
|
||||||
|
#endif
|
||||||
|
dbuff.offset = 0;
|
||||||
|
}
|
||||||
|
dbuff.buff[dbuff.offset++] = ' ';
|
||||||
|
}
|
||||||
|
if (dbuff.offset + slen >= 512) {
|
||||||
|
dbuff.buff[dbuff.offset] = 0x00;
|
||||||
|
#ifdef LUAT_LOG_NO_NEWLINE
|
||||||
|
if (dbuff.offset) {
|
||||||
|
luat_nprint(dbuff.buff, dbuff.offset);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
luat_nprint(dbuff.buff, dbuff.offset);
|
||||||
|
#endif
|
||||||
|
luat_nprint((char*)str, slen);
|
||||||
|
memset(&dbuff, 0, sizeof(debug_buff_t));
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
memcpy(dbuff.buff + dbuff.offset, str, slen);
|
||||||
|
dbuff.offset += slen;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int luaB_print (lua_State *L) {
|
||||||
|
int n = lua_gettop(L); /* number of arguments */
|
||||||
|
int i;
|
||||||
|
lua_getglobal(L, "tostring");
|
||||||
|
for (i=1; i<=n; i++) {
|
||||||
|
const char *s;
|
||||||
|
size_t l;
|
||||||
|
lua_pushvalue(L, -1); /* function to be called */
|
||||||
|
lua_pushvalue(L, i); /* value to print */
|
||||||
|
lua_call(L, 1, 1);
|
||||||
|
s = lua_tolstring(L, -1, &l); /* get result */
|
||||||
|
if (s == NULL)
|
||||||
|
return luaL_error(L, "'tostring' must return a string to 'print'");
|
||||||
|
luat_debug_print(i, s, l, 0);
|
||||||
|
lua_pop(L, 1); /* pop result */
|
||||||
|
}
|
||||||
|
luat_debug_print(0, NULL, 0, 1);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#define SPACECHARS " \f\n\r\t\v"
|
||||||
|
|
||||||
|
static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
|
||||||
|
lua_Unsigned n = 0;
|
||||||
|
int neg = 0;
|
||||||
|
s += strspn(s, SPACECHARS); /* skip initial spaces */
|
||||||
|
if (*s == '-') { s++; neg = 1; } /* handle signal */
|
||||||
|
else if (*s == '+') s++;
|
||||||
|
if (!isalnum((unsigned char)*s)) /* no digit? */
|
||||||
|
return NULL;
|
||||||
|
do {
|
||||||
|
int digit = (isdigit((unsigned char)*s)) ? *s - '0'
|
||||||
|
: (toupper((unsigned char)*s) - 'A') + 10;
|
||||||
|
if (digit >= base) return NULL; /* invalid numeral */
|
||||||
|
n = n * base + digit;
|
||||||
|
s++;
|
||||||
|
} while (isalnum((unsigned char)*s));
|
||||||
|
s += strspn(s, SPACECHARS); /* skip trailing spaces */
|
||||||
|
*pn = (lua_Integer)((neg) ? (0u - n) : n);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_tonumber (lua_State *L) {
|
||||||
|
if (lua_isnoneornil(L, 2)) { /* standard conversion? */
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
if (lua_type(L, 1) == LUA_TNUMBER) { /* already a number? */
|
||||||
|
lua_settop(L, 1); /* yes; return it */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
size_t l;
|
||||||
|
const char *s = lua_tolstring(L, 1, &l);
|
||||||
|
if (s != NULL && lua_stringtonumber(L, s) == l + 1)
|
||||||
|
return 1; /* successful conversion to number */
|
||||||
|
/* else not a number */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
size_t l;
|
||||||
|
const char *s;
|
||||||
|
lua_Integer n = 0; /* to avoid warnings */
|
||||||
|
lua_Integer base = luaL_checkinteger(L, 2);
|
||||||
|
luaL_checktype(L, 1, LUA_TSTRING); /* no numbers as strings */
|
||||||
|
s = lua_tolstring(L, 1, &l);
|
||||||
|
luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
|
||||||
|
if (b_str2int(s, (int)base, &n) == s + l) {
|
||||||
|
lua_pushinteger(L, n);
|
||||||
|
return 1;
|
||||||
|
} /* else not a number */
|
||||||
|
} /* else not a number */
|
||||||
|
lua_pushnil(L); /* not a number */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_error (lua_State *L) {
|
||||||
|
int level = (int)luaL_optinteger(L, 2, 1);
|
||||||
|
lua_settop(L, 1);
|
||||||
|
if (lua_type(L, 1) == LUA_TSTRING && level > 0) {
|
||||||
|
luaL_where(L, level); /* add extra information */
|
||||||
|
lua_pushvalue(L, 1);
|
||||||
|
lua_concat(L, 2);
|
||||||
|
}
|
||||||
|
return lua_error(L);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_getmetatable (lua_State *L) {
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
if (!lua_getmetatable(L, 1)) {
|
||||||
|
lua_pushnil(L);
|
||||||
|
return 1; /* no metatable */
|
||||||
|
}
|
||||||
|
luaL_getmetafield(L, 1, "__metatable");
|
||||||
|
return 1; /* returns either __metatable field (if present) or metatable */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_setmetatable (lua_State *L) {
|
||||||
|
int t = lua_type(L, 2);
|
||||||
|
luaL_checktype(L, 1, LUA_TTABLE);
|
||||||
|
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
|
||||||
|
"nil or table expected");
|
||||||
|
if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
|
||||||
|
return luaL_error(L, "cannot change a protected metatable");
|
||||||
|
lua_settop(L, 2);
|
||||||
|
lua_setmetatable(L, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_rawequal (lua_State *L) {
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
luaL_checkany(L, 2);
|
||||||
|
lua_pushboolean(L, lua_rawequal(L, 1, 2));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_rawlen (lua_State *L) {
|
||||||
|
int t = lua_type(L, 1);
|
||||||
|
luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
|
||||||
|
"table or string expected");
|
||||||
|
lua_pushinteger(L, lua_rawlen(L, 1));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_rawget (lua_State *L) {
|
||||||
|
luaL_checktype(L, 1, LUA_TTABLE);
|
||||||
|
luaL_checkany(L, 2);
|
||||||
|
lua_settop(L, 2);
|
||||||
|
lua_rawget(L, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int luaB_rawset (lua_State *L) {
|
||||||
|
luaL_checktype(L, 1, LUA_TTABLE);
|
||||||
|
luaL_checkany(L, 2);
|
||||||
|
luaL_checkany(L, 3);
|
||||||
|
lua_settop(L, 3);
|
||||||
|
lua_rawset(L, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_collectgarbage (lua_State *L) {
|
||||||
|
static const char *const opts[] = {"stop", "restart", "collect",
|
||||||
|
"count", "step", "setpause", "setstepmul",
|
||||||
|
"isrunning", NULL};
|
||||||
|
static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
|
||||||
|
LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
|
||||||
|
LUA_GCISRUNNING};
|
||||||
|
int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
|
||||||
|
int ex = (int)luaL_optinteger(L, 2, 0);
|
||||||
|
int res = lua_gc(L, o, ex);
|
||||||
|
switch (o) {
|
||||||
|
case LUA_GCCOUNT: {
|
||||||
|
int b = lua_gc(L, LUA_GCCOUNTB, 0);
|
||||||
|
lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
case LUA_GCSTEP: case LUA_GCISRUNNING: {
|
||||||
|
lua_pushboolean(L, res);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
lua_pushinteger(L, res);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_type (lua_State *L) {
|
||||||
|
int t = lua_type(L, 1);
|
||||||
|
luaL_argcheck(L, t != LUA_TNONE, 1, "value expected");
|
||||||
|
lua_pushstring(L, lua_typename(L, t));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int pairsmeta (lua_State *L, const char *method, int iszero,
|
||||||
|
lua_CFunction iter) {
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
if (luaL_getmetafield(L, 1, method) == LUA_TNIL) { /* no metamethod? */
|
||||||
|
lua_pushcfunction(L, iter); /* will return generator, */
|
||||||
|
lua_pushvalue(L, 1); /* state, */
|
||||||
|
if (iszero) lua_pushinteger(L, 0); /* and initial value */
|
||||||
|
else lua_pushnil(L);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushvalue(L, 1); /* argument 'self' to metamethod */
|
||||||
|
lua_call(L, 1, 3); /* get 3 values from metamethod */
|
||||||
|
}
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_next (lua_State *L) {
|
||||||
|
luaL_checktype(L, 1, LUA_TTABLE);
|
||||||
|
lua_settop(L, 2); /* create a 2nd argument if there isn't one */
|
||||||
|
if (lua_next(L, 1))
|
||||||
|
return 2;
|
||||||
|
else {
|
||||||
|
lua_pushnil(L);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_pairs (lua_State *L) {
|
||||||
|
return pairsmeta(L, "__pairs", 0, luaB_next);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Traversal function for 'ipairs'
|
||||||
|
*/
|
||||||
|
static int ipairsaux (lua_State *L) {
|
||||||
|
lua_Integer i = luaL_checkinteger(L, 2) + 1;
|
||||||
|
lua_pushinteger(L, i);
|
||||||
|
return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 'ipairs' function. Returns 'ipairsaux', given "table", 0.
|
||||||
|
** (The given "table" may not be a table.)
|
||||||
|
*/
|
||||||
|
static int luaB_ipairs (lua_State *L) {
|
||||||
|
#if defined(LUA_COMPAT_IPAIRS)
|
||||||
|
return pairsmeta(L, "__ipairs", 1, ipairsaux);
|
||||||
|
#else
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
lua_pushcfunction(L, ipairsaux); /* iteration function */
|
||||||
|
lua_pushvalue(L, 1); /* state */
|
||||||
|
lua_pushinteger(L, 0); /* initial value */
|
||||||
|
return 3;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int load_aux (lua_State *L, int status, int envidx) {
|
||||||
|
if (status == LUA_OK) {
|
||||||
|
if (envidx != 0) { /* 'env' parameter? */
|
||||||
|
lua_pushvalue(L, envidx); /* environment for loaded function */
|
||||||
|
if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */
|
||||||
|
lua_pop(L, 1); /* remove 'env' if not used by previous call */
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
else { /* error (message is on top of the stack) */
|
||||||
|
lua_pushnil(L);
|
||||||
|
lua_insert(L, -2); /* put before error message */
|
||||||
|
return 2; /* return nil plus error message */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_loadfile (lua_State *L) {
|
||||||
|
const char *fname = luaL_optstring(L, 1, NULL);
|
||||||
|
const char *mode = luaL_optstring(L, 2, NULL);
|
||||||
|
int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */
|
||||||
|
int status = luaL_loadfilex(L, fname, mode);
|
||||||
|
return load_aux(L, status, env);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** Generic Read function
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** reserved slot, above all arguments, to hold a copy of the returned
|
||||||
|
** string to avoid it being collected while parsed. 'load' has four
|
||||||
|
** optional arguments (chunk, source name, mode, and environment).
|
||||||
|
*/
|
||||||
|
#define RESERVEDSLOT 5
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Reader for generic 'load' function: 'lua_load' uses the
|
||||||
|
** stack for internal stuff, so the reader cannot change the
|
||||||
|
** stack top. Instead, it keeps its resulting string in a
|
||||||
|
** reserved slot inside the stack.
|
||||||
|
*/
|
||||||
|
static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
|
||||||
|
(void)(ud); /* not used */
|
||||||
|
luaL_checkstack(L, 2, "too many nested functions");
|
||||||
|
lua_pushvalue(L, 1); /* get function */
|
||||||
|
lua_call(L, 0, 1); /* call it */
|
||||||
|
if (lua_isnil(L, -1)) {
|
||||||
|
lua_pop(L, 1); /* pop result */
|
||||||
|
*size = 0;
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
else if (!lua_isstring(L, -1))
|
||||||
|
luaL_error(L, "reader function must return a string");
|
||||||
|
lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
|
||||||
|
return lua_tolstring(L, RESERVEDSLOT, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_load (lua_State *L) {
|
||||||
|
int status;
|
||||||
|
size_t l;
|
||||||
|
const char *s = lua_tolstring(L, 1, &l);
|
||||||
|
const char *mode = luaL_optstring(L, 3, "bt");
|
||||||
|
int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */
|
||||||
|
if (s != NULL) { /* loading a string? */
|
||||||
|
const char *chunkname = luaL_optstring(L, 2, s);
|
||||||
|
status = luaL_loadbufferx(L, s, l, chunkname, mode);
|
||||||
|
}
|
||||||
|
else { /* loading from a reader function */
|
||||||
|
const char *chunkname = luaL_optstring(L, 2, "=(load)");
|
||||||
|
luaL_checktype(L, 1, LUA_TFUNCTION);
|
||||||
|
lua_settop(L, RESERVEDSLOT); /* create reserved slot */
|
||||||
|
status = lua_load(L, generic_reader, NULL, chunkname, mode);
|
||||||
|
}
|
||||||
|
return load_aux(L, status, env);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
|
||||||
|
(void)d1; (void)d2; /* only to match 'lua_Kfunction' prototype */
|
||||||
|
return lua_gettop(L) - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_dofile (lua_State *L) {
|
||||||
|
const char *fname = luaL_optstring(L, 1, NULL);
|
||||||
|
lua_settop(L, 1);
|
||||||
|
if (luaL_loadfile(L, fname) != LUA_OK)
|
||||||
|
return lua_error(L);
|
||||||
|
lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
|
||||||
|
return dofilecont(L, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_assert (lua_State *L) {
|
||||||
|
if (lua_toboolean(L, 1)) /* condition is true? */
|
||||||
|
return lua_gettop(L); /* return all arguments */
|
||||||
|
else { /* error */
|
||||||
|
luaL_checkany(L, 1); /* there must be a condition */
|
||||||
|
lua_remove(L, 1); /* remove it */
|
||||||
|
lua_pushliteral(L, "assertion failed!"); /* default message */
|
||||||
|
lua_settop(L, 1); /* leave only message (default if no other one) */
|
||||||
|
return luaB_error(L); /* call 'error' */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_select (lua_State *L) {
|
||||||
|
int n = lua_gettop(L);
|
||||||
|
if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
|
||||||
|
lua_pushinteger(L, n-1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_Integer i = luaL_checkinteger(L, 1);
|
||||||
|
if (i < 0) i = n + i;
|
||||||
|
else if (i > n) i = n;
|
||||||
|
luaL_argcheck(L, 1 <= i, 1, "index out of range");
|
||||||
|
return n - (int)i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Continuation function for 'pcall' and 'xpcall'. Both functions
|
||||||
|
** already pushed a 'true' before doing the call, so in case of success
|
||||||
|
** 'finishpcall' only has to return everything in the stack minus
|
||||||
|
** 'extra' values (where 'extra' is exactly the number of items to be
|
||||||
|
** ignored).
|
||||||
|
*/
|
||||||
|
static int finishpcall (lua_State *L, int status, lua_KContext extra) {
|
||||||
|
if (status != LUA_OK && status != LUA_YIELD) { /* error? */
|
||||||
|
lua_pushboolean(L, 0); /* first result (false) */
|
||||||
|
lua_pushvalue(L, -2); /* error message */
|
||||||
|
return 2; /* return false, msg */
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return lua_gettop(L) - (int)extra; /* return all results */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_pcall (lua_State *L) {
|
||||||
|
int status;
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
lua_pushboolean(L, 1); /* first result if no errors */
|
||||||
|
lua_insert(L, 1); /* put it in place */
|
||||||
|
status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
|
||||||
|
return finishpcall(L, status, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Do a protected call with error handling. After 'lua_rotate', the
|
||||||
|
** stack will have <f, err, true, f, [args...]>; so, the function passes
|
||||||
|
** 2 to 'finishpcall' to skip the 2 first values when returning results.
|
||||||
|
*/
|
||||||
|
static int luaB_xpcall (lua_State *L) {
|
||||||
|
int status;
|
||||||
|
int n = lua_gettop(L);
|
||||||
|
luaL_checktype(L, 2, LUA_TFUNCTION); /* check error function */
|
||||||
|
lua_pushboolean(L, 1); /* first result */
|
||||||
|
lua_pushvalue(L, 1); /* function */
|
||||||
|
lua_rotate(L, 3, 2); /* move them below function's arguments */
|
||||||
|
status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
|
||||||
|
return finishpcall(L, status, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_tostring (lua_State *L) {
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
luaL_tolstring(L, 1, NULL);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
int ll_require (lua_State *L);
|
||||||
|
|
||||||
|
static const luaL_Reg base_funcs[] = {
|
||||||
|
{"assert", luaB_assert},
|
||||||
|
{"collectgarbage", luaB_collectgarbage},
|
||||||
|
{"dofile", luaB_dofile},
|
||||||
|
{"error", luaB_error},
|
||||||
|
{"getmetatable", luaB_getmetatable},
|
||||||
|
{"ipairs", luaB_ipairs},
|
||||||
|
{"loadfile", luaB_loadfile},
|
||||||
|
{"load", luaB_load},
|
||||||
|
#if defined(LUA_COMPAT_LOADSTRING)
|
||||||
|
{"loadstring", luaB_load},
|
||||||
|
#endif
|
||||||
|
{"next", luaB_next},
|
||||||
|
{"pairs", luaB_pairs},
|
||||||
|
{"pcall", luaB_pcall},
|
||||||
|
{"print", luaB_print},
|
||||||
|
{"rawequal", luaB_rawequal},
|
||||||
|
{"rawlen", luaB_rawlen},
|
||||||
|
{"rawget", luaB_rawget},
|
||||||
|
{"rawset", luaB_rawset},
|
||||||
|
{"select", luaB_select},
|
||||||
|
{"setmetatable", luaB_setmetatable},
|
||||||
|
{"tonumber", luaB_tonumber},
|
||||||
|
{"tostring", luaB_tostring},
|
||||||
|
{"type", luaB_type},
|
||||||
|
{"xpcall", luaB_xpcall},
|
||||||
|
/* placeholders */
|
||||||
|
#ifdef LUAT_MEMORY_OPT_G_FUNCS
|
||||||
|
{"require", ll_require},
|
||||||
|
#else
|
||||||
|
{"_G", NULL},
|
||||||
|
{"_VERSION", NULL},
|
||||||
|
#endif
|
||||||
|
{NULL, NULL}
|
||||||
|
};
|
||||||
|
|
||||||
|
#ifdef LUAT_MEMORY_OPT_G_FUNCS
|
||||||
|
static int luaB_index(lua_State *L) {
|
||||||
|
const char* keyname = luaL_checkstring(L, 2);
|
||||||
|
int i = 0;
|
||||||
|
while (1) {
|
||||||
|
if (base_funcs[i].name == NULL) break;
|
||||||
|
if (!strcmp(keyname, base_funcs[i].name)) {
|
||||||
|
lua_pushcfunction(L, base_funcs[i].func);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
i ++;
|
||||||
|
}
|
||||||
|
if (!strcmp(keyname, "_VERSION")) {
|
||||||
|
lua_pushliteral(L, LUA_VERSION);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!strcmp(keyname, "_G")) {
|
||||||
|
lua_pushvalue(L, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
lua_rawget(L, 1);
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int luaB_newindex(lua_State *L) {
|
||||||
|
lua_rawset(L, 1);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_base (lua_State *L) {
|
||||||
|
lua_pushglobaltable(L);
|
||||||
|
|
||||||
|
lua_pushvalue(L, -1);
|
||||||
|
lua_setfield(L, -2, "_G");
|
||||||
|
|
||||||
|
lua_pushvalue(L, -1); // _G.metatable = _G
|
||||||
|
lua_setmetatable(L, -2);
|
||||||
|
|
||||||
|
lua_pushcfunction(L, luaB_index);
|
||||||
|
lua_setfield(L, -2, "__index");
|
||||||
|
lua_pushcfunction(L, luaB_newindex);
|
||||||
|
lua_setfield(L, -2, "__newindex");
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
LUAMOD_API int luaopen_base (lua_State *L) {
|
||||||
|
/* open lib into global table */
|
||||||
|
lua_pushglobaltable(L);
|
||||||
|
luaL_setfuncs(L, base_funcs, 0);
|
||||||
|
/* set global _G */
|
||||||
|
lua_pushvalue(L, -1);
|
||||||
|
lua_setfield(L, -2, "_G");
|
||||||
|
/* set global _VERSION */
|
||||||
|
lua_pushliteral(L, LUA_VERSION);
|
||||||
|
lua_setfield(L, -2, "_VERSION");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lbitlib.c,v 1.30.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Standard library for bitwise operations
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lbitlib_c
|
||||||
|
#define LUA_LIB
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lauxlib.h"
|
||||||
|
#include "lualib.h"
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_COMPAT_BITLIB) /* { */
|
||||||
|
|
||||||
|
|
||||||
|
#define pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n))
|
||||||
|
#define checkunsigned(L,i) ((lua_Unsigned)luaL_checkinteger(L,i))
|
||||||
|
|
||||||
|
|
||||||
|
/* number of bits to consider in a number */
|
||||||
|
#if !defined(LUA_NBITS)
|
||||||
|
#define LUA_NBITS 32
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must
|
||||||
|
** be made in two parts to avoid problems when LUA_NBITS is equal to the
|
||||||
|
** number of bits in a lua_Unsigned.)
|
||||||
|
*/
|
||||||
|
#define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
|
||||||
|
|
||||||
|
|
||||||
|
/* macro to trim extra bits */
|
||||||
|
#define trim(x) ((x) & ALLONES)
|
||||||
|
|
||||||
|
|
||||||
|
/* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */
|
||||||
|
#define mask(n) (~((ALLONES << 1) << ((n) - 1)))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
static lua_Unsigned andaux (lua_State *L) {
|
||||||
|
int i, n = lua_gettop(L);
|
||||||
|
lua_Unsigned r = ~(lua_Unsigned)0;
|
||||||
|
for (i = 1; i <= n; i++)
|
||||||
|
r &= checkunsigned(L, i);
|
||||||
|
return trim(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_and (lua_State *L) {
|
||||||
|
lua_Unsigned r = andaux(L);
|
||||||
|
pushunsigned(L, r);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_test (lua_State *L) {
|
||||||
|
lua_Unsigned r = andaux(L);
|
||||||
|
lua_pushboolean(L, r != 0);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_or (lua_State *L) {
|
||||||
|
int i, n = lua_gettop(L);
|
||||||
|
lua_Unsigned r = 0;
|
||||||
|
for (i = 1; i <= n; i++)
|
||||||
|
r |= checkunsigned(L, i);
|
||||||
|
pushunsigned(L, trim(r));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_xor (lua_State *L) {
|
||||||
|
int i, n = lua_gettop(L);
|
||||||
|
lua_Unsigned r = 0;
|
||||||
|
for (i = 1; i <= n; i++)
|
||||||
|
r ^= checkunsigned(L, i);
|
||||||
|
pushunsigned(L, trim(r));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_not (lua_State *L) {
|
||||||
|
lua_Unsigned r = ~checkunsigned(L, 1);
|
||||||
|
pushunsigned(L, trim(r));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) {
|
||||||
|
if (i < 0) { /* shift right? */
|
||||||
|
i = -i;
|
||||||
|
r = trim(r);
|
||||||
|
if (i >= LUA_NBITS) r = 0;
|
||||||
|
else r >>= i;
|
||||||
|
}
|
||||||
|
else { /* shift left */
|
||||||
|
if (i >= LUA_NBITS) r = 0;
|
||||||
|
else r <<= i;
|
||||||
|
r = trim(r);
|
||||||
|
}
|
||||||
|
pushunsigned(L, r);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_lshift (lua_State *L) {
|
||||||
|
return b_shift(L, checkunsigned(L, 1), luaL_checkinteger(L, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_rshift (lua_State *L) {
|
||||||
|
return b_shift(L, checkunsigned(L, 1), -luaL_checkinteger(L, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_arshift (lua_State *L) {
|
||||||
|
lua_Unsigned r = checkunsigned(L, 1);
|
||||||
|
lua_Integer i = luaL_checkinteger(L, 2);
|
||||||
|
if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1))))
|
||||||
|
return b_shift(L, r, -i);
|
||||||
|
else { /* arithmetic shift for 'negative' number */
|
||||||
|
if (i >= LUA_NBITS) r = ALLONES;
|
||||||
|
else
|
||||||
|
r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */
|
||||||
|
pushunsigned(L, r);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_rot (lua_State *L, lua_Integer d) {
|
||||||
|
lua_Unsigned r = checkunsigned(L, 1);
|
||||||
|
int i = d & (LUA_NBITS - 1); /* i = d % NBITS */
|
||||||
|
r = trim(r);
|
||||||
|
if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */
|
||||||
|
r = (r << i) | (r >> (LUA_NBITS - i));
|
||||||
|
pushunsigned(L, trim(r));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_lrot (lua_State *L) {
|
||||||
|
return b_rot(L, luaL_checkinteger(L, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_rrot (lua_State *L) {
|
||||||
|
return b_rot(L, -luaL_checkinteger(L, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** get field and width arguments for field-manipulation functions,
|
||||||
|
** checking whether they are valid.
|
||||||
|
** ('luaL_error' called without 'return' to avoid later warnings about
|
||||||
|
** 'width' being used uninitialized.)
|
||||||
|
*/
|
||||||
|
static int fieldargs (lua_State *L, int farg, int *width) {
|
||||||
|
lua_Integer f = luaL_checkinteger(L, farg);
|
||||||
|
lua_Integer w = luaL_optinteger(L, farg + 1, 1);
|
||||||
|
luaL_argcheck(L, 0 <= f, farg, "field cannot be negative");
|
||||||
|
luaL_argcheck(L, 0 < w, farg + 1, "width must be positive");
|
||||||
|
if (f + w > LUA_NBITS)
|
||||||
|
luaL_error(L, "trying to access non-existent bits");
|
||||||
|
*width = (int)w;
|
||||||
|
return (int)f;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_extract (lua_State *L) {
|
||||||
|
int w;
|
||||||
|
lua_Unsigned r = trim(checkunsigned(L, 1));
|
||||||
|
int f = fieldargs(L, 2, &w);
|
||||||
|
r = (r >> f) & mask(w);
|
||||||
|
pushunsigned(L, r);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int b_replace (lua_State *L) {
|
||||||
|
int w;
|
||||||
|
lua_Unsigned r = trim(checkunsigned(L, 1));
|
||||||
|
lua_Unsigned v = trim(checkunsigned(L, 2));
|
||||||
|
int f = fieldargs(L, 3, &w);
|
||||||
|
lua_Unsigned m = mask(w);
|
||||||
|
r = (r & ~(m << f)) | ((v & m) << f);
|
||||||
|
pushunsigned(L, r);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lua: res = bit( position )
|
||||||
|
static int b_bit( lua_State* L )
|
||||||
|
{
|
||||||
|
lua_pushinteger( L, ( lua_Integer )( 1 << (lua_Unsigned)luaL_checkinteger( L, 1 ) ) );
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lua: res = set( value, pos1, pos2, ... )
|
||||||
|
static int b_set( lua_State* L )
|
||||||
|
{
|
||||||
|
lua_Unsigned val = (lua_Unsigned)luaL_checkinteger( L, 1 );
|
||||||
|
unsigned total = lua_gettop( L ), i;
|
||||||
|
|
||||||
|
for( i = 2; i <= total; i ++ )
|
||||||
|
val |= 1 << ( unsigned )luaL_checkinteger( L, i );
|
||||||
|
lua_pushinteger( L, ( lua_Integer )val );
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lua: res = clear( value, pos1, pos2, ... )
|
||||||
|
static int b_clear( lua_State* L )
|
||||||
|
{
|
||||||
|
lua_Unsigned val = (lua_Unsigned)luaL_checkinteger( L, 1 );
|
||||||
|
unsigned total = lua_gettop( L ), i;
|
||||||
|
|
||||||
|
for( i = 2; i <= total; i ++ )
|
||||||
|
val &= ~( 1 << ( unsigned )luaL_checkinteger( L, i ) );
|
||||||
|
lua_pushinteger( L, ( lua_Integer )val );
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lua: res = isset( value, position )
|
||||||
|
static int b_isset( lua_State* L )
|
||||||
|
{
|
||||||
|
lua_Unsigned val = (lua_Unsigned)luaL_checkinteger( L, 1 );
|
||||||
|
unsigned pos = ( unsigned )luaL_checkinteger( L, 2 );
|
||||||
|
|
||||||
|
lua_pushboolean( L, val & ( 1 << pos ) ? 1 : 0 );
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lua: res = isclear( value, position )
|
||||||
|
static int b_isclear( lua_State* L )
|
||||||
|
{
|
||||||
|
lua_Unsigned val = (lua_Unsigned)luaL_checkinteger( L, 1 );
|
||||||
|
unsigned pos = ( unsigned )luaL_checkinteger( L, 2 );
|
||||||
|
|
||||||
|
lua_pushboolean( L, val & ( 1 << pos ) ? 0 : 1 );
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#include "rotable2.h"
|
||||||
|
static const rotable_Reg_t bitlib[] = {
|
||||||
|
{"arshift", ROREG_FUNC(b_arshift)},
|
||||||
|
{"band", ROREG_FUNC(b_and)},
|
||||||
|
{"bnot", ROREG_FUNC(b_not)},
|
||||||
|
{"bor", ROREG_FUNC(b_or)},
|
||||||
|
{"bxor", ROREG_FUNC(b_xor)},
|
||||||
|
{"btest", ROREG_FUNC(b_test)},
|
||||||
|
{"extract", ROREG_FUNC(b_extract)},
|
||||||
|
{"lrotate", ROREG_FUNC(b_lrot)},
|
||||||
|
{"lshift", ROREG_FUNC(b_lshift)},
|
||||||
|
{"replace", ROREG_FUNC(b_replace)},
|
||||||
|
{"rrotate", ROREG_FUNC(b_rrot)},
|
||||||
|
{"rshift", ROREG_FUNC(b_rshift)},
|
||||||
|
{"bit", ROREG_FUNC(b_bit)},
|
||||||
|
{"set", ROREG_FUNC(b_set)},
|
||||||
|
{"clear", ROREG_FUNC(b_clear)},
|
||||||
|
{"isset", ROREG_FUNC(b_isset)},
|
||||||
|
{"isclear", ROREG_FUNC(b_isclear)},
|
||||||
|
{NULL, ROREG_INT(0) }
|
||||||
|
};
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_bit32 (lua_State *L) {
|
||||||
|
luat_newlib2(L, bitlib);
|
||||||
|
lua_pushvalue(L, -1);
|
||||||
|
lua_setglobal(L, "bit"); // 兼容LuatOS-Air
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_bit32 (lua_State *L) {
|
||||||
|
return luaL_error(L, "library 'bit32' has been deprecated");
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,168 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lcorolib.c,v 1.10.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Coroutine Library
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lcorolib_c
|
||||||
|
#define LUA_LIB
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lauxlib.h"
|
||||||
|
#include "lualib.h"
|
||||||
|
|
||||||
|
|
||||||
|
static lua_State *getco (lua_State *L) {
|
||||||
|
lua_State *co = lua_tothread(L, 1);
|
||||||
|
luaL_argcheck(L, co, 1, "thread expected");
|
||||||
|
return co;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int auxresume (lua_State *L, lua_State *co, int narg) {
|
||||||
|
int status;
|
||||||
|
if (!lua_checkstack(co, narg)) {
|
||||||
|
lua_pushliteral(L, "too many arguments to resume");
|
||||||
|
return -1; /* error flag */
|
||||||
|
}
|
||||||
|
if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) {
|
||||||
|
lua_pushliteral(L, "cannot resume dead coroutine");
|
||||||
|
return -1; /* error flag */
|
||||||
|
}
|
||||||
|
lua_xmove(L, co, narg);
|
||||||
|
status = lua_resume(co, L, narg);
|
||||||
|
if (status == LUA_OK || status == LUA_YIELD) {
|
||||||
|
int nres = lua_gettop(co);
|
||||||
|
if (!lua_checkstack(L, nres + 1)) {
|
||||||
|
lua_pop(co, nres); /* remove results anyway */
|
||||||
|
lua_pushliteral(L, "too many results to resume");
|
||||||
|
return -1; /* error flag */
|
||||||
|
}
|
||||||
|
lua_xmove(co, L, nres); /* move yielded values */
|
||||||
|
return nres;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_xmove(co, L, 1); /* move error message */
|
||||||
|
return -1; /* error flag */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_coresume (lua_State *L) {
|
||||||
|
lua_State *co = getco(L);
|
||||||
|
int r;
|
||||||
|
r = auxresume(L, co, lua_gettop(L) - 1);
|
||||||
|
if (r < 0) {
|
||||||
|
lua_pushboolean(L, 0);
|
||||||
|
lua_insert(L, -2);
|
||||||
|
return 2; /* return false + error message */
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushboolean(L, 1);
|
||||||
|
lua_insert(L, -(r + 1));
|
||||||
|
return r + 1; /* return true + 'resume' returns */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_auxwrap (lua_State *L) {
|
||||||
|
lua_State *co = lua_tothread(L, lua_upvalueindex(1));
|
||||||
|
int r = auxresume(L, co, lua_gettop(L));
|
||||||
|
if (r < 0) {
|
||||||
|
if (lua_type(L, -1) == LUA_TSTRING) { /* error object is a string? */
|
||||||
|
luaL_where(L, 1); /* add extra info */
|
||||||
|
lua_insert(L, -2);
|
||||||
|
lua_concat(L, 2);
|
||||||
|
}
|
||||||
|
return lua_error(L); /* propagate error */
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_cocreate (lua_State *L) {
|
||||||
|
lua_State *NL;
|
||||||
|
luaL_checktype(L, 1, LUA_TFUNCTION);
|
||||||
|
NL = lua_newthread(L);
|
||||||
|
lua_pushvalue(L, 1); /* move function to top */
|
||||||
|
lua_xmove(L, NL, 1); /* move function from L to NL */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_cowrap (lua_State *L) {
|
||||||
|
luaB_cocreate(L);
|
||||||
|
lua_pushcclosure(L, luaB_auxwrap, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_yield (lua_State *L) {
|
||||||
|
return lua_yield(L, lua_gettop(L));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_costatus (lua_State *L) {
|
||||||
|
lua_State *co = getco(L);
|
||||||
|
if (L == co) lua_pushliteral(L, "running");
|
||||||
|
else {
|
||||||
|
switch (lua_status(co)) {
|
||||||
|
case LUA_YIELD:
|
||||||
|
lua_pushliteral(L, "suspended");
|
||||||
|
break;
|
||||||
|
case LUA_OK: {
|
||||||
|
lua_Debug ar;
|
||||||
|
if (lua_getstack(co, 0, &ar) > 0) /* does it have frames? */
|
||||||
|
lua_pushliteral(L, "normal"); /* it is running */
|
||||||
|
else if (lua_gettop(co) == 0)
|
||||||
|
lua_pushliteral(L, "dead");
|
||||||
|
else
|
||||||
|
lua_pushliteral(L, "suspended"); /* initial state */
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: /* some error occurred */
|
||||||
|
lua_pushliteral(L, "dead");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_yieldable (lua_State *L) {
|
||||||
|
lua_pushboolean(L, lua_isyieldable(L));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int luaB_corunning (lua_State *L) {
|
||||||
|
int ismain = lua_pushthread(L);
|
||||||
|
lua_pushboolean(L, ismain);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#include "rotable2.h"
|
||||||
|
static const rotable_Reg_t co_funcs[] = {
|
||||||
|
{"create", ROREG_FUNC(luaB_cocreate)},
|
||||||
|
{"resume", ROREG_FUNC(luaB_coresume)},
|
||||||
|
{"running", ROREG_FUNC(luaB_corunning)},
|
||||||
|
{"status", ROREG_FUNC(luaB_costatus)},
|
||||||
|
{"wrap", ROREG_FUNC(luaB_cowrap)},
|
||||||
|
{"yield", ROREG_FUNC(luaB_yield)},
|
||||||
|
{"isyieldable", ROREG_FUNC(luaB_yieldable)},
|
||||||
|
{NULL, ROREG_INT(0) }
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_coroutine (lua_State *L) {
|
||||||
|
luat_newlib2(L, co_funcs);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lctype.c,v 1.12.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** 'ctype' functions for Lua
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lctype_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include "lctype.h"
|
||||||
|
|
||||||
|
#if !LUA_USE_CTYPE /* { */
|
||||||
|
|
||||||
|
#include <limits.h>
|
||||||
|
|
||||||
|
LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
|
||||||
|
0x00, /* EOZ */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */
|
||||||
|
0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 1. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x0c, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, /* 2. */
|
||||||
|
0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
|
||||||
|
0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, 0x16, /* 3. */
|
||||||
|
0x16, 0x16, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04,
|
||||||
|
0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 4. */
|
||||||
|
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
|
||||||
|
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 5. */
|
||||||
|
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x05,
|
||||||
|
0x04, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x05, /* 6. */
|
||||||
|
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
|
||||||
|
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */
|
||||||
|
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f. */
|
||||||
|
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
@@ -0,0 +1,456 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ldblib.c,v 1.151.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Interface from Lua to its debug API
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define ldblib_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"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** The hook table at registry[&HOOKKEY] maps threads to their current
|
||||||
|
** hook function. (We only need the unique address of 'HOOKKEY'.)
|
||||||
|
*/
|
||||||
|
static const int HOOKKEY = 0;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** If L1 != L, L1 can be in any state, and therefore there are no
|
||||||
|
** guarantees about its stack space; any push in L1 must be
|
||||||
|
** checked.
|
||||||
|
*/
|
||||||
|
static void checkstack (lua_State *L, lua_State *L1, int n) {
|
||||||
|
if (L != L1 && !lua_checkstack(L1, n))
|
||||||
|
luaL_error(L, "stack overflow");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_getregistry (lua_State *L) {
|
||||||
|
lua_pushvalue(L, LUA_REGISTRYINDEX);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_getmetatable (lua_State *L) {
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
if (!lua_getmetatable(L, 1)) {
|
||||||
|
lua_pushnil(L); /* no metatable */
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_setmetatable (lua_State *L) {
|
||||||
|
int t = lua_type(L, 2);
|
||||||
|
luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
|
||||||
|
"nil or table expected");
|
||||||
|
lua_settop(L, 2);
|
||||||
|
lua_setmetatable(L, 1);
|
||||||
|
return 1; /* return 1st argument */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_getuservalue (lua_State *L) {
|
||||||
|
if (lua_type(L, 1) != LUA_TUSERDATA)
|
||||||
|
lua_pushnil(L);
|
||||||
|
else
|
||||||
|
lua_getuservalue(L, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_setuservalue (lua_State *L) {
|
||||||
|
luaL_checktype(L, 1, LUA_TUSERDATA);
|
||||||
|
luaL_checkany(L, 2);
|
||||||
|
lua_settop(L, 2);
|
||||||
|
lua_setuservalue(L, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Auxiliary function used by several library functions: check for
|
||||||
|
** an optional thread as function's first argument and set 'arg' with
|
||||||
|
** 1 if this argument is present (so that functions can skip it to
|
||||||
|
** access their other arguments)
|
||||||
|
*/
|
||||||
|
static lua_State *getthread (lua_State *L, int *arg) {
|
||||||
|
if (lua_isthread(L, 1)) {
|
||||||
|
*arg = 1;
|
||||||
|
return lua_tothread(L, 1);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
*arg = 0;
|
||||||
|
return L; /* function will operate over current thread */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Variations of 'lua_settable', used by 'db_getinfo' to put results
|
||||||
|
** from 'lua_getinfo' into result table. Key is always a string;
|
||||||
|
** value can be a string, an int, or a boolean.
|
||||||
|
*/
|
||||||
|
static void settabss (lua_State *L, const char *k, const char *v) {
|
||||||
|
lua_pushstring(L, v);
|
||||||
|
lua_setfield(L, -2, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void settabsi (lua_State *L, const char *k, int v) {
|
||||||
|
lua_pushinteger(L, v);
|
||||||
|
lua_setfield(L, -2, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void settabsb (lua_State *L, const char *k, int v) {
|
||||||
|
lua_pushboolean(L, v);
|
||||||
|
lua_setfield(L, -2, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** In function 'db_getinfo', the call to 'lua_getinfo' may push
|
||||||
|
** results on the stack; later it creates the result table to put
|
||||||
|
** these objects. Function 'treatstackoption' puts the result from
|
||||||
|
** 'lua_getinfo' on top of the result table so that it can call
|
||||||
|
** 'lua_setfield'.
|
||||||
|
*/
|
||||||
|
static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {
|
||||||
|
if (L == L1)
|
||||||
|
lua_rotate(L, -2, 1); /* exchange object and table */
|
||||||
|
else
|
||||||
|
lua_xmove(L1, L, 1); /* move object to the "main" stack */
|
||||||
|
lua_setfield(L, -2, fname); /* put object into table */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Calls 'lua_getinfo' and collects all results in a new table.
|
||||||
|
** L1 needs stack space for an optional input (function) plus
|
||||||
|
** two optional outputs (function and line table) from function
|
||||||
|
** 'lua_getinfo'.
|
||||||
|
*/
|
||||||
|
static int db_getinfo (lua_State *L) {
|
||||||
|
lua_Debug ar;
|
||||||
|
int arg;
|
||||||
|
lua_State *L1 = getthread(L, &arg);
|
||||||
|
const char *options = luaL_optstring(L, arg+2, "flnStu");
|
||||||
|
checkstack(L, L1, 3);
|
||||||
|
if (lua_isfunction(L, arg + 1)) { /* info about a function? */
|
||||||
|
options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */
|
||||||
|
lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */
|
||||||
|
lua_xmove(L, L1, 1);
|
||||||
|
}
|
||||||
|
else { /* stack level */
|
||||||
|
if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
|
||||||
|
lua_pushnil(L); /* level out of range */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!lua_getinfo(L1, options, &ar))
|
||||||
|
return luaL_argerror(L, arg+2, "invalid option");
|
||||||
|
lua_newtable(L); /* table to collect results */
|
||||||
|
if (strchr(options, '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);
|
||||||
|
}
|
||||||
|
if (strchr(options, 'l'))
|
||||||
|
settabsi(L, "currentline", ar.currentline);
|
||||||
|
if (strchr(options, 'u')) {
|
||||||
|
settabsi(L, "nups", ar.nups);
|
||||||
|
settabsi(L, "nparams", ar.nparams);
|
||||||
|
settabsb(L, "isvararg", ar.isvararg);
|
||||||
|
}
|
||||||
|
if (strchr(options, 'n')) {
|
||||||
|
settabss(L, "name", ar.name);
|
||||||
|
settabss(L, "namewhat", ar.namewhat);
|
||||||
|
}
|
||||||
|
if (strchr(options, 't'))
|
||||||
|
settabsb(L, "istailcall", ar.istailcall);
|
||||||
|
if (strchr(options, 'L'))
|
||||||
|
treatstackoption(L, L1, "activelines");
|
||||||
|
if (strchr(options, 'f'))
|
||||||
|
treatstackoption(L, L1, "func");
|
||||||
|
return 1; /* return table */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_getlocal (lua_State *L) {
|
||||||
|
int arg;
|
||||||
|
lua_State *L1 = getthread(L, &arg);
|
||||||
|
lua_Debug ar;
|
||||||
|
const char *name;
|
||||||
|
int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */
|
||||||
|
if (lua_isfunction(L, arg + 1)) { /* function argument? */
|
||||||
|
lua_pushvalue(L, arg + 1); /* push function */
|
||||||
|
lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */
|
||||||
|
return 1; /* return only name (there is no value) */
|
||||||
|
}
|
||||||
|
else { /* stack-level argument */
|
||||||
|
int level = (int)luaL_checkinteger(L, arg + 1);
|
||||||
|
if (!lua_getstack(L1, level, &ar)) /* out of range? */
|
||||||
|
return luaL_argerror(L, arg+1, "level out of range");
|
||||||
|
checkstack(L, L1, 1);
|
||||||
|
name = lua_getlocal(L1, &ar, nvar);
|
||||||
|
if (name) {
|
||||||
|
lua_xmove(L1, L, 1); /* move local value */
|
||||||
|
lua_pushstring(L, name); /* push name */
|
||||||
|
lua_rotate(L, -2, 1); /* re-order */
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushnil(L); /* no name (nor value) */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_setlocal (lua_State *L) {
|
||||||
|
int arg;
|
||||||
|
const char *name;
|
||||||
|
lua_State *L1 = getthread(L, &arg);
|
||||||
|
lua_Debug ar;
|
||||||
|
int level = (int)luaL_checkinteger(L, arg + 1);
|
||||||
|
int nvar = (int)luaL_checkinteger(L, arg + 2);
|
||||||
|
if (!lua_getstack(L1, level, &ar)) /* out of range? */
|
||||||
|
return luaL_argerror(L, arg+1, "level out of range");
|
||||||
|
luaL_checkany(L, arg+3);
|
||||||
|
lua_settop(L, arg+3);
|
||||||
|
checkstack(L, L1, 1);
|
||||||
|
lua_xmove(L, L1, 1);
|
||||||
|
name = lua_setlocal(L1, &ar, nvar);
|
||||||
|
if (name == NULL)
|
||||||
|
lua_pop(L1, 1); /* pop value (if not popped by 'lua_setlocal') */
|
||||||
|
lua_pushstring(L, name);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** get (if 'get' is true) or set an upvalue from a closure
|
||||||
|
*/
|
||||||
|
static int auxupvalue (lua_State *L, int get) {
|
||||||
|
const char *name;
|
||||||
|
int n = (int)luaL_checkinteger(L, 2); /* upvalue index */
|
||||||
|
luaL_checktype(L, 1, LUA_TFUNCTION); /* closure */
|
||||||
|
name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
|
||||||
|
if (name == NULL) return 0;
|
||||||
|
lua_pushstring(L, name);
|
||||||
|
lua_insert(L, -(get+1)); /* no-op if get is false */
|
||||||
|
return get + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_getupvalue (lua_State *L) {
|
||||||
|
return auxupvalue(L, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_setupvalue (lua_State *L) {
|
||||||
|
luaL_checkany(L, 3);
|
||||||
|
return auxupvalue(L, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Check whether a given upvalue from a given closure exists and
|
||||||
|
** returns its index
|
||||||
|
*/
|
||||||
|
static int checkupval (lua_State *L, int argf, int argnup) {
|
||||||
|
int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */
|
||||||
|
luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */
|
||||||
|
luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,
|
||||||
|
"invalid upvalue index");
|
||||||
|
return nup;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_upvalueid (lua_State *L) {
|
||||||
|
int n = checkupval(L, 1, 2);
|
||||||
|
lua_pushlightuserdata(L, lua_upvalueid(L, 1, n));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_upvaluejoin (lua_State *L) {
|
||||||
|
int n1 = checkupval(L, 1, 2);
|
||||||
|
int n2 = checkupval(L, 3, 4);
|
||||||
|
luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected");
|
||||||
|
luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected");
|
||||||
|
lua_upvaluejoin(L, 1, n1, 3, n2);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Call hook function registered at hook table for the current
|
||||||
|
** thread (if there is one)
|
||||||
|
*/
|
||||||
|
static void hookf (lua_State *L, lua_Debug *ar) {
|
||||||
|
static const char *const hooknames[] =
|
||||||
|
{"call", "return", "line", "count", "tail call"};
|
||||||
|
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
|
||||||
|
lua_pushthread(L);
|
||||||
|
if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */
|
||||||
|
lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */
|
||||||
|
if (ar->currentline >= 0)
|
||||||
|
lua_pushinteger(L, ar->currentline); /* push current line */
|
||||||
|
else lua_pushnil(L);
|
||||||
|
lua_assert(lua_getinfo(L, "lS", ar));
|
||||||
|
lua_call(L, 2, 0); /* call hook function */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Convert a string mask (for 'sethook') into a bit mask
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Convert a bit mask (for 'gethook') into a string 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_sethook (lua_State *L) {
|
||||||
|
int arg, mask, count;
|
||||||
|
lua_Hook func;
|
||||||
|
lua_State *L1 = getthread(L, &arg);
|
||||||
|
if (lua_isnoneornil(L, arg+1)) { /* no hook? */
|
||||||
|
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 = (int)luaL_optinteger(L, arg + 3, 0);
|
||||||
|
func = hookf; mask = makemask(smask, count);
|
||||||
|
}
|
||||||
|
if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) {
|
||||||
|
lua_createtable(L, 0, 2); /* create a hook table */
|
||||||
|
lua_pushvalue(L, -1);
|
||||||
|
lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY); /* set it in position */
|
||||||
|
lua_pushstring(L, "k");
|
||||||
|
lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */
|
||||||
|
lua_pushvalue(L, -1);
|
||||||
|
lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */
|
||||||
|
}
|
||||||
|
checkstack(L, L1, 1);
|
||||||
|
lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */
|
||||||
|
lua_pushvalue(L, arg + 1); /* value (hook function) */
|
||||||
|
lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */
|
||||||
|
lua_sethook(L1, func, mask, count);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int db_gethook (lua_State *L) {
|
||||||
|
int arg;
|
||||||
|
lua_State *L1 = getthread(L, &arg);
|
||||||
|
char buff[5];
|
||||||
|
int mask = lua_gethookmask(L1);
|
||||||
|
lua_Hook hook = lua_gethook(L1);
|
||||||
|
if (hook == NULL) /* no hook? */
|
||||||
|
lua_pushnil(L);
|
||||||
|
else if (hook != hookf) /* external hook? */
|
||||||
|
lua_pushliteral(L, "external hook");
|
||||||
|
else { /* hook table must exist */
|
||||||
|
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
|
||||||
|
checkstack(L, L1, 1);
|
||||||
|
lua_pushthread(L1); lua_xmove(L1, L, 1);
|
||||||
|
lua_rawget(L, -2); /* 1st result = hooktable[L1] */
|
||||||
|
lua_remove(L, -2); /* remove hook table */
|
||||||
|
}
|
||||||
|
lua_pushstring(L, unmakemask(mask, buff)); /* 2nd result = mask */
|
||||||
|
lua_pushinteger(L, lua_gethookcount(L1)); /* 3rd result = count */
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// static int db_debug (lua_State *L) {
|
||||||
|
// for (;;) {
|
||||||
|
// char buffer[250];
|
||||||
|
// lua_writestringerror("%s", "lua_debug> ");
|
||||||
|
// 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))
|
||||||
|
// lua_writestringerror("%s\n", lua_tostring(L, -1));
|
||||||
|
// lua_settop(L, 0); /* remove eventual returns */
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
|
||||||
|
static int db_traceback (lua_State *L) {
|
||||||
|
int arg;
|
||||||
|
lua_State *L1 = getthread(L, &arg);
|
||||||
|
const char *msg = lua_tostring(L, arg + 1);
|
||||||
|
if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */
|
||||||
|
lua_pushvalue(L, arg + 1); /* return it untouched */
|
||||||
|
else {
|
||||||
|
int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);
|
||||||
|
luaL_traceback(L, L1, msg, level);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#include "rotable2.h"
|
||||||
|
static const rotable_Reg_t dblib[] = {
|
||||||
|
// {"debug", ROREG_FUNC(db_debug)},
|
||||||
|
{"getuservalue", ROREG_FUNC(db_getuservalue)},
|
||||||
|
{"gethook", ROREG_FUNC(db_gethook)},
|
||||||
|
{"getinfo", ROREG_FUNC(db_getinfo)},
|
||||||
|
{"getlocal", ROREG_FUNC(db_getlocal)},
|
||||||
|
{"getregistry", ROREG_FUNC(db_getregistry)},
|
||||||
|
{"getmetatable", ROREG_FUNC(db_getmetatable)},
|
||||||
|
{"getupvalue", ROREG_FUNC(db_getupvalue)},
|
||||||
|
{"upvaluejoin", ROREG_FUNC(db_upvaluejoin)},
|
||||||
|
{"upvalueid", ROREG_FUNC(db_upvalueid)},
|
||||||
|
{"setuservalue", ROREG_FUNC(db_setuservalue)},
|
||||||
|
{"sethook", ROREG_FUNC(db_sethook)},
|
||||||
|
{"setlocal", ROREG_FUNC(db_setlocal)},
|
||||||
|
{"setmetatable", ROREG_FUNC(db_setmetatable)},
|
||||||
|
{"setupvalue", ROREG_FUNC(db_setupvalue)},
|
||||||
|
{"traceback", ROREG_FUNC(db_traceback)},
|
||||||
|
{NULL, ROREG_INT(0) }
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_debug (lua_State *L) {
|
||||||
|
luat_newlib2(L, dblib);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,709 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ldebug.c,v 2.121.1.2 2017/07/10 17:21:50 roberto Exp $
|
||||||
|
** Debug Interface
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define ldebug_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stdarg.h>
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lapi.h"
|
||||||
|
#include "lcode.h"
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lfunc.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lopcodes.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
#include "ltable.h"
|
||||||
|
#include "ltm.h"
|
||||||
|
#include "lvm.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL)
|
||||||
|
|
||||||
|
|
||||||
|
/* Active Lua function (given call info) */
|
||||||
|
#define ci_func(ci) (clLvalue((ci)->func))
|
||||||
|
|
||||||
|
|
||||||
|
static const char *funcnamefromcode (lua_State *L, CallInfo *ci,
|
||||||
|
const char **name);
|
||||||
|
|
||||||
|
int getfuncline(Proto *p, int pc) {
|
||||||
|
int tmp2 = -1;
|
||||||
|
if (p->lineinfo) {
|
||||||
|
memcpy(&tmp2, &p->lineinfo[pc], sizeof(tmp2));
|
||||||
|
}
|
||||||
|
return tmp2;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int currentpc (CallInfo *ci) {
|
||||||
|
lua_assert(isLua(ci));
|
||||||
|
return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int currentline (CallInfo *ci) {
|
||||||
|
return getfuncline(ci_func(ci)->p, currentpc(ci));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** If function yielded, its 'func' can be in the 'extra' field. The
|
||||||
|
** next function restores 'func' to its correct value for debugging
|
||||||
|
** purposes. (It exchanges 'func' and 'extra'; so, when called again,
|
||||||
|
** after debugging, it also "re-restores" ** 'func' to its altered value.
|
||||||
|
*/
|
||||||
|
static void swapextra (lua_State *L) {
|
||||||
|
if (L->status == LUA_YIELD) {
|
||||||
|
CallInfo *ci = L->ci; /* get function that yielded */
|
||||||
|
StkId temp = ci->func; /* exchange its 'func' and 'extra' values */
|
||||||
|
ci->func = restorestack(L, ci->extra);
|
||||||
|
ci->extra = savestack(L, temp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** This function can be called asynchronously (e.g. during a signal).
|
||||||
|
** Fields 'oldpc', 'basehookcount', and 'hookcount' (set by
|
||||||
|
** 'resethookcount') are for debug only, and it is no problem if they
|
||||||
|
** get arbitrary values (causes at most one wrong hook call). 'hookmask'
|
||||||
|
** is an atomic value. We assume that pointers are atomic too (e.g., gcc
|
||||||
|
** ensures that for all platforms where it runs). Moreover, 'hook' is
|
||||||
|
** always checked before being called (see 'luaD_hook').
|
||||||
|
*/
|
||||||
|
LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
|
||||||
|
if (func == NULL || mask == 0) { /* turn off hooks? */
|
||||||
|
mask = 0;
|
||||||
|
func = NULL;
|
||||||
|
}
|
||||||
|
if (isLua(L->ci))
|
||||||
|
L->oldpc = L->ci->u.l.savedpc;
|
||||||
|
L->hook = func;
|
||||||
|
L->basehookcount = count;
|
||||||
|
resethookcount(L);
|
||||||
|
L->hookmask = cast_byte(mask);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API lua_Hook lua_gethook (lua_State *L) {
|
||||||
|
return L->hook;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int lua_gethookmask (lua_State *L) {
|
||||||
|
return L->hookmask;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int lua_gethookcount (lua_State *L) {
|
||||||
|
return L->basehookcount;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
|
||||||
|
int status;
|
||||||
|
CallInfo *ci;
|
||||||
|
if (level < 0) return 0; /* invalid (negative) level */
|
||||||
|
lua_lock(L);
|
||||||
|
for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous)
|
||||||
|
level--;
|
||||||
|
if (level == 0 && ci != &L->base_ci) { /* level found? */
|
||||||
|
status = 1;
|
||||||
|
ar->i_ci = ci;
|
||||||
|
}
|
||||||
|
else status = 0; /* no such level */
|
||||||
|
lua_unlock(L);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char *upvalname (Proto *p, int uv) {
|
||||||
|
TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name);
|
||||||
|
if (s == NULL) return "?";
|
||||||
|
else return getstr(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
|
||||||
|
int nparams = clLvalue(ci->func)->p->numparams;
|
||||||
|
if (n <= 0 || n >= cast_int(ci->u.l.base - ci->func) - nparams)
|
||||||
|
return NULL; /* no such vararg */
|
||||||
|
else {
|
||||||
|
*pos = ci->func + nparams + n;
|
||||||
|
return "(*vararg)"; /* generic name for any vararg */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char *findlocal (lua_State *L, CallInfo *ci, int n,
|
||||||
|
StkId *pos) {
|
||||||
|
const char *name = NULL;
|
||||||
|
StkId base;
|
||||||
|
if (isLua(ci)) {
|
||||||
|
if (n < 0) { /* access to vararg values? */
|
||||||
|
if (n == INT_MIN) /* '-n' would overflow (CVE-2020-24370) */
|
||||||
|
return NULL;
|
||||||
|
return findvararg(ci, -n, pos);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
base = ci->u.l.base;
|
||||||
|
name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
base = ci->func + 1;
|
||||||
|
if (name == NULL) { /* no 'standard' name? */
|
||||||
|
StkId limit = (ci == L->ci) ? L->top : ci->next->func;
|
||||||
|
if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */
|
||||||
|
name = "(*temporary)"; /* generic name for any valid slot */
|
||||||
|
else
|
||||||
|
return NULL; /* no name */
|
||||||
|
}
|
||||||
|
*pos = base + (n - 1);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
|
||||||
|
const char *name;
|
||||||
|
lua_lock(L);
|
||||||
|
swapextra(L);
|
||||||
|
if (ar == NULL) { /* information about non-active function? */
|
||||||
|
if (!isLfunction(L->top - 1)) /* not a Lua function? */
|
||||||
|
name = NULL;
|
||||||
|
else /* consider live variables at function start (parameters) */
|
||||||
|
name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0);
|
||||||
|
}
|
||||||
|
else { /* active function; get information through 'ar' */
|
||||||
|
StkId pos = NULL; /* to avoid warnings */
|
||||||
|
name = findlocal(L, ar->i_ci, n, &pos);
|
||||||
|
if (name) {
|
||||||
|
setobj2s(L, L->top, pos);
|
||||||
|
api_incr_top(L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
swapextra(L);
|
||||||
|
lua_unlock(L);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
|
||||||
|
StkId pos = NULL; /* to avoid warnings */
|
||||||
|
const char *name;
|
||||||
|
lua_lock(L);
|
||||||
|
swapextra(L);
|
||||||
|
name = findlocal(L, ar->i_ci, n, &pos);
|
||||||
|
if (name) {
|
||||||
|
setobjs2s(L, pos, L->top - 1);
|
||||||
|
L->top--; /* pop value */
|
||||||
|
}
|
||||||
|
swapextra(L);
|
||||||
|
lua_unlock(L);
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void funcinfo (lua_Debug *ar, Closure *cl) {
|
||||||
|
if (noLuaClosure(cl)) {
|
||||||
|
ar->source = "=[C]";
|
||||||
|
ar->linedefined = -1;
|
||||||
|
ar->lastlinedefined = -1;
|
||||||
|
ar->what = "C";
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Proto *p = cl->l.p;
|
||||||
|
ar->source = p->source ? getstr(p->source) : "=?";
|
||||||
|
ar->linedefined = p->linedefined;
|
||||||
|
ar->lastlinedefined = p->lastlinedefined;
|
||||||
|
ar->what = (ar->linedefined == 0) ? "main" : "Lua";
|
||||||
|
}
|
||||||
|
luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void collectvalidlines (lua_State *L, Closure *f) {
|
||||||
|
if (noLuaClosure(f)) {
|
||||||
|
setnilvalue(L->top);
|
||||||
|
api_incr_top(L);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
int i;
|
||||||
|
TValue v;
|
||||||
|
int *lineinfo = f->l.p->lineinfo;
|
||||||
|
Table *t = luaH_new(L); /* new table to store active lines */
|
||||||
|
sethvalue(L, L->top, t); /* push it on stack */
|
||||||
|
api_incr_top(L);
|
||||||
|
setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */
|
||||||
|
for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */
|
||||||
|
luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
|
||||||
|
if (ci == NULL) /* no 'ci'? */
|
||||||
|
return NULL; /* no info */
|
||||||
|
else if (ci->callstatus & CIST_FIN) { /* is this a finalizer? */
|
||||||
|
*name = "__gc";
|
||||||
|
return "metamethod"; /* report it as such */
|
||||||
|
}
|
||||||
|
/* calling function is a known Lua function? */
|
||||||
|
else if (!(ci->callstatus & CIST_TAIL) && isLua(ci->previous))
|
||||||
|
return funcnamefromcode(L, ci->previous, name);
|
||||||
|
else return NULL; /* no way to find a name */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
|
||||||
|
Closure *f, CallInfo *ci) {
|
||||||
|
int status = 1;
|
||||||
|
for (; *what; what++) {
|
||||||
|
switch (*what) {
|
||||||
|
case 'S': {
|
||||||
|
funcinfo(ar, f);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'l': {
|
||||||
|
ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'u': {
|
||||||
|
ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
|
||||||
|
if (noLuaClosure(f)) {
|
||||||
|
ar->isvararg = 1;
|
||||||
|
ar->nparams = 0;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ar->isvararg = f->l.p->is_vararg;
|
||||||
|
ar->nparams = f->l.p->numparams;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 't': {
|
||||||
|
ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'n': {
|
||||||
|
ar->namewhat = getfuncname(L, ci, &ar->name);
|
||||||
|
if (ar->namewhat == NULL) {
|
||||||
|
ar->namewhat = ""; /* not found */
|
||||||
|
ar->name = NULL;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'L':
|
||||||
|
case 'f': /* handled by lua_getinfo */
|
||||||
|
break;
|
||||||
|
default: status = 0; /* invalid option */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
|
||||||
|
int status;
|
||||||
|
Closure *cl;
|
||||||
|
CallInfo *ci;
|
||||||
|
StkId func;
|
||||||
|
lua_lock(L);
|
||||||
|
swapextra(L);
|
||||||
|
if (*what == '>') {
|
||||||
|
ci = NULL;
|
||||||
|
func = L->top - 1;
|
||||||
|
api_check(L, ttisfunction(func), "function expected");
|
||||||
|
what++; /* skip the '>' */
|
||||||
|
L->top--; /* pop function */
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ci = ar->i_ci;
|
||||||
|
func = ci->func;
|
||||||
|
lua_assert(ttisfunction(ci->func));
|
||||||
|
}
|
||||||
|
cl = ttisclosure(func) ? clvalue(func) : NULL;
|
||||||
|
status = auxgetinfo(L, what, ar, cl, ci);
|
||||||
|
if (strchr(what, 'f')) {
|
||||||
|
setobjs2s(L, L->top, func);
|
||||||
|
api_incr_top(L);
|
||||||
|
}
|
||||||
|
swapextra(L); /* correct before option 'L', which can raise a mem. error */
|
||||||
|
if (strchr(what, 'L'))
|
||||||
|
collectvalidlines(L, cl);
|
||||||
|
lua_unlock(L);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** Symbolic Execution
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
static const char *getobjname (Proto *p, int lastpc, int reg,
|
||||||
|
const char **name);
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** find a "name" for the RK value 'c'
|
||||||
|
*/
|
||||||
|
static void kname (Proto *p, int pc, int c, const char **name) {
|
||||||
|
if (ISK(c)) { /* is 'c' a constant? */
|
||||||
|
TValue *kvalue = &p->k[INDEXK(c)];
|
||||||
|
if (ttisstring(kvalue)) { /* literal constant? */
|
||||||
|
*name = svalue(kvalue); /* it is its own name */
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
/* else no reasonable name found */
|
||||||
|
}
|
||||||
|
else { /* 'c' is a register */
|
||||||
|
const char *what = getobjname(p, pc, c, name); /* search for 'c' */
|
||||||
|
if (what && *what == 'c') { /* found a constant name? */
|
||||||
|
return; /* 'name' already filled */
|
||||||
|
}
|
||||||
|
/* else no reasonable name found */
|
||||||
|
}
|
||||||
|
*name = "?"; /* no reasonable name found */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int filterpc (int pc, int jmptarget) {
|
||||||
|
if (pc < jmptarget) /* is code conditional (inside a jump)? */
|
||||||
|
return -1; /* cannot know who sets that register */
|
||||||
|
else return pc; /* current position sets that register */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** try to find last instruction before 'lastpc' that modified register 'reg'
|
||||||
|
*/
|
||||||
|
static int findsetreg (Proto *p, int lastpc, int reg) {
|
||||||
|
int pc;
|
||||||
|
int setreg = -1; /* keep last instruction that changed 'reg' */
|
||||||
|
int jmptarget = 0; /* any code before this address is conditional */
|
||||||
|
for (pc = 0; pc < lastpc; pc++) {
|
||||||
|
Instruction i = p->code[pc];
|
||||||
|
OpCode op = GET_OPCODE(i);
|
||||||
|
int a = GETARG_A(i);
|
||||||
|
switch (op) {
|
||||||
|
case OP_LOADNIL: {
|
||||||
|
int b = GETARG_B(i);
|
||||||
|
if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */
|
||||||
|
setreg = filterpc(pc, jmptarget);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case OP_TFORCALL: {
|
||||||
|
if (reg >= a + 2) /* affect all regs above its base */
|
||||||
|
setreg = filterpc(pc, jmptarget);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case OP_CALL:
|
||||||
|
case OP_TAILCALL: {
|
||||||
|
if (reg >= a) /* affect all registers above base */
|
||||||
|
setreg = filterpc(pc, jmptarget);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case OP_JMP: {
|
||||||
|
int b = GETARG_sBx(i);
|
||||||
|
int dest = pc + 1 + b;
|
||||||
|
/* jump is forward and do not skip 'lastpc'? */
|
||||||
|
if (pc < dest && dest <= lastpc) {
|
||||||
|
if (dest > jmptarget)
|
||||||
|
jmptarget = dest; /* update 'jmptarget' */
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if (testAMode(op) && reg == a) /* any instruction that set A */
|
||||||
|
setreg = filterpc(pc, jmptarget);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return setreg;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char *getobjname (Proto *p, int lastpc, int reg,
|
||||||
|
const char **name) {
|
||||||
|
int pc;
|
||||||
|
*name = luaF_getlocalname(p, reg + 1, lastpc);
|
||||||
|
if (*name) /* is a local? */
|
||||||
|
return "local";
|
||||||
|
/* else try symbolic execution */
|
||||||
|
pc = findsetreg(p, lastpc, reg);
|
||||||
|
if (pc != -1) { /* could find instruction? */
|
||||||
|
Instruction i = p->code[pc];
|
||||||
|
OpCode op = GET_OPCODE(i);
|
||||||
|
switch (op) {
|
||||||
|
case OP_MOVE: {
|
||||||
|
int b = GETARG_B(i); /* move from 'b' to 'a' */
|
||||||
|
if (b < GETARG_A(i))
|
||||||
|
return getobjname(p, pc, b, name); /* get name for 'b' */
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case OP_GETTABUP:
|
||||||
|
case OP_GETTABLE: {
|
||||||
|
int k = GETARG_C(i); /* key index */
|
||||||
|
int t = GETARG_B(i); /* table index */
|
||||||
|
const char *vn = (op == OP_GETTABLE) /* name of indexed variable */
|
||||||
|
? luaF_getlocalname(p, t + 1, pc)
|
||||||
|
: upvalname(p, t);
|
||||||
|
kname(p, pc, k, name);
|
||||||
|
return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";
|
||||||
|
}
|
||||||
|
case OP_GETUPVAL: {
|
||||||
|
*name = upvalname(p, GETARG_B(i));
|
||||||
|
return "upvalue";
|
||||||
|
}
|
||||||
|
case OP_LOADK:
|
||||||
|
case OP_LOADKX: {
|
||||||
|
int b = (op == OP_LOADK) ? GETARG_Bx(i)
|
||||||
|
: GETARG_Ax(p->code[pc + 1]);
|
||||||
|
if (ttisstring(&p->k[b])) {
|
||||||
|
*name = svalue(&p->k[b]);
|
||||||
|
return "constant";
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case OP_SELF: {
|
||||||
|
int k = GETARG_C(i); /* key index */
|
||||||
|
kname(p, pc, k, name);
|
||||||
|
return "method";
|
||||||
|
}
|
||||||
|
default: break; /* go through to return NULL */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NULL; /* could not find reasonable name */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Try to find a name for a function based on the code that called it.
|
||||||
|
** (Only works when function was called by a Lua function.)
|
||||||
|
** Returns what the name is (e.g., "for iterator", "method",
|
||||||
|
** "metamethod") and sets '*name' to point to the name.
|
||||||
|
*/
|
||||||
|
static const char *funcnamefromcode (lua_State *L, CallInfo *ci,
|
||||||
|
const char **name) {
|
||||||
|
TMS tm = (TMS)0; /* (initial value avoids warnings) */
|
||||||
|
Proto *p = ci_func(ci)->p; /* calling function */
|
||||||
|
int pc = currentpc(ci); /* calling instruction index */
|
||||||
|
Instruction i = p->code[pc]; /* calling instruction */
|
||||||
|
if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
|
||||||
|
*name = "?";
|
||||||
|
return "hook";
|
||||||
|
}
|
||||||
|
switch (GET_OPCODE(i)) {
|
||||||
|
case OP_CALL:
|
||||||
|
case OP_TAILCALL:
|
||||||
|
return getobjname(p, pc, GETARG_A(i), name); /* get function name */
|
||||||
|
case OP_TFORCALL: { /* for iterator */
|
||||||
|
*name = "for iterator";
|
||||||
|
return "for iterator";
|
||||||
|
}
|
||||||
|
/* other instructions can do calls through metamethods */
|
||||||
|
case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
|
||||||
|
tm = TM_INDEX;
|
||||||
|
break;
|
||||||
|
case OP_SETTABUP: case OP_SETTABLE:
|
||||||
|
tm = TM_NEWINDEX;
|
||||||
|
break;
|
||||||
|
case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD:
|
||||||
|
case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND:
|
||||||
|
case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: {
|
||||||
|
int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD); /* ORDER OP */
|
||||||
|
tm = cast(TMS, offset + cast_int(TM_ADD)); /* ORDER TM */
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case OP_UNM: tm = TM_UNM; break;
|
||||||
|
case OP_BNOT: tm = TM_BNOT; break;
|
||||||
|
case OP_LEN: tm = TM_LEN; break;
|
||||||
|
case OP_CONCAT: tm = TM_CONCAT; break;
|
||||||
|
case OP_EQ: tm = TM_EQ; break;
|
||||||
|
case OP_LT: tm = TM_LT; break;
|
||||||
|
case OP_LE: tm = TM_LE; break;
|
||||||
|
default:
|
||||||
|
return NULL; /* cannot find a reasonable name */
|
||||||
|
}
|
||||||
|
*name = getstr(G(L)->tmname[tm]);
|
||||||
|
return "metamethod";
|
||||||
|
}
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** The subtraction of two potentially unrelated pointers is
|
||||||
|
** not ISO C, but it should not crash a program; the subsequent
|
||||||
|
** checks are ISO C and ensure a correct result.
|
||||||
|
*/
|
||||||
|
static int isinstack (CallInfo *ci, const TValue *o) {
|
||||||
|
ptrdiff_t i = o - ci->u.l.base;
|
||||||
|
return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Checks whether value 'o' came from an upvalue. (That can only happen
|
||||||
|
** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
|
||||||
|
** upvalues.)
|
||||||
|
*/
|
||||||
|
static const char *getupvalname (CallInfo *ci, const TValue *o,
|
||||||
|
const char **name) {
|
||||||
|
LClosure *c = ci_func(ci);
|
||||||
|
int i;
|
||||||
|
for (i = 0; i < c->nupvalues; i++) {
|
||||||
|
if (c->upvals[i]->v == o) {
|
||||||
|
*name = upvalname(c->p, i);
|
||||||
|
return "upvalue";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char *varinfo (lua_State *L, const TValue *o) {
|
||||||
|
const char *name = NULL; /* to avoid warnings */
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
const char *kind = NULL;
|
||||||
|
if (isLua(ci)) {
|
||||||
|
kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
|
||||||
|
if (!kind && isinstack(ci, o)) /* no? try a register */
|
||||||
|
kind = getobjname(ci_func(ci)->p, currentpc(ci),
|
||||||
|
cast_int(o - ci->u.l.base), &name);
|
||||||
|
}
|
||||||
|
return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
|
||||||
|
const char *t = luaT_objtypename(L, o);
|
||||||
|
luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
|
||||||
|
if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
|
||||||
|
luaG_typeerror(L, p1, "concatenate");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaG_opinterror (lua_State *L, const TValue *p1,
|
||||||
|
const TValue *p2, const char *msg) {
|
||||||
|
lua_Number temp;
|
||||||
|
if (!tonumber(p1, &temp)) /* first operand is wrong? */
|
||||||
|
p2 = p1; /* now second is wrong */
|
||||||
|
luaG_typeerror(L, p2, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Error when both values are convertible to numbers, but not to integers
|
||||||
|
*/
|
||||||
|
l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
|
||||||
|
lua_Integer temp;
|
||||||
|
if (!tointeger(p1, &temp))
|
||||||
|
p2 = p1;
|
||||||
|
luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
|
||||||
|
const char *t1 = luaT_objtypename(L, p1);
|
||||||
|
const char *t2 = luaT_objtypename(L, p2);
|
||||||
|
if (strcmp(t1, t2) == 0)
|
||||||
|
luaG_runerror(L, "attempt to compare two %s values", t1);
|
||||||
|
else
|
||||||
|
luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* add src:line information to 'msg' */
|
||||||
|
const char *luaG_addinfo (lua_State *L, const char *msg, TString *src,
|
||||||
|
int line) {
|
||||||
|
char buff[LUA_IDSIZE];
|
||||||
|
if (src)
|
||||||
|
luaO_chunkid(buff, getstr(src), LUA_IDSIZE);
|
||||||
|
else { /* no source available; use "?" instead */
|
||||||
|
buff[0] = '?'; buff[1] = '\0';
|
||||||
|
}
|
||||||
|
return luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaG_errormsg (lua_State *L) {
|
||||||
|
if (L->errfunc != 0) { /* is there an error handling function? */
|
||||||
|
StkId errfunc = restorestack(L, L->errfunc);
|
||||||
|
setobjs2s(L, L->top, L->top - 1); /* move argument */
|
||||||
|
setobjs2s(L, L->top - 1, errfunc); /* push function */
|
||||||
|
L->top++; /* assume EXTRA_STACK */
|
||||||
|
luaD_callnoyield(L, L->top - 2, 1); /* call it */
|
||||||
|
}
|
||||||
|
luaD_throw(L, LUA_ERRRUN);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
const char *msg;
|
||||||
|
va_list argp;
|
||||||
|
luaC_checkGC(L); /* error message uses memory */
|
||||||
|
va_start(argp, fmt);
|
||||||
|
msg = luaO_pushvfstring(L, fmt, argp); /* format message */
|
||||||
|
va_end(argp);
|
||||||
|
if (isLua(ci)) /* if Lua function, add source:line information */
|
||||||
|
luaG_addinfo(L, msg, ci_func(ci)->p->source, currentline(ci));
|
||||||
|
luaG_errormsg(L);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaG_traceexec (lua_State *L) {
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
lu_byte mask = L->hookmask;
|
||||||
|
int counthook = (--L->hookcount == 0 && (mask & LUA_MASKCOUNT));
|
||||||
|
if (counthook)
|
||||||
|
resethookcount(L); /* reset count */
|
||||||
|
else if (!(mask & LUA_MASKLINE))
|
||||||
|
return; /* no line hook and count != 0; nothing to be done */
|
||||||
|
if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */
|
||||||
|
ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
|
||||||
|
return; /* do not call hook again (VM yielded, so it did not move) */
|
||||||
|
}
|
||||||
|
if (counthook)
|
||||||
|
luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */
|
||||||
|
if (mask & LUA_MASKLINE) {
|
||||||
|
Proto *p = ci_func(ci)->p;
|
||||||
|
int npc = pcRel(ci->u.l.savedpc, p);
|
||||||
|
int newline = getfuncline(p, npc);
|
||||||
|
if (npc == 0 || /* call linehook when enter a new function, */
|
||||||
|
ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */
|
||||||
|
newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */
|
||||||
|
luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */
|
||||||
|
}
|
||||||
|
L->oldpc = ci->u.l.savedpc;
|
||||||
|
if (L->status == LUA_YIELD) { /* did hook yield? */
|
||||||
|
if (counthook)
|
||||||
|
L->hookcount = 1; /* undo decrement to zero */
|
||||||
|
ci->u.l.savedpc--; /* undo increment (resume will increment it again) */
|
||||||
|
ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */
|
||||||
|
ci->func = L->top - 1; /* protect stack below results */
|
||||||
|
luaD_throw(L, LUA_YIELD);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,802 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ldo.c,v 2.157.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Stack and Call structure of Lua
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define ldo_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <setjmp.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lapi.h"
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lfunc.h"
|
||||||
|
#include "lgc.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lopcodes.h"
|
||||||
|
#include "lparser.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
#include "ltable.h"
|
||||||
|
#include "ltm.h"
|
||||||
|
#include "lundump.h"
|
||||||
|
#include "lvm.h"
|
||||||
|
#include "lzio.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define errorstatus(s) ((s) > LUA_YIELD)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** Error-recovery functions
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
|
||||||
|
** default, Lua handles errors with exceptions when compiling as
|
||||||
|
** C++ code, with _longjmp/_setjmp when asked to use them, and with
|
||||||
|
** longjmp/setjmp otherwise.
|
||||||
|
*/
|
||||||
|
#if !defined(LUAI_THROW) /* { */
|
||||||
|
|
||||||
|
#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
|
||||||
|
|
||||||
|
/* C++ exceptions */
|
||||||
|
#define LUAI_THROW(L,c) throw(c)
|
||||||
|
#define LUAI_TRY(L,c,a) \
|
||||||
|
try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
|
||||||
|
#define luai_jmpbuf int /* dummy variable */
|
||||||
|
|
||||||
|
#elif defined(LUA_USE_POSIX) /* }{ */
|
||||||
|
|
||||||
|
/* in POSIX, try _longjmp/_setjmp (more efficient) */
|
||||||
|
#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
|
||||||
|
#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
|
||||||
|
#define luai_jmpbuf jmp_buf
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
/* ISO C handling with long jumps */
|
||||||
|
#define LUAI_THROW(L,c) longjmp((c)->b, 1)
|
||||||
|
#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
|
||||||
|
#define luai_jmpbuf jmp_buf
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* chain list of long jump buffers */
|
||||||
|
struct lua_longjmp {
|
||||||
|
struct lua_longjmp *previous;
|
||||||
|
luai_jmpbuf b;
|
||||||
|
volatile int status; /* error code */
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
|
||||||
|
switch (errcode) {
|
||||||
|
case LUA_ERRMEM: { /* memory error? */
|
||||||
|
setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case LUA_ERRERR: {
|
||||||
|
setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
L->top = oldtop + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaD_throw (lua_State *L, int errcode) {
|
||||||
|
if (L->errorJmp) { /* thread has an error handler? */
|
||||||
|
L->errorJmp->status = errcode; /* set status */
|
||||||
|
LUAI_THROW(L, L->errorJmp); /* jump to it */
|
||||||
|
}
|
||||||
|
else { /* thread has no error handler */
|
||||||
|
global_State *g = G(L);
|
||||||
|
L->status = cast_byte(errcode); /* mark it as dead */
|
||||||
|
if (g->mainthread->errorJmp) { /* main thread has a handler? */
|
||||||
|
setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
|
||||||
|
luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
|
||||||
|
}
|
||||||
|
else { /* no handler at all; abort */
|
||||||
|
if (g->panic) { /* panic function? */
|
||||||
|
seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */
|
||||||
|
if (L->ci->top < L->top)
|
||||||
|
L->ci->top = L->top; /* pushing msg. can break this invariant */
|
||||||
|
lua_unlock(L);
|
||||||
|
g->panic(L); /* call panic function (last chance to jump out) */
|
||||||
|
}
|
||||||
|
while (1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
|
||||||
|
unsigned short oldnCcalls = L->nCcalls;
|
||||||
|
struct lua_longjmp lj;
|
||||||
|
lj.status = LUA_OK;
|
||||||
|
lj.previous = L->errorJmp; /* chain new error handler */
|
||||||
|
L->errorJmp = &lj;
|
||||||
|
LUAI_TRY(L, &lj,
|
||||||
|
(*f)(L, ud);
|
||||||
|
);
|
||||||
|
L->errorJmp = lj.previous; /* restore old error handler */
|
||||||
|
L->nCcalls = oldnCcalls;
|
||||||
|
return lj.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Stack reallocation
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
static void correctstack (lua_State *L, TValue *oldstack) {
|
||||||
|
CallInfo *ci;
|
||||||
|
UpVal *up;
|
||||||
|
L->top = (L->top - oldstack) + L->stack;
|
||||||
|
for (up = L->openupval; up != NULL; up = up->u.open.next)
|
||||||
|
up->v = (up->v - oldstack) + L->stack;
|
||||||
|
for (ci = L->ci; ci != NULL; ci = ci->previous) {
|
||||||
|
ci->top = (ci->top - oldstack) + L->stack;
|
||||||
|
ci->func = (ci->func - oldstack) + L->stack;
|
||||||
|
if (isLua(ci))
|
||||||
|
ci->u.l.base = (ci->u.l.base - oldstack) + L->stack;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* some space for error handling */
|
||||||
|
#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
|
||||||
|
|
||||||
|
|
||||||
|
void luaD_reallocstack (lua_State *L, int newsize) {
|
||||||
|
TValue *oldstack = L->stack;
|
||||||
|
int lim = L->stacksize;
|
||||||
|
lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
|
||||||
|
lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
|
||||||
|
luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue);
|
||||||
|
for (; lim < newsize; lim++)
|
||||||
|
setnilvalue(L->stack + lim); /* erase new segment */
|
||||||
|
L->stacksize = newsize;
|
||||||
|
L->stack_last = L->stack + newsize - EXTRA_STACK;
|
||||||
|
correctstack(L, oldstack);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaD_growstack (lua_State *L, int n) {
|
||||||
|
int size = L->stacksize;
|
||||||
|
if (size > LUAI_MAXSTACK) /* error after extra size? */
|
||||||
|
luaD_throw(L, LUA_ERRERR);
|
||||||
|
else {
|
||||||
|
int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
|
||||||
|
int newsize = 2 * size;
|
||||||
|
if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK;
|
||||||
|
if (newsize < needed) newsize = needed;
|
||||||
|
if (newsize > LUAI_MAXSTACK) { /* stack overflow? */
|
||||||
|
luaD_reallocstack(L, ERRORSTACKSIZE);
|
||||||
|
luaG_runerror(L, "stack overflow");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
luaD_reallocstack(L, newsize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int stackinuse (lua_State *L) {
|
||||||
|
CallInfo *ci;
|
||||||
|
StkId lim = L->top;
|
||||||
|
for (ci = L->ci; ci != NULL; ci = ci->previous) {
|
||||||
|
if (lim < ci->top) lim = ci->top;
|
||||||
|
}
|
||||||
|
lua_assert(lim <= L->stack_last);
|
||||||
|
return cast_int(lim - L->stack) + 1; /* part of stack in use */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaD_shrinkstack (lua_State *L) {
|
||||||
|
int inuse = stackinuse(L);
|
||||||
|
int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
|
||||||
|
if (goodsize > LUAI_MAXSTACK)
|
||||||
|
goodsize = LUAI_MAXSTACK; /* respect stack limit */
|
||||||
|
if (L->stacksize > LUAI_MAXSTACK) /* had been handling stack overflow? */
|
||||||
|
luaE_freeCI(L); /* free all CIs (list grew because of an error) */
|
||||||
|
else
|
||||||
|
luaE_shrinkCI(L); /* shrink list */
|
||||||
|
/* if thread is currently not handling a stack overflow and its
|
||||||
|
good size is smaller than current size, shrink its stack */
|
||||||
|
if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&
|
||||||
|
goodsize < L->stacksize)
|
||||||
|
luaD_reallocstack(L, goodsize);
|
||||||
|
else /* don't change stack */
|
||||||
|
condmovestack(L,{},{}); /* (change only for debugging) */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaD_inctop (lua_State *L) {
|
||||||
|
luaD_checkstack(L, 1);
|
||||||
|
L->top++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Call a hook for the given event. Make sure there is a hook to be
|
||||||
|
** called. (Both 'L->hook' and 'L->hookmask', which triggers this
|
||||||
|
** function, can be changed asynchronously by signals.)
|
||||||
|
*/
|
||||||
|
void luaD_hook (lua_State *L, int event, int line) {
|
||||||
|
lua_Hook hook = L->hook;
|
||||||
|
if (hook && L->allowhook) { /* make sure there is a hook */
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
ptrdiff_t top = savestack(L, L->top);
|
||||||
|
ptrdiff_t ci_top = savestack(L, ci->top);
|
||||||
|
lua_Debug ar;
|
||||||
|
ar.event = event;
|
||||||
|
ar.currentline = line;
|
||||||
|
ar.i_ci = ci;
|
||||||
|
luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
|
||||||
|
ci->top = L->top + LUA_MINSTACK;
|
||||||
|
lua_assert(ci->top <= L->stack_last);
|
||||||
|
L->allowhook = 0; /* cannot call hooks inside a hook */
|
||||||
|
ci->callstatus |= CIST_HOOKED;
|
||||||
|
lua_unlock(L);
|
||||||
|
(*hook)(L, &ar);
|
||||||
|
lua_lock(L);
|
||||||
|
lua_assert(!L->allowhook);
|
||||||
|
L->allowhook = 1;
|
||||||
|
ci->top = restorestack(L, ci_top);
|
||||||
|
L->top = restorestack(L, top);
|
||||||
|
ci->callstatus &= ~CIST_HOOKED;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void callhook (lua_State *L, CallInfo *ci) {
|
||||||
|
int hook = LUA_HOOKCALL;
|
||||||
|
ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
|
||||||
|
if (isLua(ci->previous) &&
|
||||||
|
GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) {
|
||||||
|
ci->callstatus |= CIST_TAIL;
|
||||||
|
hook = LUA_HOOKTAILCALL;
|
||||||
|
}
|
||||||
|
luaD_hook(L, hook, -1);
|
||||||
|
ci->u.l.savedpc--; /* correct 'pc' */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
|
||||||
|
int i;
|
||||||
|
int nfixargs = p->numparams;
|
||||||
|
StkId base, fixed;
|
||||||
|
/* move fixed parameters to final position */
|
||||||
|
fixed = L->top - actual; /* first fixed argument */
|
||||||
|
base = L->top; /* final position of first argument */
|
||||||
|
for (i = 0; i < nfixargs && i < actual; i++) {
|
||||||
|
setobjs2s(L, L->top++, fixed + i);
|
||||||
|
setnilvalue(fixed + i); /* erase original copy (for GC) */
|
||||||
|
}
|
||||||
|
for (; i < nfixargs; i++)
|
||||||
|
setnilvalue(L->top++); /* complete missing arguments */
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Check whether __call metafield of 'func' is a function. If so, put
|
||||||
|
** it in stack below original 'func' so that 'luaD_precall' can call
|
||||||
|
** it. Raise an error if __call metafield is not a function.
|
||||||
|
*/
|
||||||
|
static void tryfuncTM (lua_State *L, StkId func) {
|
||||||
|
const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
|
||||||
|
StkId p;
|
||||||
|
if (!ttisfunction(tm))
|
||||||
|
luaG_typeerror(L, func, "call");
|
||||||
|
/* Open a hole inside the stack at 'func' */
|
||||||
|
for (p = L->top; p > func; p--)
|
||||||
|
setobjs2s(L, p, p-1);
|
||||||
|
L->top++; /* slot ensured by caller */
|
||||||
|
setobj2s(L, func, tm); /* tag method is the new function to be called */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
|
||||||
|
** Handle most typical cases (zero results for commands, one result for
|
||||||
|
** expressions, multiple results for tail calls/single parameters)
|
||||||
|
** separated.
|
||||||
|
*/
|
||||||
|
static int moveresults (lua_State *L, const TValue *firstResult, StkId res,
|
||||||
|
int nres, int wanted) {
|
||||||
|
switch (wanted) { /* handle typical cases separately */
|
||||||
|
case 0: break; /* nothing to move */
|
||||||
|
case 1: { /* one result needed */
|
||||||
|
if (nres == 0) /* no results? */
|
||||||
|
firstResult = luaO_nilobject; /* adjust with nil */
|
||||||
|
setobjs2s(L, res, firstResult); /* move it to proper place */
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case LUA_MULTRET: {
|
||||||
|
int i;
|
||||||
|
for (i = 0; i < nres; i++) /* move all results to correct place */
|
||||||
|
setobjs2s(L, res + i, firstResult + i);
|
||||||
|
L->top = res + nres;
|
||||||
|
return 0; /* wanted == LUA_MULTRET */
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
int i;
|
||||||
|
if (wanted <= nres) { /* enough results? */
|
||||||
|
for (i = 0; i < wanted; i++) /* move wanted results to correct place */
|
||||||
|
setobjs2s(L, res + i, firstResult + i);
|
||||||
|
}
|
||||||
|
else { /* not enough results; use all of them plus nils */
|
||||||
|
for (i = 0; i < nres; i++) /* move all results to correct place */
|
||||||
|
setobjs2s(L, res + i, firstResult + i);
|
||||||
|
for (; i < wanted; i++) /* complete wanted number of results */
|
||||||
|
setnilvalue(res + i);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
L->top = res + wanted; /* top points after the last result */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Finishes a function call: calls hook if necessary, removes CallInfo,
|
||||||
|
** moves current number of results to proper place; returns 0 iff call
|
||||||
|
** wanted multiple (variable number of) results.
|
||||||
|
*/
|
||||||
|
int luaD_poscall (lua_State *L, CallInfo *ci, StkId firstResult, int nres) {
|
||||||
|
StkId res;
|
||||||
|
int wanted = ci->nresults;
|
||||||
|
if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) {
|
||||||
|
if (L->hookmask & LUA_MASKRET) {
|
||||||
|
ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */
|
||||||
|
luaD_hook(L, LUA_HOOKRET, -1);
|
||||||
|
firstResult = restorestack(L, fr);
|
||||||
|
}
|
||||||
|
L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */
|
||||||
|
}
|
||||||
|
res = ci->func; /* res == final position of 1st result */
|
||||||
|
L->ci = ci->previous; /* back to caller */
|
||||||
|
/* move results to proper place */
|
||||||
|
return moveresults(L, firstResult, res, nres, wanted);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))
|
||||||
|
|
||||||
|
|
||||||
|
/* macro to check stack size, preserving 'p' */
|
||||||
|
#define checkstackp(L,n,p) \
|
||||||
|
luaD_checkstackaux(L, n, \
|
||||||
|
ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \
|
||||||
|
luaC_checkGC(L), /* stack grow uses memory */ \
|
||||||
|
p = restorestack(L, t__)) /* 'pos' part: restore 'p' */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Prepares a function call: checks the stack, creates a new CallInfo
|
||||||
|
** entry, fills in the relevant information, calls hook if needed.
|
||||||
|
** If function is a C function, does the call, too. (Otherwise, leave
|
||||||
|
** the execution ('luaV_execute') to the caller, to allow stackless
|
||||||
|
** calls.) Returns true iff function has been executed (C function).
|
||||||
|
*/
|
||||||
|
int luaD_precall (lua_State *L, StkId func, int nresults) {
|
||||||
|
lua_CFunction f;
|
||||||
|
CallInfo *ci;
|
||||||
|
switch (ttype(func)) {
|
||||||
|
case LUA_TCCL: /* C closure */
|
||||||
|
f = clCvalue(func)->f;
|
||||||
|
goto Cfunc;
|
||||||
|
case LUA_TLCF: /* light C function */
|
||||||
|
f = fvalue(func);
|
||||||
|
Cfunc: {
|
||||||
|
int n; /* number of returns */
|
||||||
|
checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
|
||||||
|
ci = next_ci(L); /* now 'enter' new function */
|
||||||
|
ci->nresults = nresults;
|
||||||
|
ci->func = func;
|
||||||
|
ci->top = L->top + LUA_MINSTACK;
|
||||||
|
lua_assert(ci->top <= L->stack_last);
|
||||||
|
ci->callstatus = 0;
|
||||||
|
if (L->hookmask & LUA_MASKCALL)
|
||||||
|
luaD_hook(L, LUA_HOOKCALL, -1);
|
||||||
|
lua_unlock(L);
|
||||||
|
n = (*f)(L); /* do the actual call */
|
||||||
|
lua_lock(L);
|
||||||
|
api_checknelems(L, n);
|
||||||
|
luaD_poscall(L, ci, L->top - n, n);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
case LUA_TLCL: { /* Lua function: prepare its call */
|
||||||
|
StkId base;
|
||||||
|
Proto *p = clLvalue(func)->p;
|
||||||
|
int n = cast_int(L->top - func) - 1; /* number of real arguments */
|
||||||
|
int fsize = p->maxstacksize; /* frame size */
|
||||||
|
checkstackp(L, fsize, func);
|
||||||
|
if (p->is_vararg)
|
||||||
|
base = adjust_varargs(L, p, n);
|
||||||
|
else { /* non vararg function */
|
||||||
|
for (; n < p->numparams; n++)
|
||||||
|
setnilvalue(L->top++); /* complete missing arguments */
|
||||||
|
base = func + 1;
|
||||||
|
}
|
||||||
|
ci = next_ci(L); /* now 'enter' new function */
|
||||||
|
ci->nresults = nresults;
|
||||||
|
ci->func = func;
|
||||||
|
ci->u.l.base = base;
|
||||||
|
L->top = ci->top = base + fsize;
|
||||||
|
lua_assert(ci->top <= L->stack_last);
|
||||||
|
ci->u.l.savedpc = p->code; /* starting point */
|
||||||
|
ci->callstatus = CIST_LUA;
|
||||||
|
if (L->hookmask & LUA_MASKCALL)
|
||||||
|
callhook(L, ci);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
default: { /* not a function */
|
||||||
|
checkstackp(L, 1, func); /* ensure space for metamethod */
|
||||||
|
tryfuncTM(L, func); /* try to get '__call' metamethod */
|
||||||
|
return luaD_precall(L, func, nresults); /* now it must be a function */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Check appropriate error for stack overflow ("regular" overflow or
|
||||||
|
** overflow while handling stack overflow). If 'nCalls' is larger than
|
||||||
|
** LUAI_MAXCCALLS (which means it is handling a "regular" overflow) but
|
||||||
|
** smaller than 9/8 of LUAI_MAXCCALLS, does not report an error (to
|
||||||
|
** allow overflow handling to work)
|
||||||
|
*/
|
||||||
|
static void stackerror (lua_State *L) {
|
||||||
|
if (L->nCcalls == LUAI_MAXCCALLS)
|
||||||
|
luaG_runerror(L, "C stack overflow");
|
||||||
|
else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
|
||||||
|
luaD_throw(L, LUA_ERRERR); /* error while handing stack error */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Call a function (C or Lua). The function to be called is at *func.
|
||||||
|
** The arguments are on the stack, right after the function.
|
||||||
|
** When returns, all the results are on the stack, starting at the original
|
||||||
|
** function position.
|
||||||
|
*/
|
||||||
|
void luaD_call (lua_State *L, StkId func, int nResults) {
|
||||||
|
if (++L->nCcalls >= LUAI_MAXCCALLS)
|
||||||
|
stackerror(L);
|
||||||
|
if (!luaD_precall(L, func, nResults)) /* is a Lua function? */
|
||||||
|
luaV_execute(L); /* call it */
|
||||||
|
L->nCcalls--;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Similar to 'luaD_call', but does not allow yields during the call
|
||||||
|
*/
|
||||||
|
void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
|
||||||
|
L->nny++;
|
||||||
|
luaD_call(L, func, nResults);
|
||||||
|
L->nny--;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Completes the execution of an interrupted C function, calling its
|
||||||
|
** continuation function.
|
||||||
|
*/
|
||||||
|
static void finishCcall (lua_State *L, int status) {
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
int n;
|
||||||
|
/* must have a continuation and must be able to call it */
|
||||||
|
lua_assert(ci->u.c.k != NULL && L->nny == 0);
|
||||||
|
/* error status can only happen in a protected call */
|
||||||
|
lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
|
||||||
|
if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */
|
||||||
|
ci->callstatus &= ~CIST_YPCALL; /* continuation is also inside it */
|
||||||
|
L->errfunc = ci->u.c.old_errfunc; /* with the same error function */
|
||||||
|
}
|
||||||
|
/* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
|
||||||
|
handled */
|
||||||
|
adjustresults(L, ci->nresults);
|
||||||
|
lua_unlock(L);
|
||||||
|
n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation function */
|
||||||
|
lua_lock(L);
|
||||||
|
api_checknelems(L, n);
|
||||||
|
luaD_poscall(L, ci, L->top - n, n); /* finish 'luaD_precall' */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Executes "full continuation" (everything in the stack) of a
|
||||||
|
** previously interrupted coroutine until the stack is empty (or another
|
||||||
|
** interruption long-jumps out of the loop). If the coroutine is
|
||||||
|
** recovering from an error, 'ud' points to the error status, which must
|
||||||
|
** be passed to the first continuation function (otherwise the default
|
||||||
|
** status is LUA_YIELD).
|
||||||
|
*/
|
||||||
|
static void unroll (lua_State *L, void *ud) {
|
||||||
|
if (ud != NULL) /* error status? */
|
||||||
|
finishCcall(L, *(int *)ud); /* finish 'lua_pcallk' callee */
|
||||||
|
while (L->ci != &L->base_ci) { /* something in the stack */
|
||||||
|
if (!isLua(L->ci)) /* C function? */
|
||||||
|
finishCcall(L, LUA_YIELD); /* complete its execution */
|
||||||
|
else { /* Lua function */
|
||||||
|
luaV_finishOp(L); /* finish interrupted instruction */
|
||||||
|
luaV_execute(L); /* execute down to higher C 'boundary' */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Try to find a suspended protected call (a "recover point") for the
|
||||||
|
** given thread.
|
||||||
|
*/
|
||||||
|
static CallInfo *findpcall (lua_State *L) {
|
||||||
|
CallInfo *ci;
|
||||||
|
for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
|
||||||
|
if (ci->callstatus & CIST_YPCALL)
|
||||||
|
return ci;
|
||||||
|
}
|
||||||
|
return NULL; /* no pending pcall */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Recovers from an error in a coroutine. Finds a recover point (if
|
||||||
|
** there is one) and completes the execution of the interrupted
|
||||||
|
** 'luaD_pcall'. If there is no recover point, returns zero.
|
||||||
|
*/
|
||||||
|
static int recover (lua_State *L, int status) {
|
||||||
|
StkId oldtop;
|
||||||
|
CallInfo *ci = findpcall(L);
|
||||||
|
if (ci == NULL) return 0; /* no recovery point */
|
||||||
|
/* "finish" luaD_pcall */
|
||||||
|
oldtop = restorestack(L, ci->extra);
|
||||||
|
luaF_close(L, oldtop);
|
||||||
|
seterrorobj(L, status, oldtop);
|
||||||
|
L->ci = ci;
|
||||||
|
L->allowhook = getoah(ci->callstatus); /* restore original 'allowhook' */
|
||||||
|
L->nny = 0; /* should be zero to be yieldable */
|
||||||
|
luaD_shrinkstack(L);
|
||||||
|
L->errfunc = ci->u.c.old_errfunc;
|
||||||
|
return 1; /* continue running the coroutine */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Signal an error in the call to 'lua_resume', not in the execution
|
||||||
|
** of the coroutine itself. (Such errors should not be handled by any
|
||||||
|
** coroutine error handler and should not kill the coroutine.)
|
||||||
|
*/
|
||||||
|
static int resume_error (lua_State *L, const char *msg, int narg) {
|
||||||
|
L->top -= narg; /* remove args from the stack */
|
||||||
|
setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
|
||||||
|
api_incr_top(L);
|
||||||
|
lua_unlock(L);
|
||||||
|
return LUA_ERRRUN;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Do the work for 'lua_resume' in protected mode. Most of the work
|
||||||
|
** depends on the status of the coroutine: initial state, suspended
|
||||||
|
** inside a hook, or regularly suspended (optionally with a continuation
|
||||||
|
** function), plus erroneous cases: non-suspended coroutine or dead
|
||||||
|
** coroutine.
|
||||||
|
*/
|
||||||
|
static void resume (lua_State *L, void *ud) {
|
||||||
|
int n = *(cast(int*, ud)); /* number of arguments */
|
||||||
|
StkId firstArg = L->top - n; /* first argument */
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
if (L->status == LUA_OK) { /* starting a coroutine? */
|
||||||
|
if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */
|
||||||
|
luaV_execute(L); /* call it */
|
||||||
|
}
|
||||||
|
else { /* resuming from previous yield */
|
||||||
|
lua_assert(L->status == LUA_YIELD);
|
||||||
|
L->status = LUA_OK; /* mark that it is running (again) */
|
||||||
|
ci->func = restorestack(L, ci->extra);
|
||||||
|
if (isLua(ci)) /* yielded inside a hook? */
|
||||||
|
luaV_execute(L); /* just continue running Lua code */
|
||||||
|
else { /* 'common' yield */
|
||||||
|
if (ci->u.c.k != NULL) { /* does it have a continuation function? */
|
||||||
|
lua_unlock(L);
|
||||||
|
n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
|
||||||
|
lua_lock(L);
|
||||||
|
api_checknelems(L, n);
|
||||||
|
firstArg = L->top - n; /* yield results come from continuation */
|
||||||
|
}
|
||||||
|
luaD_poscall(L, ci, firstArg, n); /* finish 'luaD_precall' */
|
||||||
|
}
|
||||||
|
unroll(L, NULL); /* run continuation */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
|
||||||
|
int status;
|
||||||
|
unsigned short oldnny = L->nny; /* save "number of non-yieldable" calls */
|
||||||
|
lua_lock(L);
|
||||||
|
if (L->status == LUA_OK) { /* may be starting a coroutine */
|
||||||
|
if (L->ci != &L->base_ci) /* not in base level? */
|
||||||
|
return resume_error(L, "cannot resume non-suspended coroutine", nargs);
|
||||||
|
}
|
||||||
|
else if (L->status != LUA_YIELD)
|
||||||
|
return resume_error(L, "cannot resume dead coroutine", nargs);
|
||||||
|
L->nCcalls = (from) ? from->nCcalls + 1 : 1;
|
||||||
|
if (L->nCcalls >= LUAI_MAXCCALLS)
|
||||||
|
return resume_error(L, "C stack overflow", nargs);
|
||||||
|
luai_userstateresume(L, nargs);
|
||||||
|
L->nny = 0; /* allow yields */
|
||||||
|
api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
|
||||||
|
status = luaD_rawrunprotected(L, resume, &nargs);
|
||||||
|
if (status == -1) /* error calling 'lua_resume'? */
|
||||||
|
status = LUA_ERRRUN;
|
||||||
|
else { /* continue running after recoverable errors */
|
||||||
|
while (errorstatus(status) && recover(L, status)) {
|
||||||
|
/* unroll continuation */
|
||||||
|
status = luaD_rawrunprotected(L, unroll, &status);
|
||||||
|
}
|
||||||
|
if (errorstatus(status)) { /* unrecoverable error? */
|
||||||
|
L->status = cast_byte(status); /* mark thread as 'dead' */
|
||||||
|
seterrorobj(L, status, L->top); /* push error message */
|
||||||
|
L->ci->top = L->top;
|
||||||
|
}
|
||||||
|
else lua_assert(status == L->status); /* normal end or yield */
|
||||||
|
}
|
||||||
|
L->nny = oldnny; /* restore 'nny' */
|
||||||
|
L->nCcalls--;
|
||||||
|
lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));
|
||||||
|
lua_unlock(L);
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int lua_isyieldable (lua_State *L) {
|
||||||
|
return (L->nny == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
|
||||||
|
lua_KFunction k) {
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
luai_userstateyield(L, nresults);
|
||||||
|
lua_lock(L);
|
||||||
|
api_checknelems(L, nresults);
|
||||||
|
if (L->nny > 0) {
|
||||||
|
if (L != G(L)->mainthread)
|
||||||
|
luaG_runerror(L, "attempt to yield across a C-call boundary");
|
||||||
|
else
|
||||||
|
luaG_runerror(L, "attempt to yield from outside a coroutine");
|
||||||
|
}
|
||||||
|
L->status = LUA_YIELD;
|
||||||
|
ci->extra = savestack(L, ci->func); /* save current 'func' */
|
||||||
|
if (isLua(ci)) { /* inside a hook? */
|
||||||
|
api_check(L, k == NULL, "hooks cannot continue after yielding");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
|
||||||
|
ci->u.c.ctx = ctx; /* save context */
|
||||||
|
ci->func = L->top - nresults - 1; /* protect stack below results */
|
||||||
|
luaD_throw(L, LUA_YIELD);
|
||||||
|
}
|
||||||
|
lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
|
||||||
|
lua_unlock(L);
|
||||||
|
return 0; /* return to 'luaD_hook' */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaD_pcall (lua_State *L, Pfunc func, void *u,
|
||||||
|
ptrdiff_t old_top, ptrdiff_t ef) {
|
||||||
|
int status;
|
||||||
|
CallInfo *old_ci = L->ci;
|
||||||
|
lu_byte old_allowhooks = L->allowhook;
|
||||||
|
unsigned short old_nny = L->nny;
|
||||||
|
ptrdiff_t old_errfunc = L->errfunc;
|
||||||
|
L->errfunc = ef;
|
||||||
|
status = luaD_rawrunprotected(L, func, u);
|
||||||
|
if (status != LUA_OK) { /* an error occurred? */
|
||||||
|
StkId oldtop = restorestack(L, old_top);
|
||||||
|
luaF_close(L, oldtop); /* close possible pending closures */
|
||||||
|
seterrorobj(L, status, oldtop);
|
||||||
|
L->ci = old_ci;
|
||||||
|
L->allowhook = old_allowhooks;
|
||||||
|
L->nny = old_nny;
|
||||||
|
luaD_shrinkstack(L);
|
||||||
|
}
|
||||||
|
L->errfunc = old_errfunc;
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Execute a protected parser.
|
||||||
|
*/
|
||||||
|
struct SParser { /* data to 'f_parser' */
|
||||||
|
ZIO *z;
|
||||||
|
Mbuffer buff; /* dynamic structure used by the scanner */
|
||||||
|
Dyndata dyd; /* dynamic structures used by the parser */
|
||||||
|
const char *mode;
|
||||||
|
const char *name;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
static void checkmode (lua_State *L, const char *mode, const char *x) {
|
||||||
|
if (mode && strchr(mode, x[0]) == NULL) {
|
||||||
|
luaO_pushfstring(L,
|
||||||
|
"attempt to load a %s chunk (mode is '%s')", x, mode);
|
||||||
|
luaD_throw(L, LUA_ERRSYNTAX);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void f_parser (lua_State *L, void *ud) {
|
||||||
|
LClosure *cl;
|
||||||
|
struct SParser *p = cast(struct SParser *, ud);
|
||||||
|
int c = zgetc(p->z); /* read first character */
|
||||||
|
if (c == LUA_SIGNATURE[0]) {
|
||||||
|
checkmode(L, p->mode, "binary");
|
||||||
|
cl = luaU_undump(L, p->z, p->name);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
checkmode(L, p->mode, "text");
|
||||||
|
cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
|
||||||
|
}
|
||||||
|
lua_assert(cl->nupvalues == cl->p->sizeupvalues);
|
||||||
|
luaF_initupvals(L, cl);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
|
||||||
|
const char *mode) {
|
||||||
|
struct SParser p;
|
||||||
|
int status;
|
||||||
|
L->nny++; /* cannot yield during parsing */
|
||||||
|
p.z = z; p.name = name; p.mode = mode;
|
||||||
|
p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
|
||||||
|
p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
|
||||||
|
p.dyd.label.arr = NULL; p.dyd.label.size = 0;
|
||||||
|
luaZ_initbuffer(L, &p.buff);
|
||||||
|
status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
|
||||||
|
luaZ_freebuffer(L, &p.buff);
|
||||||
|
luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
|
||||||
|
luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
|
||||||
|
luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
|
||||||
|
L->nny--;
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,215 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ldump.c,v 2.37.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** save precompiled Lua chunks
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define ldump_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lundump.h"
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
lua_State *L;
|
||||||
|
lua_Writer writer;
|
||||||
|
void *data;
|
||||||
|
int strip;
|
||||||
|
int status;
|
||||||
|
} DumpState;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** All high-level dumps go through DumpVector; you can change it to
|
||||||
|
** change the endianness of the result
|
||||||
|
*/
|
||||||
|
#define DumpVector(v,n,D) DumpBlock(v,(n)*sizeof((v)[0]),D)
|
||||||
|
|
||||||
|
#define DumpLiteral(s,D) DumpBlock(s, sizeof(s) - sizeof(char), D)
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpBlock (const void *b, size_t size, DumpState *D) {
|
||||||
|
if (D->status == 0 && size > 0) {
|
||||||
|
lua_unlock(D->L);
|
||||||
|
D->status = (*D->writer)(D->L, b, size, D->data);
|
||||||
|
lua_lock(D->L);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#define DumpVar(x,D) DumpVector(&x,1,D)
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpByte (int y, DumpState *D) {
|
||||||
|
lu_byte x = (lu_byte)y;
|
||||||
|
DumpVar(x, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpInt (int x, DumpState *D) {
|
||||||
|
DumpVar(x, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpNumber (lua_Number x, DumpState *D) {
|
||||||
|
DumpVar(x, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpInteger (lua_Integer x, DumpState *D) {
|
||||||
|
DumpVar(x, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpString (const TString *s, DumpState *D) {
|
||||||
|
if (s == NULL)
|
||||||
|
DumpByte(0, D);
|
||||||
|
else {
|
||||||
|
size_t size = tsslen(s) + 1; /* include trailing '\0' */
|
||||||
|
const char *str = getstr(s);
|
||||||
|
if (size < 0xFF)
|
||||||
|
DumpByte(cast_int(size), D);
|
||||||
|
else {
|
||||||
|
DumpByte(0xFF, D);
|
||||||
|
DumpVar(size, D);
|
||||||
|
}
|
||||||
|
DumpVector(str, size - 1, D); /* no need to save '\0' */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpCode (const Proto *f, DumpState *D) {
|
||||||
|
DumpInt(f->sizecode, D);
|
||||||
|
DumpVector(f->code, f->sizecode, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpFunction(const Proto *f, TString *psource, DumpState *D);
|
||||||
|
|
||||||
|
static void DumpConstants (const Proto *f, DumpState *D) {
|
||||||
|
int i;
|
||||||
|
int n = f->sizek;
|
||||||
|
DumpInt(n, D);
|
||||||
|
for (i = 0; i < n; i++) {
|
||||||
|
const TValue *o = &f->k[i];
|
||||||
|
DumpByte(ttype(o), D);
|
||||||
|
switch (ttype(o)) {
|
||||||
|
case LUA_TNIL:
|
||||||
|
break;
|
||||||
|
case LUA_TBOOLEAN:
|
||||||
|
DumpByte(bvalue(o), D);
|
||||||
|
break;
|
||||||
|
case LUA_TNUMFLT:
|
||||||
|
DumpNumber(fltvalue(o), D);
|
||||||
|
break;
|
||||||
|
case LUA_TNUMINT:
|
||||||
|
DumpInteger(ivalue(o), D);
|
||||||
|
break;
|
||||||
|
case LUA_TSHRSTR:
|
||||||
|
case LUA_TLNGSTR:
|
||||||
|
DumpString(tsvalue(o), D);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
lua_assert(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpProtos (const Proto *f, DumpState *D) {
|
||||||
|
int i;
|
||||||
|
int n = f->sizep;
|
||||||
|
DumpInt(n, D);
|
||||||
|
for (i = 0; i < n; i++)
|
||||||
|
DumpFunction(f->p[i], f->source, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpUpvalues (const Proto *f, DumpState *D) {
|
||||||
|
int i, n = f->sizeupvalues;
|
||||||
|
DumpInt(n, D);
|
||||||
|
for (i = 0; i < n; i++) {
|
||||||
|
DumpByte(f->upvalues[i].instack, D);
|
||||||
|
DumpByte(f->upvalues[i].idx, D);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpDebug (const Proto *f, DumpState *D) {
|
||||||
|
int i, n;
|
||||||
|
n = (D->strip) ? 0 : f->sizelineinfo;
|
||||||
|
DumpInt(n, D);
|
||||||
|
DumpVector(f->lineinfo, n, D);
|
||||||
|
n = (D->strip) ? 0 : f->sizelocvars;
|
||||||
|
DumpInt(n, D);
|
||||||
|
for (i = 0; i < n; i++) {
|
||||||
|
DumpString(f->locvars[i].varname, D);
|
||||||
|
DumpInt(f->locvars[i].startpc, D);
|
||||||
|
DumpInt(f->locvars[i].endpc, D);
|
||||||
|
}
|
||||||
|
n = (D->strip) ? 0 : f->sizeupvalues;
|
||||||
|
DumpInt(n, D);
|
||||||
|
for (i = 0; i < n; i++)
|
||||||
|
DumpString(f->upvalues[i].name, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpFunction (const Proto *f, TString *psource, DumpState *D) {
|
||||||
|
if (D->strip || f->source == psource)
|
||||||
|
DumpString(NULL, D); /* no debug info or same source as its parent */
|
||||||
|
else
|
||||||
|
DumpString(f->source, D);
|
||||||
|
DumpInt(f->linedefined, D);
|
||||||
|
DumpInt(f->lastlinedefined, D);
|
||||||
|
DumpByte(f->numparams, D);
|
||||||
|
DumpByte(f->is_vararg, D);
|
||||||
|
DumpByte(f->maxstacksize, D);
|
||||||
|
DumpCode(f, D);
|
||||||
|
DumpConstants(f, D);
|
||||||
|
DumpUpvalues(f, D);
|
||||||
|
DumpProtos(f, D);
|
||||||
|
DumpDebug(f, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void DumpHeader (DumpState *D) {
|
||||||
|
DumpLiteral(LUA_SIGNATURE, D);
|
||||||
|
DumpByte(LUAC_VERSION, D);
|
||||||
|
DumpByte(LUAC_FORMAT, D);
|
||||||
|
DumpLiteral(LUAC_DATA, D);
|
||||||
|
DumpByte(sizeof(int), D);
|
||||||
|
DumpByte(sizeof(size_t), D);
|
||||||
|
DumpByte(sizeof(Instruction), D);
|
||||||
|
DumpByte(sizeof(lua_Integer), D);
|
||||||
|
DumpByte(sizeof(lua_Number), D);
|
||||||
|
DumpInteger(LUAC_INT, D);
|
||||||
|
DumpNumber(LUAC_NUM, D);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** dump Lua function as precompiled chunk
|
||||||
|
*/
|
||||||
|
int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data,
|
||||||
|
int strip) {
|
||||||
|
DumpState D;
|
||||||
|
D.L = L;
|
||||||
|
D.writer = w;
|
||||||
|
D.data = data;
|
||||||
|
D.strip = strip;
|
||||||
|
D.status = 0;
|
||||||
|
DumpHeader(&D);
|
||||||
|
DumpByte(f->sizeupvalues, &D);
|
||||||
|
DumpFunction(f, NULL, &D);
|
||||||
|
return D.status;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lfunc.c,v 2.45.1.1 2017/04/19 17:39:34 roberto Exp $
|
||||||
|
** Auxiliary functions to manipulate prototypes and closures
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lfunc_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lfunc.h"
|
||||||
|
#include "lgc.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
CClosure *luaF_newCclosure (lua_State *L, int n) {
|
||||||
|
GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n));
|
||||||
|
CClosure *c = gco2ccl(o);
|
||||||
|
c->nupvalues = cast_byte(n);
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LClosure *luaF_newLclosure (lua_State *L, int n) {
|
||||||
|
GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n));
|
||||||
|
LClosure *c = gco2lcl(o);
|
||||||
|
c->p = NULL;
|
||||||
|
c->nupvalues = cast_byte(n);
|
||||||
|
while (n--) c->upvals[n] = NULL;
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
** fill a closure with new closed upvalues
|
||||||
|
*/
|
||||||
|
void luaF_initupvals (lua_State *L, LClosure *cl) {
|
||||||
|
int i;
|
||||||
|
for (i = 0; i < cl->nupvalues; i++) {
|
||||||
|
UpVal *uv = luaM_new(L, UpVal);
|
||||||
|
uv->refcount = 1;
|
||||||
|
uv->v = &uv->u.value; /* make it closed */
|
||||||
|
setnilvalue(uv->v);
|
||||||
|
cl->upvals[i] = uv;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
UpVal *luaF_findupval (lua_State *L, StkId level) {
|
||||||
|
UpVal **pp = &L->openupval;
|
||||||
|
UpVal *p;
|
||||||
|
UpVal *uv;
|
||||||
|
lua_assert(isintwups(L) || L->openupval == NULL);
|
||||||
|
while (*pp != NULL && (p = *pp)->v >= level) {
|
||||||
|
lua_assert(upisopen(p));
|
||||||
|
if (p->v == level) /* found a corresponding upvalue? */
|
||||||
|
return p; /* return it */
|
||||||
|
pp = &p->u.open.next;
|
||||||
|
}
|
||||||
|
/* not found: create a new upvalue */
|
||||||
|
uv = luaM_new(L, UpVal);
|
||||||
|
uv->refcount = 0;
|
||||||
|
uv->u.open.next = *pp; /* link it to list of open upvalues */
|
||||||
|
uv->u.open.touched = 1;
|
||||||
|
*pp = uv;
|
||||||
|
uv->v = level; /* current value lives in the stack */
|
||||||
|
if (!isintwups(L)) { /* thread not in list of threads with upvalues? */
|
||||||
|
L->twups = G(L)->twups; /* link it to the list */
|
||||||
|
G(L)->twups = L;
|
||||||
|
}
|
||||||
|
return uv;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaF_close (lua_State *L, StkId level) {
|
||||||
|
UpVal *uv;
|
||||||
|
while (L->openupval != NULL && (uv = L->openupval)->v >= level) {
|
||||||
|
lua_assert(upisopen(uv));
|
||||||
|
L->openupval = uv->u.open.next; /* remove from 'open' list */
|
||||||
|
if (uv->refcount == 0) /* no references? */
|
||||||
|
luaM_free(L, uv); /* free upvalue */
|
||||||
|
else {
|
||||||
|
setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */
|
||||||
|
uv->v = &uv->u.value; /* now current value lives here */
|
||||||
|
luaC_upvalbarrier(L, uv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Proto *luaF_newproto (lua_State *L) {
|
||||||
|
GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto));
|
||||||
|
Proto *f = gco2p(o);
|
||||||
|
f->k = NULL;
|
||||||
|
f->sizek = 0;
|
||||||
|
f->p = NULL;
|
||||||
|
f->sizep = 0;
|
||||||
|
f->code = NULL;
|
||||||
|
f->cache = NULL;
|
||||||
|
f->sizecode = 0;
|
||||||
|
f->lineinfo = NULL;
|
||||||
|
f->sizelineinfo = 0;
|
||||||
|
f->upvalues = NULL;
|
||||||
|
f->sizeupvalues = 0;
|
||||||
|
f->numparams = 0;
|
||||||
|
f->is_vararg = 0;
|
||||||
|
f->maxstacksize = 0;
|
||||||
|
f->locvars = NULL;
|
||||||
|
f->sizelocvars = 0;
|
||||||
|
f->linedefined = 0;
|
||||||
|
f->lastlinedefined = 0;
|
||||||
|
f->source = NULL;
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaF_freeproto (lua_State *L, Proto *f) {
|
||||||
|
luaM_freearray(L, f->code, f->sizecode);
|
||||||
|
luaM_freearray(L, f->p, f->sizep);
|
||||||
|
luaM_freearray(L, f->k, f->sizek);
|
||||||
|
luaM_freearray(L, f->lineinfo, f->sizelineinfo);
|
||||||
|
luaM_freearray(L, f->locvars, f->sizelocvars);
|
||||||
|
luaM_freearray(L, f->upvalues, f->sizeupvalues);
|
||||||
|
luaM_free(L, f);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Look for n-th local variable at line 'line' in function 'func'.
|
||||||
|
** Returns NULL if not found.
|
||||||
|
*/
|
||||||
|
const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
|
||||||
|
int i;
|
||||||
|
for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
|
||||||
|
if (pc < f->locvars[i].endpc) { /* is variable active? */
|
||||||
|
local_number--;
|
||||||
|
if (local_number == 0)
|
||||||
|
return getstr(f->locvars[i].varname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NULL; /* not found */
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,70 @@
|
|||||||
|
/*
|
||||||
|
** $Id: linit.c,v 1.39.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Initialization of libraries for lua.c and other clients
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#define linit_c
|
||||||
|
#define LUA_LIB
|
||||||
|
|
||||||
|
/*
|
||||||
|
** If you embed Lua in your program and need to open the standard
|
||||||
|
** libraries, call luaL_openlibs in your program. If you need a
|
||||||
|
** different set of libraries, copy this file to your project and edit
|
||||||
|
** it to suit your needs.
|
||||||
|
**
|
||||||
|
** You can also *preload* libraries, so that a later 'require' can
|
||||||
|
** open the library, which is already linked to the application.
|
||||||
|
** For that, do the following code:
|
||||||
|
**
|
||||||
|
** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
|
||||||
|
** lua_pushcfunction(L, luaopen_modname);
|
||||||
|
** lua_setfield(L, -2, modname);
|
||||||
|
** lua_pop(L, 1); // remove PRELOAD table
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lualib.h"
|
||||||
|
#include "lauxlib.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** these libs are loaded by lua.c and are readily available to any Lua
|
||||||
|
** program
|
||||||
|
*/
|
||||||
|
static const luaL_Reg loadedlibs[] = {
|
||||||
|
{"_G", luaopen_base},
|
||||||
|
{LUA_LOADLIBNAME, luaopen_package},
|
||||||
|
{LUA_COLIBNAME, luaopen_coroutine},
|
||||||
|
{LUA_TABLIBNAME, luaopen_table},
|
||||||
|
{LUA_IOLIBNAME, luaopen_io},
|
||||||
|
{LUA_OSLIBNAME, luaopen_os},
|
||||||
|
{LUA_STRLIBNAME, luaopen_string},
|
||||||
|
{LUA_MATHLIBNAME, luaopen_math},
|
||||||
|
// {LUA_UTF8LIBNAME, luaopen_utf8},
|
||||||
|
{LUA_DBLIBNAME, luaopen_debug},
|
||||||
|
#if defined(LUA_COMPAT_BITLIB)
|
||||||
|
{LUA_BITLIBNAME, luaopen_bit32},
|
||||||
|
#endif
|
||||||
|
{NULL, NULL}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
LUALIB_API void luaL_openlibs (lua_State *L) {
|
||||||
|
const luaL_Reg *lib;
|
||||||
|
/* "require" functions from 'loadedlibs' and set results to global table */
|
||||||
|
for (lib = loadedlibs; lib->func; lib++) {
|
||||||
|
luaL_requiref(L, lib->name, lib->func, 1);
|
||||||
|
lua_pop(L, 1); /* remove lib */
|
||||||
|
//extern void print_list_mem(const char* name);
|
||||||
|
//print_list_mem(lib->name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,568 @@
|
|||||||
|
/*
|
||||||
|
** $Id: llex.c,v 2.96.1.1 2017/04/19 17:20:42 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** reads a sequence '[=*[' or ']=*]', leaving the last bracket.
|
||||||
|
** If sequence is well formed, return its number of '='s + 2; otherwise,
|
||||||
|
** return 1 if there is no '='s or 0 otherwise (an unfinished '[==...').
|
||||||
|
*/
|
||||||
|
static size_t skip_sep (LexState *ls) {
|
||||||
|
size_t 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 + 2
|
||||||
|
: (count == 0) ? 1
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void read_long_string (LexState *ls, SemInfo *seminfo, size_t 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) + sep,
|
||||||
|
luaZ_bufflen(ls->buff) - 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? */
|
||||||
|
size_t sep = skip_sep(ls);
|
||||||
|
luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */
|
||||||
|
if (sep >= 2) {
|
||||||
|
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 '[' */
|
||||||
|
size_t sep = skip_sep(ls);
|
||||||
|
if (sep >= 2) {
|
||||||
|
read_long_string(ls, seminfo, sep);
|
||||||
|
return TK_STRING;
|
||||||
|
}
|
||||||
|
else if (sep == 0) /* '[=...' 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;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lmathlib.c,v 1.119.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Standard mathematical library
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lmathlib_c
|
||||||
|
#define LUA_LIB
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <math.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lauxlib.h"
|
||||||
|
#include "lualib.h"
|
||||||
|
|
||||||
|
|
||||||
|
#undef PI
|
||||||
|
#define PI (l_mathop(3.141592653589793238462643383279502884))
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(l_rand) /* { */
|
||||||
|
#if defined(LUA_USE_POSIX)
|
||||||
|
#define l_rand() random()
|
||||||
|
#define l_srand(x) srandom(x)
|
||||||
|
#define L_RANDMAX 2147483647 /* (2^31 - 1), following POSIX */
|
||||||
|
#else
|
||||||
|
#define l_rand() rand()
|
||||||
|
#define l_srand(x) srand(x)
|
||||||
|
#define L_RANDMAX RAND_MAX
|
||||||
|
#endif
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
static int math_abs (lua_State *L) {
|
||||||
|
if (lua_isinteger(L, 1)) {
|
||||||
|
lua_Integer n = lua_tointeger(L, 1);
|
||||||
|
if (n < 0) n = (lua_Integer)(0u - (lua_Unsigned)n);
|
||||||
|
lua_pushinteger(L, n);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_sin (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(sin)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_cos (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_tan (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_asin (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_acos (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(acos)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_atan (lua_State *L) {
|
||||||
|
lua_Number y = luaL_checknumber(L, 1);
|
||||||
|
lua_Number x = luaL_optnumber(L, 2, 1);
|
||||||
|
lua_pushnumber(L, l_mathop(atan2)(y, x));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_toint (lua_State *L) {
|
||||||
|
int valid;
|
||||||
|
lua_Integer n = lua_tointegerx(L, 1, &valid);
|
||||||
|
if (valid)
|
||||||
|
lua_pushinteger(L, n);
|
||||||
|
else {
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
lua_pushnil(L); /* value is not convertible to integer */
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void pushnumint (lua_State *L, lua_Number d) {
|
||||||
|
lua_Integer n;
|
||||||
|
if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */
|
||||||
|
lua_pushinteger(L, n); /* result is integer */
|
||||||
|
else
|
||||||
|
lua_pushnumber(L, d); /* result is float */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_floor (lua_State *L) {
|
||||||
|
if (lua_isinteger(L, 1))
|
||||||
|
lua_settop(L, 1); /* integer is its own floor */
|
||||||
|
else {
|
||||||
|
lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
|
||||||
|
pushnumint(L, d);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_ceil (lua_State *L) {
|
||||||
|
if (lua_isinteger(L, 1))
|
||||||
|
lua_settop(L, 1); /* integer is its own ceil */
|
||||||
|
else {
|
||||||
|
lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));
|
||||||
|
pushnumint(L, d);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_fmod (lua_State *L) {
|
||||||
|
if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
|
||||||
|
lua_Integer d = lua_tointeger(L, 2);
|
||||||
|
if ((lua_Unsigned)d + 1u <= 1u) { /* special cases: -1 or 0 */
|
||||||
|
luaL_argcheck(L, d != 0, 2, "zero");
|
||||||
|
lua_pushinteger(L, 0); /* avoid overflow with 0x80000... / -1 */
|
||||||
|
}
|
||||||
|
else
|
||||||
|
lua_pushinteger(L, lua_tointeger(L, 1) % d);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
|
||||||
|
luaL_checknumber(L, 2)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** next function does not use 'modf', avoiding problems with 'double*'
|
||||||
|
** (which is not compatible with 'float*') when lua_Number is not
|
||||||
|
** 'double'.
|
||||||
|
*/
|
||||||
|
static int math_modf (lua_State *L) {
|
||||||
|
if (lua_isinteger(L ,1)) {
|
||||||
|
lua_settop(L, 1); /* number is its own integer part */
|
||||||
|
lua_pushnumber(L, 0); /* no fractional part */
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_Number n = luaL_checknumber(L, 1);
|
||||||
|
/* integer part (rounds toward zero) */
|
||||||
|
lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
|
||||||
|
pushnumint(L, ip);
|
||||||
|
/* fractional part (test needed for inf/-inf) */
|
||||||
|
lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
|
||||||
|
}
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_sqrt (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_ult (lua_State *L) {
|
||||||
|
lua_Integer a = luaL_checkinteger(L, 1);
|
||||||
|
lua_Integer b = luaL_checkinteger(L, 2);
|
||||||
|
lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_log (lua_State *L) {
|
||||||
|
lua_Number x = luaL_checknumber(L, 1);
|
||||||
|
lua_Number res;
|
||||||
|
if (lua_isnoneornil(L, 2))
|
||||||
|
res = l_mathop(log)(x);
|
||||||
|
else {
|
||||||
|
lua_Number base = luaL_checknumber(L, 2);
|
||||||
|
#if !defined(LUA_USE_C89)
|
||||||
|
if (base == l_mathop(2.0))
|
||||||
|
res = l_mathop(log2)(x); else
|
||||||
|
#endif
|
||||||
|
if (base == l_mathop(10.0))
|
||||||
|
res = l_mathop(log10)(x);
|
||||||
|
else
|
||||||
|
res = l_mathop(log)(x)/l_mathop(log)(base);
|
||||||
|
}
|
||||||
|
lua_pushnumber(L, res);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_exp (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_deg (lua_State *L) {
|
||||||
|
lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_rad (lua_State *L) {
|
||||||
|
lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_min (lua_State *L) {
|
||||||
|
int n = lua_gettop(L); /* number of arguments */
|
||||||
|
int imin = 1; /* index of current minimum value */
|
||||||
|
int i;
|
||||||
|
luaL_argcheck(L, n >= 1, 1, "value expected");
|
||||||
|
for (i = 2; i <= n; i++) {
|
||||||
|
if (lua_compare(L, i, imin, LUA_OPLT))
|
||||||
|
imin = i;
|
||||||
|
}
|
||||||
|
lua_pushvalue(L, imin);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_max (lua_State *L) {
|
||||||
|
int n = lua_gettop(L); /* number of arguments */
|
||||||
|
int imax = 1; /* index of current maximum value */
|
||||||
|
int i;
|
||||||
|
luaL_argcheck(L, n >= 1, 1, "value expected");
|
||||||
|
for (i = 2; i <= n; i++) {
|
||||||
|
if (lua_compare(L, imax, i, LUA_OPLT))
|
||||||
|
imax = i;
|
||||||
|
}
|
||||||
|
lua_pushvalue(L, imax);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
** This function uses 'double' (instead of 'lua_Number') to ensure that
|
||||||
|
** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0'
|
||||||
|
** will keep full precision (ensuring that 'r' is always less than 1.0.)
|
||||||
|
*/
|
||||||
|
static int math_random (lua_State *L) {
|
||||||
|
lua_Integer low, up;
|
||||||
|
#ifdef LUAT_USE_CRYPTO
|
||||||
|
extern int luat_crypto_trng(char* buff, size_t len);
|
||||||
|
luat_crypto_trng((char*)&low, sizeof(lua_Integer));
|
||||||
|
double r = (double)(low & RAND_MAX) * (1.0 / ((double)L_RANDMAX + 1.0));
|
||||||
|
#else
|
||||||
|
double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0));
|
||||||
|
#endif
|
||||||
|
switch (lua_gettop(L)) { /* check number of arguments */
|
||||||
|
case 0: { /* no arguments */
|
||||||
|
lua_pushnumber(L, (lua_Number)r); /* Number between 0 and 1 */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
case 1: { /* only upper limit */
|
||||||
|
low = 1;
|
||||||
|
up = luaL_checkinteger(L, 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 2: { /* lower and upper limits */
|
||||||
|
low = luaL_checkinteger(L, 1);
|
||||||
|
up = luaL_checkinteger(L, 2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: return luaL_error(L, "wrong number of arguments");
|
||||||
|
}
|
||||||
|
/* random integer in the interval [low, up] */
|
||||||
|
luaL_argcheck(L, low <= up, 1, "interval is empty");
|
||||||
|
luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
|
||||||
|
"interval too large");
|
||||||
|
r *= (double)(up - low) + 1.0;
|
||||||
|
lua_pushinteger(L, (lua_Integer)r + low);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_randomseed (lua_State *L) {
|
||||||
|
#ifdef LUAT_USE_CRYPTO
|
||||||
|
#else
|
||||||
|
l_srand((unsigned int)(lua_Integer)luaL_checknumber(L, 1));
|
||||||
|
(void)l_rand(); /* discard first value to avoid undesirable correlations */
|
||||||
|
#endif
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int math_type (lua_State *L) {
|
||||||
|
if (lua_type(L, 1) == LUA_TNUMBER) {
|
||||||
|
if (lua_isinteger(L, 1))
|
||||||
|
lua_pushliteral(L, "integer");
|
||||||
|
else
|
||||||
|
lua_pushliteral(L, "float");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
luaL_checkany(L, 1);
|
||||||
|
lua_pushnil(L);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Deprecated functions (for compatibility only)
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
#if defined(LUA_COMPAT_MATHLIB)
|
||||||
|
|
||||||
|
static int math_cosh (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_sinh (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_tanh (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_pow (lua_State *L) {
|
||||||
|
lua_Number x = luaL_checknumber(L, 1);
|
||||||
|
lua_Number y = luaL_checknumber(L, 2);
|
||||||
|
lua_pushnumber(L, l_mathop(pow)(x, y));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_frexp (lua_State *L) {
|
||||||
|
int e;
|
||||||
|
lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
|
||||||
|
lua_pushinteger(L, e);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_ldexp (lua_State *L) {
|
||||||
|
lua_Number x = luaL_checknumber(L, 1);
|
||||||
|
int ep = (int)luaL_checkinteger(L, 2);
|
||||||
|
lua_pushnumber(L, l_mathop(ldexp)(x, ep));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int math_log10 (lua_State *L) {
|
||||||
|
lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
#include "rotable2.h"
|
||||||
|
static const rotable_Reg_t mathlib[] = {
|
||||||
|
{"abs", ROREG_FUNC(math_abs)},
|
||||||
|
{"acos", ROREG_FUNC(math_acos)},
|
||||||
|
{"asin", ROREG_FUNC(math_asin)},
|
||||||
|
{"atan", ROREG_FUNC( math_atan)},
|
||||||
|
{"ceil", ROREG_FUNC(math_ceil)},
|
||||||
|
{"cos", ROREG_FUNC(math_cos)},
|
||||||
|
{"deg", ROREG_FUNC(math_deg)},
|
||||||
|
{"exp", ROREG_FUNC(math_exp)},
|
||||||
|
{"tointeger", ROREG_FUNC(math_toint)},
|
||||||
|
{"floor", ROREG_FUNC(math_floor)},
|
||||||
|
{"fmod", ROREG_FUNC(math_fmod)},
|
||||||
|
{"ult", ROREG_FUNC(math_ult)},
|
||||||
|
{"log", ROREG_FUNC(math_log)},
|
||||||
|
{"max", ROREG_FUNC(math_max)},
|
||||||
|
{"min", ROREG_FUNC(math_min)},
|
||||||
|
{"modf", ROREG_FUNC(math_modf)},
|
||||||
|
{"rad", ROREG_FUNC(math_rad)},
|
||||||
|
{"random", ROREG_FUNC(math_random)},
|
||||||
|
{"randomseed", ROREG_FUNC(math_randomseed)},
|
||||||
|
{"sin", ROREG_FUNC(math_sin)},
|
||||||
|
{"sqrt", ROREG_FUNC(math_sqrt)},
|
||||||
|
{"tan", ROREG_FUNC(math_tan)},
|
||||||
|
{"type", ROREG_FUNC(math_type)},
|
||||||
|
#if defined(LUA_COMPAT_MATHLIB)
|
||||||
|
{"atan2", ROREG_FUNC(math_atan)},
|
||||||
|
{"cosh", ROREG_FUNC(math_cosh)},
|
||||||
|
{"sinh", ROREG_FUNC(math_sinh)},
|
||||||
|
{"tanh", ROREG_FUNC(math_tanh)},
|
||||||
|
{"pow", ROREG_FUNC(math_pow)},
|
||||||
|
{"frexp", ROREG_FUNC(math_frexp)},
|
||||||
|
{"ldexp", ROREG_FUNC(math_ldexp)},
|
||||||
|
{"log10", ROREG_FUNC(math_log10)},
|
||||||
|
#endif
|
||||||
|
/* placeholders */
|
||||||
|
{"pi", ROREG_NUM(PI)},
|
||||||
|
{"huge", ROREG_NUM(HUGE_VAL)},
|
||||||
|
{"maxinteger", ROREG_INT(LUA_MAXINTEGER)},
|
||||||
|
{"mininteger", ROREG_INT(LUA_MININTEGER)},
|
||||||
|
{NULL, ROREG_INT(0) }
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Open math library
|
||||||
|
*/
|
||||||
|
LUAMOD_API int luaopen_math (lua_State *L) {
|
||||||
|
luat_newlib2(L, mathlib);
|
||||||
|
// lua_pushnumber(L, PI);
|
||||||
|
// lua_setfield(L, -2, "pi");
|
||||||
|
// lua_pushnumber(L, (lua_Number)HUGE_VAL);
|
||||||
|
// lua_setfield(L, -2, "huge");
|
||||||
|
// lua_pushinteger(L, LUA_MAXINTEGER);
|
||||||
|
// lua_setfield(L, -2, "maxinteger");
|
||||||
|
// lua_pushinteger(L, LUA_MININTEGER);
|
||||||
|
// lua_setfield(L, -2, "mininteger");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lmem.c,v 1.91.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Interface to Memory Manager
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lmem_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lgc.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
|
||||||
|
#include "luat_mem.h"
|
||||||
|
|
||||||
|
/*
|
||||||
|
** About the realloc function:
|
||||||
|
** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
|
||||||
|
** ('osize' is the old size, 'nsize' is the new size)
|
||||||
|
**
|
||||||
|
** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no
|
||||||
|
** matter 'x').
|
||||||
|
**
|
||||||
|
** * frealloc(ud, p, x, 0) frees the block 'p'
|
||||||
|
** (in this specific case, frealloc must return NULL);
|
||||||
|
** particularly, frealloc(ud, NULL, 0, 0) does nothing
|
||||||
|
** (which is equivalent to free(NULL) in ISO C)
|
||||||
|
**
|
||||||
|
** frealloc returns NULL if it cannot create or reallocate the area
|
||||||
|
** (any reallocation to an equal or smaller size cannot fail!)
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define MINSIZEARRAY 4
|
||||||
|
|
||||||
|
|
||||||
|
void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
|
||||||
|
int limit, const char *what) {
|
||||||
|
void *newblock;
|
||||||
|
int newsize;
|
||||||
|
if (*size >= limit/2) { /* cannot double it? */
|
||||||
|
if (*size >= limit) /* cannot grow even a little? */
|
||||||
|
luaG_runerror(L, "too many %s (limit is %d)", what, limit);
|
||||||
|
newsize = limit; /* still have at least one free place */
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
newsize = (*size)*2;
|
||||||
|
if (newsize < MINSIZEARRAY)
|
||||||
|
newsize = MINSIZEARRAY; /* minimum size */
|
||||||
|
}
|
||||||
|
newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
|
||||||
|
*size = newsize; /* update only when everything else is OK */
|
||||||
|
return newblock;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#include "bget.h"
|
||||||
|
#include "luat_base.h"
|
||||||
|
|
||||||
|
#define LUAT_LOG_TAG "mem"
|
||||||
|
#include "luat_log.h"
|
||||||
|
|
||||||
|
|
||||||
|
l_noret luaM_toobig (lua_State *L, size_t n, size_t e, const char *what) {
|
||||||
|
LLOGE("memory allocation error: block too big %s n=%lu e=%lu",
|
||||||
|
what, (unsigned long)n, (unsigned long)e);
|
||||||
|
luaG_runerror(L, "memory allocation error: block too big (%s)", what);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** generic allocation routine.
|
||||||
|
*/
|
||||||
|
void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
|
||||||
|
void *newblock;
|
||||||
|
global_State *g = G(L);
|
||||||
|
size_t realosize = (block) ? osize : 0;
|
||||||
|
lua_assert((realosize == 0) == (block == NULL));
|
||||||
|
#if defined(HARDMEMTESTS)
|
||||||
|
if (nsize > realosize && g->gcrunning) {
|
||||||
|
bufsize curalloc;
|
||||||
|
bufsize totfree;
|
||||||
|
bufsize maxfree;
|
||||||
|
unsigned long nget;
|
||||||
|
unsigned long nrel;
|
||||||
|
bstats(&curalloc, &totfree, &maxfree, &nget, &nrel);
|
||||||
|
if (totfree < nsize)
|
||||||
|
luaC_fullgc(L, 1); /* force a GC whenever possible */
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
newblock = (*g->frealloc)(g->ud, block, osize, nsize);
|
||||||
|
if (newblock == NULL && nsize > 0) {
|
||||||
|
lua_assert(nsize > realosize); /* cannot fail when shrinking a block */
|
||||||
|
if (g->version) { /* is state fully built? */
|
||||||
|
luaC_fullgc(L, 1); /* try to free some memory... */
|
||||||
|
newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
|
||||||
|
}
|
||||||
|
if (newblock == NULL) {
|
||||||
|
size_t total = 0;
|
||||||
|
size_t used = 0;
|
||||||
|
size_t max_used = 0;
|
||||||
|
luat_meminfo_luavm(&total, &used, &max_used);
|
||||||
|
LLOGE("memory allocation failed total %d, used %d, alloc %d", total, used, nsize);
|
||||||
|
luaD_throw(L, LUA_ERRMEM); /* rethrow memory error */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lua_assert((nsize == 0) == (newblock == NULL));
|
||||||
|
g->GCdebt = (g->GCdebt + nsize) - realosize;
|
||||||
|
return newblock;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
/*
|
||||||
|
** $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"
|
||||||
|
|
||||||
|
#include "luat_fs.h"
|
||||||
|
#undef fopen
|
||||||
|
#undef fclose
|
||||||
|
#define fopen luat_fs_fopen
|
||||||
|
#define fclose luat_fs_fclose
|
||||||
|
|
||||||
|
#define LUAT_LOG_TAG "loadlib"
|
||||||
|
#include "luat_log.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
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define LIB_FAIL "open"
|
||||||
|
|
||||||
|
|
||||||
|
#define setprogdir(L) ((void)0)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** 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 */
|
||||||
|
|
||||||
|
/* error codes for 'lookforfunc' */
|
||||||
|
#define ERRLIB 1
|
||||||
|
#define ERRFUNC 2
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** 'require' function
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef LUAT_MODULE_SEARCH_PATH
|
||||||
|
#define LUAT_MODULE_SEARCH_PATH "/%s.luac", "/%s.lua", \
|
||||||
|
"/luadb/%s.luac", "/luadb/%s.lua",\
|
||||||
|
"/lua/%s.luac", "/lua/%s.lua",\
|
||||||
|
"",
|
||||||
|
#endif
|
||||||
|
static const char* search_paths[] = {
|
||||||
|
LUAT_MODULE_SEARCH_PATH
|
||||||
|
};
|
||||||
|
|
||||||
|
char custom_search_paths[4][24] = {0};
|
||||||
|
|
||||||
|
int luat_search_module(const char* name, char* filename) {
|
||||||
|
int index = 0;
|
||||||
|
for (size_t i = 0; i < 4; i++)
|
||||||
|
{
|
||||||
|
if (strlen(custom_search_paths[i]) == 0)
|
||||||
|
continue;
|
||||||
|
snprintf(filename, 64, custom_search_paths[i], name);
|
||||||
|
if (luat_fs_fexist(filename)) return 0;
|
||||||
|
filename[0] = 0x00;
|
||||||
|
}
|
||||||
|
while (1) {
|
||||||
|
if (strlen(search_paths[index]) == 0)
|
||||||
|
break;
|
||||||
|
snprintf(filename, 64, search_paths[index], name);
|
||||||
|
if (luat_fs_fexist(filename)) return 0;
|
||||||
|
index ++;
|
||||||
|
filename[0] = 0x00;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int searcher_Lua (lua_State *L) {
|
||||||
|
char filename[64] = {0};
|
||||||
|
size_t len = 0;
|
||||||
|
const char *name = luaL_checklstring(L, 1, &len);
|
||||||
|
if (len < 1 || len > 48) {
|
||||||
|
lua_pushfstring(L, "module name '%s' len %d is invalid", name, len);
|
||||||
|
return lua_error(L);
|
||||||
|
}
|
||||||
|
int re = luat_search_module(name, filename);
|
||||||
|
if (re == 0)
|
||||||
|
re = checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
|
||||||
|
return re;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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 */
|
||||||
|
|
||||||
|
// add by wendal, 替换原有的逻辑
|
||||||
|
lua_pushstring(L, name);
|
||||||
|
//luat_os_print_heapinfo("go-loadfile");
|
||||||
|
// LLOGD("module %s , searching......",name);
|
||||||
|
if (searcher_Lua(L) == 2) {
|
||||||
|
//luat_os_print_heapinfo("go-call");
|
||||||
|
//LLOGD("module %s , found OK!!!",name);
|
||||||
|
lua_gc(L, LUA_GCCOLLECT, 0);
|
||||||
|
lua_pushstring(L, name);
|
||||||
|
lua_call(L, 2, 1);
|
||||||
|
//luat_os_print_heapinfo("after-call");
|
||||||
|
lua_gc(L, LUA_GCCOLLECT, 0);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
luaL_error(L, "module '%s' not found", name);
|
||||||
|
}
|
||||||
|
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 int ll_unload(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_pushnil(L);
|
||||||
|
lua_setfield(L, -2, name);
|
||||||
|
lua_settop(L, 0);
|
||||||
|
lua_gc(L, LUA_GCCOLLECT, 0);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_package (lua_State *L) {
|
||||||
|
#ifndef LUAT_MEMORY_OPT_G_FUNCS
|
||||||
|
lua_pushcfunction(L, ll_require);
|
||||||
|
lua_setglobal(L, "require");
|
||||||
|
lua_pushcfunction(L, ll_unload);
|
||||||
|
lua_setglobal(L, "unload");
|
||||||
|
#endif
|
||||||
|
#if defined(LUA_COMPAT_MODULE)
|
||||||
|
// 兼容LuatOS-Air
|
||||||
|
lua_pushcfunction(L, ll_module);
|
||||||
|
lua_setglobal(L, "module");
|
||||||
|
lua_newtable(L);
|
||||||
|
lua_pushcfunction(L, ll_seeall);
|
||||||
|
lua_setfield(L, -2, "seeall");
|
||||||
|
#else
|
||||||
|
lua_pushnil(L);
|
||||||
|
#endif
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if 0
|
||||||
|
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 */
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,591 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lobject.c,v 2.113.1.1 2017/04/19 17:29:57 roberto Exp $
|
||||||
|
** Some generic functions over Lua objects
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lobject_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
#include "stdint.h"
|
||||||
|
#include <locale.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include <stdarg.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lctype.h"
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
#include "lvm.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** converts an integer to a "floating point byte", represented as
|
||||||
|
** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
|
||||||
|
** eeeee != 0 and (xxx) otherwise.
|
||||||
|
*/
|
||||||
|
int luaO_int2fb (unsigned int x) {
|
||||||
|
int e = 0; /* exponent */
|
||||||
|
if (x < 8) return x;
|
||||||
|
while (x >= (8 << 4)) { /* coarse steps */
|
||||||
|
x = (x + 0xf) >> 4; /* x = ceil(x / 16) */
|
||||||
|
e += 4;
|
||||||
|
}
|
||||||
|
while (x >= (8 << 1)) { /* fine steps */
|
||||||
|
x = (x + 1) >> 1; /* x = ceil(x / 2) */
|
||||||
|
e++;
|
||||||
|
}
|
||||||
|
return ((e+1) << 3) | (cast_int(x) - 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* converts back */
|
||||||
|
int luaO_fb2int (int x) {
|
||||||
|
return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Computes ceil(log2(x))
|
||||||
|
*/
|
||||||
|
int luaO_ceillog2 (unsigned int x) {
|
||||||
|
static const lu_byte log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */
|
||||||
|
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,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,
|
||||||
|
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
||||||
|
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
|
||||||
|
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
|
||||||
|
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
|
||||||
|
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
|
||||||
|
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
|
||||||
|
};
|
||||||
|
int l = 0;
|
||||||
|
x--;
|
||||||
|
while (x >= 256) { l += 8; x >>= 8; }
|
||||||
|
return l + log_2[x];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
|
||||||
|
lua_Integer v2) {
|
||||||
|
switch (op) {
|
||||||
|
case LUA_OPADD: return intop(+, v1, v2);
|
||||||
|
case LUA_OPSUB:return intop(-, v1, v2);
|
||||||
|
case LUA_OPMUL:return intop(*, v1, v2);
|
||||||
|
case LUA_OPMOD: return luaV_mod(L, v1, v2);
|
||||||
|
case LUA_OPIDIV: return luaV_div(L, v1, v2);
|
||||||
|
case LUA_OPBAND: return intop(&, v1, v2);
|
||||||
|
case LUA_OPBOR: return intop(|, v1, v2);
|
||||||
|
case LUA_OPBXOR: return intop(^, v1, v2);
|
||||||
|
case LUA_OPSHL: return luaV_shiftl(v1, v2);
|
||||||
|
case LUA_OPSHR: return luaV_shiftl(v1, -v2);
|
||||||
|
case LUA_OPUNM: return intop(-, 0, v1);
|
||||||
|
case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
|
||||||
|
default: lua_assert(0); return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static lua_Number numarith (lua_State *L, int op, lua_Number v1,
|
||||||
|
lua_Number v2) {
|
||||||
|
switch (op) {
|
||||||
|
case LUA_OPADD: return luai_numadd(L, v1, v2);
|
||||||
|
case LUA_OPSUB: return luai_numsub(L, v1, v2);
|
||||||
|
case LUA_OPMUL: return luai_nummul(L, v1, v2);
|
||||||
|
case LUA_OPDIV: return luai_numdiv(L, v1, v2);
|
||||||
|
case LUA_OPPOW: return luai_numpow(L, v1, v2);
|
||||||
|
case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
|
||||||
|
case LUA_OPUNM: return luai_numunm(L, v1);
|
||||||
|
case LUA_OPMOD: {
|
||||||
|
lua_Number m;
|
||||||
|
luai_nummod(L, v1, v2, m);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
default: lua_assert(0); return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
|
||||||
|
TValue *res) {
|
||||||
|
switch (op) {
|
||||||
|
case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
|
||||||
|
case LUA_OPSHL: case LUA_OPSHR:
|
||||||
|
case LUA_OPBNOT: { /* operate only on integers */
|
||||||
|
lua_Integer i1; lua_Integer i2;
|
||||||
|
if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
|
||||||
|
setivalue(res, intarith(L, op, i1, i2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else break; /* go to the end */
|
||||||
|
}
|
||||||
|
case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */
|
||||||
|
lua_Number n1; lua_Number n2;
|
||||||
|
if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
|
||||||
|
setfltvalue(res, numarith(L, op, n1, n2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else break; /* go to the end */
|
||||||
|
}
|
||||||
|
default: { /* other operations */
|
||||||
|
lua_Number n1; lua_Number n2;
|
||||||
|
if (ttisinteger(p1) && ttisinteger(p2)) {
|
||||||
|
setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
|
||||||
|
setfltvalue(res, numarith(L, op, n1, n2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
else break; /* go to the end */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* could not perform raw operation; try metamethod */
|
||||||
|
lua_assert(L != NULL); /* should not fail when folding (compile time) */
|
||||||
|
luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaO_hexavalue (int c) {
|
||||||
|
if (lisdigit(c)) return c - '0';
|
||||||
|
else return (ltolower(c) - 'a') + 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int isneg (const char **s) {
|
||||||
|
if (**s == '-') { (*s)++; return 1; }
|
||||||
|
else if (**s == '+') (*s)++;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Lua's implementation for 'lua_strx2number'
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
#if !defined(lua_strx2number)
|
||||||
|
|
||||||
|
/* maximum number of significant digits to read (to avoid overflows
|
||||||
|
even with single floats) */
|
||||||
|
#define MAXSIGDIG 30
|
||||||
|
|
||||||
|
/*
|
||||||
|
** convert an hexadecimal numeric string to a number, following
|
||||||
|
** C99 specification for 'strtod'
|
||||||
|
*/
|
||||||
|
static lua_Number lua_strx2number (const char *s, char **endptr) {
|
||||||
|
int dot = lua_getlocaledecpoint();
|
||||||
|
lua_Number r = 0.0; /* result (accumulator) */
|
||||||
|
int sigdig = 0; /* number of significant digits */
|
||||||
|
int nosigdig = 0; /* number of non-significant digits */
|
||||||
|
int e = 0; /* exponent correction */
|
||||||
|
int neg; /* 1 if number is negative */
|
||||||
|
int hasdot = 0; /* true after seen a dot */
|
||||||
|
*endptr = cast(char *, s); /* nothing is valid yet */
|
||||||
|
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
|
||||||
|
neg = isneg(&s); /* check signal */
|
||||||
|
if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
|
||||||
|
return 0.0; /* invalid format (no '0x') */
|
||||||
|
for (s += 2; ; s++) { /* skip '0x' and read numeral */
|
||||||
|
if (*s == dot) {
|
||||||
|
if (hasdot) break; /* second dot? stop loop */
|
||||||
|
else hasdot = 1;
|
||||||
|
}
|
||||||
|
else if (lisxdigit(cast_uchar(*s))) {
|
||||||
|
if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
|
||||||
|
nosigdig++;
|
||||||
|
else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
|
||||||
|
r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
|
||||||
|
else e++; /* too many digits; ignore, but still count for exponent */
|
||||||
|
if (hasdot) e--; /* decimal digit? correct exponent */
|
||||||
|
}
|
||||||
|
else break; /* neither a dot nor a digit */
|
||||||
|
}
|
||||||
|
if (nosigdig + sigdig == 0) /* no digits? */
|
||||||
|
return 0.0; /* invalid format */
|
||||||
|
*endptr = cast(char *, s); /* valid up to here */
|
||||||
|
e *= 4; /* each digit multiplies/divides value by 2^4 */
|
||||||
|
if (*s == 'p' || *s == 'P') { /* exponent part? */
|
||||||
|
int exp1 = 0; /* exponent value */
|
||||||
|
int neg1; /* exponent signal */
|
||||||
|
s++; /* skip 'p' */
|
||||||
|
neg1 = isneg(&s); /* signal */
|
||||||
|
if (!lisdigit(cast_uchar(*s)))
|
||||||
|
return 0.0; /* invalid; must have at least one digit */
|
||||||
|
while (lisdigit(cast_uchar(*s))) /* read exponent */
|
||||||
|
exp1 = exp1 * 10 + *(s++) - '0';
|
||||||
|
if (neg1) exp1 = -exp1;
|
||||||
|
e += exp1;
|
||||||
|
*endptr = cast(char *, s); /* valid up to here */
|
||||||
|
}
|
||||||
|
if (neg) r = -r;
|
||||||
|
return l_mathop(ldexp)(r, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/* maximum length of a numeral */
|
||||||
|
#if !defined (L_MAXLENNUM)
|
||||||
|
#define L_MAXLENNUM 200
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
|
||||||
|
char *endptr;
|
||||||
|
*result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
|
||||||
|
: lua_str2number(s, &endptr);
|
||||||
|
if (endptr == s) return NULL; /* nothing recognized? */
|
||||||
|
while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
|
||||||
|
return (*endptr == '\0') ? endptr : NULL; /* OK if no trailing characters */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Convert string 's' to a Lua number (put in 'result'). Return NULL
|
||||||
|
** on fail or the address of the ending '\0' on success.
|
||||||
|
** 'pmode' points to (and 'mode' contains) special things in the string:
|
||||||
|
** - 'x'/'X' means an hexadecimal numeral
|
||||||
|
** - 'n'/'N' means 'inf' or 'nan' (which should be rejected)
|
||||||
|
** - '.' just optimizes the search for the common case (nothing special)
|
||||||
|
** This function accepts both the current locale or a dot as the radix
|
||||||
|
** mark. If the convertion fails, it may mean number has a dot but
|
||||||
|
** locale accepts something else. In that case, the code copies 's'
|
||||||
|
** to a buffer (because 's' is read-only), changes the dot to the
|
||||||
|
** current locale radix mark, and tries to convert again.
|
||||||
|
*/
|
||||||
|
static const char *l_str2d (const char *s, lua_Number *result) {
|
||||||
|
const char *endptr;
|
||||||
|
const char *pmode = strpbrk(s, ".xXnN");
|
||||||
|
int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
|
||||||
|
if (mode == 'n') /* reject 'inf' and 'nan' */
|
||||||
|
return NULL;
|
||||||
|
endptr = l_str2dloc(s, result, mode); /* try to convert */
|
||||||
|
if (endptr == NULL) { /* failed? may be a different locale */
|
||||||
|
char buff[L_MAXLENNUM + 1];
|
||||||
|
const char *pdot = strchr(s, '.');
|
||||||
|
if (strlen(s) > L_MAXLENNUM || pdot == NULL)
|
||||||
|
return NULL; /* string too long or no dot; fail */
|
||||||
|
strcpy(buff, s); /* copy string to buffer */
|
||||||
|
buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
|
||||||
|
endptr = l_str2dloc(buff, result, mode); /* try again */
|
||||||
|
if (endptr != NULL)
|
||||||
|
endptr = s + (endptr - buff); /* make relative to 's' */
|
||||||
|
}
|
||||||
|
return endptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef __USER_CODE__
|
||||||
|
#define MAXBY10 cast(lua_Unsigned, 0xffffffff / 10)
|
||||||
|
#define MAXLASTD cast_int(0xffffffff % 10)
|
||||||
|
#else
|
||||||
|
#define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10)
|
||||||
|
#define MAXLASTD cast_int(LUA_MAXINTEGER % 10)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static const char *l_str2int (const char *s, lua_Integer *result) {
|
||||||
|
lua_Unsigned a = 0;
|
||||||
|
int empty = 1;
|
||||||
|
int neg;
|
||||||
|
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
|
||||||
|
neg = isneg(&s);
|
||||||
|
if (s[0] == '0' &&
|
||||||
|
(s[1] == 'x' || s[1] == 'X')) { /* hex? */
|
||||||
|
s += 2; /* skip '0x' */
|
||||||
|
for (; lisxdigit(cast_uchar(*s)); s++) {
|
||||||
|
a = a * 16 + luaO_hexavalue(*s);
|
||||||
|
empty = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else { /* decimal */
|
||||||
|
for (; lisdigit(cast_uchar(*s)); s++) {
|
||||||
|
int d = *s - '0';
|
||||||
|
if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */
|
||||||
|
return NULL; /* do not accept it (as integer) */
|
||||||
|
a = a * 10 + d;
|
||||||
|
empty = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
|
||||||
|
if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
|
||||||
|
else {
|
||||||
|
*result = l_castU2S((neg) ? 0u - a : a);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
size_t luaO_str2num (const char *s, TValue *o) {
|
||||||
|
lua_Integer i; lua_Number n;
|
||||||
|
const char *e;
|
||||||
|
if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
|
||||||
|
setivalue(o, i);
|
||||||
|
}
|
||||||
|
else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
|
||||||
|
setfltvalue(o, n);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return 0; /* conversion failed */
|
||||||
|
return (e - s) + 1; /* success; return string size */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaO_utf8esc (char *buff, unsigned long x) {
|
||||||
|
int n = 1; /* number of bytes put in buffer (backwards) */
|
||||||
|
lua_assert(x <= 0x10FFFF);
|
||||||
|
if (x < 0x80) /* ascii? */
|
||||||
|
buff[UTF8BUFFSZ - 1] = cast(char, x);
|
||||||
|
else { /* need continuation bytes */
|
||||||
|
unsigned int mfb = 0x3f; /* maximum that fits in first byte */
|
||||||
|
do { /* add continuation bytes */
|
||||||
|
buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f));
|
||||||
|
x >>= 6; /* remove added bits */
|
||||||
|
mfb >>= 1; /* now there is one less bit available in first byte */
|
||||||
|
} while (x > mfb); /* still needs continuation byte? */
|
||||||
|
buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x); /* add first byte */
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* maximum length of the conversion of a number to a string */
|
||||||
|
#define MAXNUMBER2STR 50
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Convert a number object to a string
|
||||||
|
*/
|
||||||
|
void luaO_tostring (lua_State *L, StkId obj) {
|
||||||
|
char buff[MAXNUMBER2STR];
|
||||||
|
size_t len;
|
||||||
|
lua_assert(ttisnumber(obj));
|
||||||
|
if (ttisinteger(obj))
|
||||||
|
len = lua_integer2str(buff, sizeof(buff), ivalue(obj));
|
||||||
|
else {
|
||||||
|
len = lua_number2str(buff, sizeof(buff), fltvalue(obj));
|
||||||
|
#if !defined(LUA_COMPAT_FLOATSTRING)
|
||||||
|
if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */
|
||||||
|
buff[len++] = lua_getlocaledecpoint();
|
||||||
|
buff[len++] = '0'; /* adds '.0' to result */
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void pushstr (lua_State *L, const char *str, size_t l) {
|
||||||
|
setsvalue2s(L, L->top, luaS_newlstr(L, str, l));
|
||||||
|
luaD_inctop(L);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** this function handles only '%d', '%c', '%f', '%p', and '%s'
|
||||||
|
conventional formats, plus Lua-specific '%I' and '%U'
|
||||||
|
*/
|
||||||
|
const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
|
||||||
|
int n = 0;
|
||||||
|
#ifdef __PRINT_ALIGNED_32BIT__
|
||||||
|
volatile uint32_t *ap_addr;
|
||||||
|
volatile uint32_t ap_value;
|
||||||
|
uint32_t d1,d2;
|
||||||
|
double f64;
|
||||||
|
#ifdef LUAT_CONF_VM_64bit
|
||||||
|
unsigned long long u64;
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
for (;;) {
|
||||||
|
const char *e = strchr(fmt, '%');
|
||||||
|
if (e == NULL) break;
|
||||||
|
pushstr(L, fmt, e - fmt);
|
||||||
|
switch (*(e+1)) {
|
||||||
|
case 's': { /* zero-terminated string */
|
||||||
|
const char *s = va_arg(argp, char *);
|
||||||
|
if (s == NULL) s = "(null)";
|
||||||
|
pushstr(L, s, strlen(s));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'c': { /* an 'int' as a character */
|
||||||
|
char buff = cast(char, va_arg(argp, int));
|
||||||
|
if (lisprint(cast_uchar(buff)))
|
||||||
|
pushstr(L, &buff, 1);
|
||||||
|
else /* non-printable character; print its code */
|
||||||
|
luaO_pushfstring(L, "<\\%d>", cast_uchar(buff));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'd': { /* an 'int' */
|
||||||
|
setivalue(L->top, va_arg(argp, int));
|
||||||
|
goto top2str;
|
||||||
|
}
|
||||||
|
case 'I': { /* a 'lua_Integer' */
|
||||||
|
#if (defined __PRINT_ALIGNED_32BIT__) && (defined LUAT_CONF_VM_64bit) && !(defined __BK72XX__)
|
||||||
|
// 针对EC618的va_arg取double出错的临时解决方案
|
||||||
|
// 直接调用 va_arg(argp, double) 会返回0
|
||||||
|
// 可能与某个gcc参数有关
|
||||||
|
|
||||||
|
ap_addr = (uint32_t *)&argp;
|
||||||
|
ap_value = (*ap_addr);
|
||||||
|
if (!(ap_value & 0x07))
|
||||||
|
{
|
||||||
|
d1 = va_arg(argp, uint32_t);
|
||||||
|
}
|
||||||
|
d1 = va_arg(argp, uint32_t);
|
||||||
|
d2 = va_arg(argp, uint32_t);
|
||||||
|
char* tmp = (char*)&u64;
|
||||||
|
memcpy(tmp, &d1, 4);
|
||||||
|
memcpy(tmp + 4, &d2, 4);
|
||||||
|
setivalue(L->top, (l_uacInt)u64);
|
||||||
|
#else
|
||||||
|
setivalue(L->top, cast(lua_Integer, va_arg(argp, l_uacInt)));
|
||||||
|
#endif
|
||||||
|
goto top2str;
|
||||||
|
}
|
||||||
|
case 'f': { /* a 'lua_Number' */
|
||||||
|
#ifdef __PRINT_ALIGNED_32BIT__
|
||||||
|
// 针对EC618的va_arg取double出错的临时解决方案
|
||||||
|
// 直接调用 va_arg(argp, double) 会返回0
|
||||||
|
// 可能与某个gcc参数有关
|
||||||
|
ap_addr = (uint32_t *)&argp;
|
||||||
|
ap_value = (*ap_addr);
|
||||||
|
if (!(ap_value & 0x07))
|
||||||
|
{
|
||||||
|
d1 = va_arg(argp, uint32_t);
|
||||||
|
}
|
||||||
|
d1 = va_arg(argp, uint32_t);
|
||||||
|
d2 = va_arg(argp, uint32_t);
|
||||||
|
char* tmp = (char*)&f64;
|
||||||
|
memcpy(tmp, &d1, 4);
|
||||||
|
memcpy(tmp + 4, &d2, 4);
|
||||||
|
setfltvalue(L->top, (lua_Number)f64);
|
||||||
|
#else
|
||||||
|
setfltvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
|
||||||
|
#endif
|
||||||
|
top2str: /* convert the top element to a string */
|
||||||
|
luaD_inctop(L);
|
||||||
|
luaO_tostring(L, L->top - 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'p': { /* a pointer */
|
||||||
|
char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
|
||||||
|
void *p = va_arg(argp, void *);
|
||||||
|
int l = lua_pointer2str(buff, sizeof(buff), p);
|
||||||
|
pushstr(L, buff, l);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'U': { /* an 'int' as a UTF-8 sequence */
|
||||||
|
char buff[UTF8BUFFSZ];
|
||||||
|
int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));
|
||||||
|
pushstr(L, buff + UTF8BUFFSZ - l, l);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '%': {
|
||||||
|
pushstr(L, "%", 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
|
||||||
|
*(e + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n += 2;
|
||||||
|
fmt = e+2;
|
||||||
|
}
|
||||||
|
luaD_checkstack(L, 1);
|
||||||
|
pushstr(L, fmt, strlen(fmt));
|
||||||
|
if (n > 0) luaV_concat(L, n + 1);
|
||||||
|
return svalue(L->top - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
|
||||||
|
const char *msg;
|
||||||
|
va_list argp;
|
||||||
|
va_start(argp, fmt);
|
||||||
|
msg = luaO_pushvfstring(L, fmt, argp);
|
||||||
|
va_end(argp);
|
||||||
|
return msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* number of chars of a literal string without the ending \0 */
|
||||||
|
#define LL(x) (sizeof(x)/sizeof(char) - 1)
|
||||||
|
|
||||||
|
#define RETS "..."
|
||||||
|
#define PRE "[string \""
|
||||||
|
#define POS "\"]"
|
||||||
|
|
||||||
|
#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
|
||||||
|
|
||||||
|
void luaO_chunkid (char *out, const char *source, size_t bufflen) {
|
||||||
|
size_t l = strlen(source);
|
||||||
|
if (*source == '=') { /* 'literal' source */
|
||||||
|
if (l <= bufflen) /* small enough? */
|
||||||
|
memcpy(out, source + 1, l * sizeof(char));
|
||||||
|
else { /* truncate it */
|
||||||
|
addstr(out, source + 1, bufflen - 1);
|
||||||
|
*out = '\0';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (*source == '@') { /* file name */
|
||||||
|
if (l <= bufflen) /* small enough? */
|
||||||
|
memcpy(out, source + 1, l * sizeof(char));
|
||||||
|
else { /* add '...' before rest of name */
|
||||||
|
addstr(out, RETS, LL(RETS));
|
||||||
|
bufflen -= LL(RETS);
|
||||||
|
memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else { /* string; format as [string "source"] */
|
||||||
|
const char *nl = strchr(source, '\n'); /* find first new line (if any) */
|
||||||
|
addstr(out, PRE, LL(PRE)); /* add prefix */
|
||||||
|
bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
|
||||||
|
if (l < bufflen && nl == NULL) { /* small one-line source? */
|
||||||
|
addstr(out, source, l); /* keep it */
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (nl != NULL) l = nl - source; /* stop at first newline */
|
||||||
|
if (l > bufflen) l = bufflen;
|
||||||
|
addstr(out, source, l);
|
||||||
|
addstr(out, RETS, LL(RETS));
|
||||||
|
}
|
||||||
|
memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(__LUATOS_SMALL_RAM__) && defined(__LUATOS_SCRIPT_BASE__)
|
||||||
|
char *getstr(TString *ts) {
|
||||||
|
uint32_t offset;
|
||||||
|
if (ts->static_flag) {
|
||||||
|
if (!ts->shrlen)
|
||||||
|
{
|
||||||
|
offset = (ts->static_flag - 1);
|
||||||
|
offset = (offset << 15) + ts->u.static_offset + __LUATOS_SCRIPT_BASE__;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
memcpy(&offset, cast(char *, (ts)) + sizeof(UTString), 4);
|
||||||
|
}
|
||||||
|
return (char *)(offset);
|
||||||
|
} else {
|
||||||
|
return cast(char *, (ts)) + sizeof(UTString);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lopcodes.c,v 1.55.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Opcodes for Lua virtual machine
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lopcodes_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
|
||||||
|
#include "lopcodes.h"
|
||||||
|
|
||||||
|
|
||||||
|
/* ORDER OP */
|
||||||
|
|
||||||
|
LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = {
|
||||||
|
"MOVE",
|
||||||
|
"LOADK",
|
||||||
|
"LOADKX",
|
||||||
|
"LOADBOOL",
|
||||||
|
"LOADNIL",
|
||||||
|
"GETUPVAL",
|
||||||
|
"GETTABUP",
|
||||||
|
"GETTABLE",
|
||||||
|
"SETTABUP",
|
||||||
|
"SETUPVAL",
|
||||||
|
"SETTABLE",
|
||||||
|
"NEWTABLE",
|
||||||
|
"SELF",
|
||||||
|
"ADD",
|
||||||
|
"SUB",
|
||||||
|
"MUL",
|
||||||
|
"MOD",
|
||||||
|
"POW",
|
||||||
|
"DIV",
|
||||||
|
"IDIV",
|
||||||
|
"BAND",
|
||||||
|
"BOR",
|
||||||
|
"BXOR",
|
||||||
|
"SHL",
|
||||||
|
"SHR",
|
||||||
|
"UNM",
|
||||||
|
"BNOT",
|
||||||
|
"NOT",
|
||||||
|
"LEN",
|
||||||
|
"CONCAT",
|
||||||
|
"JMP",
|
||||||
|
"EQ",
|
||||||
|
"LT",
|
||||||
|
"LE",
|
||||||
|
"TEST",
|
||||||
|
"TESTSET",
|
||||||
|
"CALL",
|
||||||
|
"TAILCALL",
|
||||||
|
"RETURN",
|
||||||
|
"FORLOOP",
|
||||||
|
"FORPREP",
|
||||||
|
"TFORCALL",
|
||||||
|
"TFORLOOP",
|
||||||
|
"SETLIST",
|
||||||
|
"CLOSURE",
|
||||||
|
"VARARG",
|
||||||
|
"EXTRAARG",
|
||||||
|
NULL
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m))
|
||||||
|
|
||||||
|
LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
|
||||||
|
/* T A B C mode opcode */
|
||||||
|
opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */
|
||||||
|
,opmode(0, 1, OpArgN, OpArgN, iABx) /* OP_LOADKX */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_LOADNIL */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */
|
||||||
|
,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABUP */
|
||||||
|
,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */
|
||||||
|
,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_SELF */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_IDIV */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BAND */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BOR */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BXOR */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHL */
|
||||||
|
,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHR */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_BNOT */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */
|
||||||
|
,opmode(0, 0, OpArgR, OpArgN, iAsBx) /* OP_JMP */
|
||||||
|
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */
|
||||||
|
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */
|
||||||
|
,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */
|
||||||
|
,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TEST */
|
||||||
|
,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */
|
||||||
|
,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_RETURN */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORLOOP */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_FORPREP */
|
||||||
|
,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */
|
||||||
|
,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */
|
||||||
|
,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */
|
||||||
|
,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */
|
||||||
|
,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */
|
||||||
|
};
|
||||||
|
|
||||||
@@ -0,0 +1,520 @@
|
|||||||
|
|
||||||
|
/*
|
||||||
|
@module os
|
||||||
|
@summary os操作
|
||||||
|
@version 1.0
|
||||||
|
@date 2020.07.03
|
||||||
|
@tag LUAT_USE_GPIO
|
||||||
|
@demo os_date_time
|
||||||
|
@usage
|
||||||
|
-- os模块是lua原生模块, 这份文档是为了方便阐述实际使用中的常见问题
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define loslib_c
|
||||||
|
#define LUA_LIB
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <errno.h>
|
||||||
|
#include <locale.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lauxlib.h"
|
||||||
|
#include "lualib.h"
|
||||||
|
|
||||||
|
#include "luat_fs.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** List of valid conversion specifiers for the 'strftime' function;
|
||||||
|
** options are grouped by length; group of length 2 start with '||'.
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
#if !defined(LUA_STRFTIMEOPTIONS) /* { */
|
||||||
|
|
||||||
|
/* options for ANSI C 89 (only 1-char options) */
|
||||||
|
#define L_STRFTIMEC89 "aAbBcdHIjmMpSUwWxXyYZ%"
|
||||||
|
|
||||||
|
/* options for ISO C 99 and POSIX */
|
||||||
|
#define L_STRFTIMEC99 "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%" \
|
||||||
|
"||" "EcECExEXEyEY" "OdOeOHOIOmOMOSOuOUOVOwOWOy" /* two-char options */
|
||||||
|
|
||||||
|
/* options for Windows */
|
||||||
|
#define L_STRFTIMEWIN "aAbBcdHIjmMpSUwWxXyYzZ%" \
|
||||||
|
"||" "#c#x#d#H#I#j#m#M#S#U#w#W#y#Y" /* two-char options */
|
||||||
|
|
||||||
|
// #if defined(LUA_USE_WINDOWS)
|
||||||
|
// #define LUA_STRFTIMEOPTIONS L_STRFTIMEWIN
|
||||||
|
// #elif defined(LUA_USE_C89)
|
||||||
|
#define LUA_STRFTIMEOPTIONS L_STRFTIMEC89
|
||||||
|
// #else /* C99 specification */
|
||||||
|
// #define LUA_STRFTIMEOPTIONS L_STRFTIMEC99
|
||||||
|
// #endif
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Configuration for time-related stuff
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
#if !defined(l_time_t) /* { */
|
||||||
|
/*
|
||||||
|
** type to represent time_t in Lua
|
||||||
|
*/
|
||||||
|
#define l_timet lua_Integer
|
||||||
|
#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
|
||||||
|
|
||||||
|
static time_t l_checktime (lua_State *L, int arg) {
|
||||||
|
lua_Integer t = luaL_checkinteger(L, arg);
|
||||||
|
luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
|
||||||
|
return (time_t)t;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(l_gmtime) /* { */
|
||||||
|
/*
|
||||||
|
** By default, Lua uses gmtime/localtime, except when POSIX is available,
|
||||||
|
** where it uses gmtime_r/localtime_r
|
||||||
|
*/
|
||||||
|
|
||||||
|
#if defined(LUA_USE_POSIX) /* { */
|
||||||
|
|
||||||
|
#define l_gmtime(t,r) gmtime_r(t,r)
|
||||||
|
#define l_localtime(t,r) localtime_r(t,r)
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
/* ISO C definitions */
|
||||||
|
#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
|
||||||
|
#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {==================================================================
|
||||||
|
** Configuration for 'tmpnam':
|
||||||
|
** By default, Lua uses tmpnam except when POSIX is available, where
|
||||||
|
** it uses mkstemp.
|
||||||
|
** ===================================================================
|
||||||
|
*/
|
||||||
|
#if !defined(lua_tmpnam) /* { */
|
||||||
|
|
||||||
|
#if defined(LUA_USE_POSIX) /* { */
|
||||||
|
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#define LUA_TMPNAMBUFSIZE 32
|
||||||
|
|
||||||
|
#if !defined(LUA_TMPNAMTEMPLATE)
|
||||||
|
#define LUA_TMPNAMTEMPLATE "/tmp/lua_XXXXXX"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define lua_tmpnam(b,e) { \
|
||||||
|
strcpy(b, LUA_TMPNAMTEMPLATE); \
|
||||||
|
e = mkstemp(b); \
|
||||||
|
if (e != -1) close(e); \
|
||||||
|
e = (e == -1); }
|
||||||
|
|
||||||
|
#else /* }{ */
|
||||||
|
|
||||||
|
/* ISO C definitions */
|
||||||
|
#define LUA_TMPNAMBUFSIZE L_tmpnam
|
||||||
|
#define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
|
||||||
|
#endif /* } */
|
||||||
|
/* }================================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_USE_LINUX) || defined(LUA_USE_WINDOWS) || defined(LUA_USE_MACOSX)
|
||||||
|
static int os_execute (lua_State *L) {
|
||||||
|
const char *cmd = luaL_optstring(L, 1, NULL);
|
||||||
|
int stat = system(cmd);
|
||||||
|
if (cmd != NULL)
|
||||||
|
return luaL_execresult(L, stat);
|
||||||
|
else {
|
||||||
|
lua_pushboolean(L, stat); /* true if there is a shell */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
移除文件
|
||||||
|
@api os.remove(path)
|
||||||
|
@string 待移除的文件完整路径
|
||||||
|
@return bool 成功返回true,其他情况返回nil
|
||||||
|
@return string 失败时返回原因字符串
|
||||||
|
@usage
|
||||||
|
-- 删除根目录下的某个文件
|
||||||
|
os.remove("/1.txt")
|
||||||
|
-- 注意, 线刷时的文件, 一般在 /luadb 目录, 这个目录下的文件是只读的
|
||||||
|
-- 也就是无法执行 os.remove("/luadb/xxx.bin")
|
||||||
|
*/
|
||||||
|
static int os_remove (lua_State *L) {
|
||||||
|
const char *filename = luaL_checkstring(L, 1);
|
||||||
|
return luaL_fileresult(L, luat_fs_remove(filename) == 0, filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
文件重命名
|
||||||
|
@api os.rename(old_path, new_path)
|
||||||
|
@string 源文件完整路径
|
||||||
|
@string 目标文件完整路径
|
||||||
|
@return bool 成功返回true,其他情况返回nil
|
||||||
|
@return string 失败时返回原因字符串
|
||||||
|
@usage
|
||||||
|
-- 注意, 只有在相同文件系统下的文件可以重命名
|
||||||
|
-- 例如:
|
||||||
|
os.rename("/1.txt", "/2.txt")
|
||||||
|
-- 不同文件系统, 或者源文件系统是只读的, 则无法执行
|
||||||
|
--os.rename("/luadb/1.txt", "/luadb/2.txt")
|
||||||
|
--os.rename("/luadb/1.txt", "/2.txt")
|
||||||
|
*/
|
||||||
|
static int os_rename (lua_State *L) {
|
||||||
|
const char *fromname = luaL_checkstring(L, 1);
|
||||||
|
const char *toname = luaL_checkstring(L, 2);
|
||||||
|
return luaL_fileresult(L, luat_fs_rename(fromname, toname) == 0, NULL);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_USE_LINUX) || defined(LUA_USE_WINDOWS) || defined(LUA_USE_MACOSX)
|
||||||
|
static int os_tmpname (lua_State *L) {
|
||||||
|
char buff[LUA_TMPNAMBUFSIZE];
|
||||||
|
int err;
|
||||||
|
lua_tmpnam(buff, err);
|
||||||
|
if (err)
|
||||||
|
return luaL_error(L, "unable to generate a unique filename");
|
||||||
|
lua_pushstring(L, buff);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int os_getenv (lua_State *L) {
|
||||||
|
lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static int os_clock (lua_State *L) {
|
||||||
|
#ifdef LUAT_USE_MCU
|
||||||
|
#ifdef LUAT_CONF_VM_64bit
|
||||||
|
extern uint64_t luat_mcu_tick64_ms(void);
|
||||||
|
lua_pushinteger(L, (lua_Integer)luat_mcu_tick64_ms()/1000);
|
||||||
|
#else
|
||||||
|
extern long luat_mcu_ticks(void);
|
||||||
|
extern uint32_t luat_mcu_hz(void);
|
||||||
|
lua_pushinteger(L, (lua_Integer)luat_mcu_ticks()/luat_mcu_hz());
|
||||||
|
#endif // LUAT_CONF_VM_64bit
|
||||||
|
#else
|
||||||
|
lua_pushinteger(L, 0);
|
||||||
|
#endif
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {======================================================
|
||||||
|
** Time/Date operations
|
||||||
|
** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
|
||||||
|
** wday=%w+1, yday=%j, isdst=? }
|
||||||
|
** =======================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
static void setfield (lua_State *L, const char *key, int value) {
|
||||||
|
lua_pushinteger(L, value);
|
||||||
|
lua_setfield(L, -2, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setboolfield (lua_State *L, const char *key, int value) {
|
||||||
|
if (value < 0) /* undefined? */
|
||||||
|
return; /* does not set field */
|
||||||
|
lua_pushboolean(L, value);
|
||||||
|
lua_setfield(L, -2, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Set all fields from structure 'tm' in the table on top of the stack
|
||||||
|
*/
|
||||||
|
static void setallfields (lua_State *L, struct tm *stm) {
|
||||||
|
setfield(L, "sec", stm->tm_sec);
|
||||||
|
setfield(L, "min", stm->tm_min);
|
||||||
|
setfield(L, "hour", stm->tm_hour);
|
||||||
|
setfield(L, "day", stm->tm_mday);
|
||||||
|
setfield(L, "month", stm->tm_mon + 1);
|
||||||
|
setfield(L, "year", stm->tm_year + 1900);
|
||||||
|
setfield(L, "wday", stm->tm_wday + 1);
|
||||||
|
setfield(L, "yday", stm->tm_yday + 1);
|
||||||
|
setboolfield(L, "isdst", stm->tm_isdst);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int getboolfield (lua_State *L, const char *key) {
|
||||||
|
int res;
|
||||||
|
res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
|
||||||
|
lua_pop(L, 1);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* maximum value for date fields (to avoid arithmetic overflows with 'int') */
|
||||||
|
#if !defined(L_MAXDATEFIELD)
|
||||||
|
#define L_MAXDATEFIELD (INT_MAX / 2)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static int getfield (lua_State *L, const char *key, int d, int delta) {
|
||||||
|
int isnum;
|
||||||
|
int t = lua_getfield(L, -1, key); /* get field and its type */
|
||||||
|
lua_Integer res = lua_tointegerx(L, -1, &isnum);
|
||||||
|
if (!isnum) { /* field is not an integer? */
|
||||||
|
if (t != LUA_TNIL) /* some other value? */
|
||||||
|
return luaL_error(L, "field '%s' is not an integer", key);
|
||||||
|
else if (d < 0) /* absent field; no default? */
|
||||||
|
return luaL_error(L, "field '%s' missing in date table", key);
|
||||||
|
res = d;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD))
|
||||||
|
return luaL_error(L, "field '%s' is out-of-bound", key);
|
||||||
|
res -= delta;
|
||||||
|
}
|
||||||
|
lua_pop(L, 1);
|
||||||
|
return (int)res;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const char *checkoption (lua_State *L, const char *conv,
|
||||||
|
ptrdiff_t convlen, char *buff) {
|
||||||
|
const char *option = LUA_STRFTIMEOPTIONS;
|
||||||
|
int oplen = 1; /* length of options being checked */
|
||||||
|
for (; *option != '\0' && oplen <= convlen; option += oplen) {
|
||||||
|
if (*option == '|') /* next block? */
|
||||||
|
oplen++; /* will check options with next length (+1) */
|
||||||
|
else if (memcmp(conv, option, oplen) == 0) { /* match? */
|
||||||
|
memcpy(buff, conv, oplen); /* copy valid option to buffer */
|
||||||
|
buff[oplen] = '\0';
|
||||||
|
return conv + oplen; /* return next item */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
luaL_argerror(L, 1,
|
||||||
|
lua_pushfstring(L, "invalid conversion specifier '%%%s'", conv));
|
||||||
|
return conv; /* to avoid warnings */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* maximum size for an individual 'strftime' item */
|
||||||
|
#define SIZETIMEFMT 250
|
||||||
|
|
||||||
|
#ifdef LUAT_USE_RTC
|
||||||
|
#include "luat_rtc.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
日期函数
|
||||||
|
@api os.date(fmt, time)
|
||||||
|
@string 格式化字符串,可以是nil
|
||||||
|
@table 日期时间的table
|
||||||
|
@return table/string 根据fmt的不同,返回值不同
|
||||||
|
@usage
|
||||||
|
|
||||||
|
-- 值得注意的几点:
|
||||||
|
-- 1. 若需要UTC时间, fmt的第一个字符写"!"
|
||||||
|
-- 2. fmt的格式化遵循 C 函数 strftime, 可以查阅 https://developer.aliyun.com/article/320480
|
||||||
|
|
||||||
|
-- 获取本地时间字符串
|
||||||
|
log.info("本地时间字符串", os.date())
|
||||||
|
-- 获取UTC时间字符串
|
||||||
|
log.info("UTC时间字符串", os.date("!%c"))
|
||||||
|
-- 格式化本地时间字符串
|
||||||
|
log.info("本地时间字符串", os.date("%Y-%m-%d %H:%M:%S"))
|
||||||
|
-- 格式化UTC时间字符串
|
||||||
|
log.info("UTC时间字符串", os.date("!%Y-%m-%d %H:%M:%S"))
|
||||||
|
-- 格式化时间字符串
|
||||||
|
log.info("自定义时间的字符串", os.date("!%Y-%m-%d %H:%M:%S", os.time({year=2000, mon=1, day=1, hour=0, min=0, sec=0})))
|
||||||
|
|
||||||
|
-- 获取本地时间的table
|
||||||
|
log.info("本地时间字符串", json.encode(os.date("*t")))
|
||||||
|
-- 获取UTC时间的table
|
||||||
|
log.info("UTC时间字符串", json.encode(os.date("!*t")))
|
||||||
|
*/
|
||||||
|
static int os_date (lua_State *L) {
|
||||||
|
size_t slen;
|
||||||
|
const char *s = luaL_optlstring(L, 1, "%c", &slen);
|
||||||
|
time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
|
||||||
|
const char *se = s + slen; /* 's' end */
|
||||||
|
struct tm tmr, *stm;
|
||||||
|
if (*s == '!') { /* UTC? */
|
||||||
|
stm = l_gmtime(&t, &tmr);
|
||||||
|
s++; /* skip '!' */
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
#ifdef LUAT_USE_RTC
|
||||||
|
t += (luat_rtc_timezone(NULL) / 4) * 3600;
|
||||||
|
stm = l_gmtime(&t, &tmr);
|
||||||
|
#else
|
||||||
|
stm = l_localtime(&t, &tmr);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
if (stm == NULL) /* invalid date? */
|
||||||
|
return luaL_error(L,
|
||||||
|
"time result cannot be represented in this installation");
|
||||||
|
if (strcmp(s, "*t") == 0) {
|
||||||
|
lua_createtable(L, 0, 9); /* 9 = number of fields */
|
||||||
|
setallfields(L, stm);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
char cc[4]; /* buffer for individual conversion specifiers */
|
||||||
|
luaL_Buffer b;
|
||||||
|
cc[0] = '%';
|
||||||
|
luaL_buffinit(L, &b);
|
||||||
|
while (s < se) {
|
||||||
|
if (*s != '%') /* not a conversion specifier? */
|
||||||
|
luaL_addchar(&b, *s++);
|
||||||
|
else {
|
||||||
|
size_t reslen;
|
||||||
|
char *buff = luaL_prepbuffsize(&b, SIZETIMEFMT);
|
||||||
|
s++; /* skip '%' */
|
||||||
|
s = checkoption(L, s, se - s, cc + 1); /* copy specifier to 'cc' */
|
||||||
|
reslen = strftime(buff, SIZETIMEFMT, cc, stm);
|
||||||
|
luaL_addsize(&b, reslen);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
luaL_pushresult(&b);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
时间戳函数
|
||||||
|
@api os.time(mytime)
|
||||||
|
@table 日期时间的table
|
||||||
|
@return int 时间戳
|
||||||
|
@usage
|
||||||
|
-- 注意注意, 这个函数返回的是UTC时间戳
|
||||||
|
-- 时间戳, 但lua下的精度只能到秒
|
||||||
|
log.info("UTC时间戳", os.time())
|
||||||
|
log.info("自定义时间戳", os.time({year=2000, mon=1, day=1, hour=0, min=0, sec=0}))
|
||||||
|
*/
|
||||||
|
static int os_time (lua_State *L) {
|
||||||
|
time_t t;
|
||||||
|
if (lua_isnoneornil(L, 1)) /* called without args? */
|
||||||
|
{
|
||||||
|
t = time(NULL); /* get current time */
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
struct tm ts;
|
||||||
|
luaL_checktype(L, 1, LUA_TTABLE);
|
||||||
|
lua_settop(L, 1); /* make sure table is at the top */
|
||||||
|
ts.tm_sec = getfield(L, "sec", 0, 0);
|
||||||
|
ts.tm_min = getfield(L, "min", 0, 0);
|
||||||
|
ts.tm_hour = getfield(L, "hour", 12, 0);
|
||||||
|
ts.tm_mday = getfield(L, "day", -1, 0);
|
||||||
|
ts.tm_year = getfield(L, "year", -1, 1900);
|
||||||
|
ts.tm_isdst = getboolfield(L, "isdst");
|
||||||
|
// 兼容RTC库的mon属性, 当初我咋就没想到呢
|
||||||
|
// https://gitee.com/openLuat/LuatOS/issues/I7MYRS
|
||||||
|
if (lua_getfield(L, 1, "mon") != LUA_TNIL) {
|
||||||
|
ts.tm_mon = lua_tointeger(L, -1) -1;
|
||||||
|
lua_pop(L, 1);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_settop(L, 1);
|
||||||
|
ts.tm_mon = getfield(L, "month", -1, 1);
|
||||||
|
}
|
||||||
|
t = mktime(&ts);
|
||||||
|
setallfields(L, &ts); /* update fields with normalized values */
|
||||||
|
}
|
||||||
|
if (t != (time_t)(l_timet)t || t == (time_t)(-1))
|
||||||
|
return luaL_error(L,
|
||||||
|
"time result cannot be represented in this installation");
|
||||||
|
l_pushtime(L, t);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
时间差值
|
||||||
|
@api os.difftime(timeA, timeB)
|
||||||
|
@int 时间A,数值类型
|
||||||
|
@int 时间B,数值类型
|
||||||
|
@return int 时间差值
|
||||||
|
*/
|
||||||
|
static int os_difftime (lua_State *L) {
|
||||||
|
time_t t1 = l_checktime(L, 1);
|
||||||
|
time_t t2 = l_checktime(L, 2);
|
||||||
|
lua_pushnumber(L, (lua_Number)difftime(t1, t2));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
#if defined(LUA_USE_LINUX) || defined(LUA_USE_WINDOWS) || defined(LUA_USE_MACOSX)
|
||||||
|
static int os_setlocale (lua_State *L) {
|
||||||
|
static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
|
||||||
|
LC_NUMERIC, LC_TIME};
|
||||||
|
static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
|
||||||
|
"numeric", "time", NULL};
|
||||||
|
const char *l = luaL_optstring(L, 1, NULL);
|
||||||
|
int op = luaL_checkoption(L, 2, "all", catnames);
|
||||||
|
lua_pushstring(L, setlocale(cat[op], l));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
static int os_exit (lua_State *L) {
|
||||||
|
int status;
|
||||||
|
if (lua_isboolean(L, 1))
|
||||||
|
status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
|
||||||
|
else
|
||||||
|
status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
|
||||||
|
if (lua_toboolean(L, 2))
|
||||||
|
lua_close(L);
|
||||||
|
if (L) exit(status); /* 'if' to avoid warnings for unreachable 'return' */
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "rotable2.h"
|
||||||
|
static const rotable_Reg_t syslib[] = {
|
||||||
|
{"clock", ROREG_FUNC(os_clock)},
|
||||||
|
{"date", ROREG_FUNC(os_date)},
|
||||||
|
{"difftime", ROREG_FUNC(os_difftime)},
|
||||||
|
#if defined(LUA_USE_LINUX) || defined(LUA_USE_WINDOWS) || defined(LUA_USE_MACOSX)
|
||||||
|
{"execute", ROREG_FUNC(os_execute)},
|
||||||
|
{"exit", ROREG_FUNC(os_exit)},
|
||||||
|
{"getenv", ROREG_FUNC(os_getenv)},
|
||||||
|
{"setlocale", ROREG_FUNC(os_setlocale)},
|
||||||
|
{"tmpname", ROREG_FUNC(os_tmpname)},
|
||||||
|
#endif
|
||||||
|
{"remove", ROREG_FUNC(os_remove)},
|
||||||
|
{"rename", ROREG_FUNC(os_rename)},
|
||||||
|
{"time", ROREG_FUNC(os_time)},
|
||||||
|
{NULL, ROREG_INT(0) }
|
||||||
|
};
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_os (lua_State *L) {
|
||||||
|
luat_newlib2(L, syslib);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,356 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lstate.c,v 2.133.1.1 2017/04/19 17:39:34 roberto Exp $
|
||||||
|
** Global State
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lstate_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lapi.h"
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lfunc.h"
|
||||||
|
#include "lgc.h"
|
||||||
|
#include "llex.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
#include "ltable.h"
|
||||||
|
#include "ltm.h"
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(LUAI_GCPAUSE)
|
||||||
|
#define LUAI_GCPAUSE 200 /* 200% */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(LUAI_GCMUL)
|
||||||
|
#define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** a macro to help the creation of a unique random seed when a state is
|
||||||
|
** created; the seed is used to randomize hashes.
|
||||||
|
*/
|
||||||
|
#if !defined(luai_makeseed)
|
||||||
|
#include <time.h>
|
||||||
|
#define luai_makeseed() cast(unsigned int, ~0)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** thread state + extra space
|
||||||
|
*/
|
||||||
|
typedef struct LX {
|
||||||
|
lu_byte extra_[LUA_EXTRASPACE];
|
||||||
|
lua_State l;
|
||||||
|
} LX;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Main thread combines a thread state and the global state
|
||||||
|
*/
|
||||||
|
typedef struct LG {
|
||||||
|
LX l;
|
||||||
|
global_State g;
|
||||||
|
} LG;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Compute an initial seed as random as possible. Rely on Address Space
|
||||||
|
** Layout Randomization (if present) to increase randomness..
|
||||||
|
*/
|
||||||
|
#define addbuff(b,p,e) \
|
||||||
|
{ size_t t = cast(size_t, e); \
|
||||||
|
memcpy(b + p, &t, sizeof(t)); p += sizeof(t); }
|
||||||
|
#if 0
|
||||||
|
static unsigned int makeseed (lua_State *L) {
|
||||||
|
char buff[4 * sizeof(size_t)];
|
||||||
|
unsigned int h = luai_makeseed();
|
||||||
|
int p = 0;
|
||||||
|
addbuff(buff, p, L); /* heap variable */
|
||||||
|
addbuff(buff, p, &h); /* local variable */
|
||||||
|
addbuff(buff, p, luaO_nilobject); /* global variable */
|
||||||
|
addbuff(buff, p, &lua_newstate); /* public function */
|
||||||
|
lua_assert(p == sizeof(buff));
|
||||||
|
return luaS_hash(buff, p, h);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*
|
||||||
|
** set GCdebt to a new value keeping the value (totalbytes + GCdebt)
|
||||||
|
** invariant (and avoiding underflows in 'totalbytes')
|
||||||
|
*/
|
||||||
|
void luaE_setdebt (global_State *g, l_mem debt) {
|
||||||
|
l_mem tb = gettotalbytes(g);
|
||||||
|
lua_assert(tb > 0);
|
||||||
|
if (debt < tb - MAX_LMEM)
|
||||||
|
debt = tb - MAX_LMEM; /* will make 'totalbytes == MAX_LMEM' */
|
||||||
|
g->totalbytes = tb - debt;
|
||||||
|
g->GCdebt = debt;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
CallInfo *luaE_extendCI (lua_State *L) {
|
||||||
|
CallInfo *ci = luaM_new(L, CallInfo);
|
||||||
|
lua_assert(L->ci->next == NULL);
|
||||||
|
L->ci->next = ci;
|
||||||
|
ci->previous = L->ci;
|
||||||
|
ci->next = NULL;
|
||||||
|
L->nci++;
|
||||||
|
return ci;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** free all CallInfo structures not in use by a thread
|
||||||
|
*/
|
||||||
|
void luaE_freeCI (lua_State *L) {
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
CallInfo *next = ci->next;
|
||||||
|
ci->next = NULL;
|
||||||
|
while ((ci = next) != NULL) {
|
||||||
|
next = ci->next;
|
||||||
|
luaM_free(L, ci);
|
||||||
|
L->nci--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** free half of the CallInfo structures not in use by a thread
|
||||||
|
*/
|
||||||
|
void luaE_shrinkCI (lua_State *L) {
|
||||||
|
CallInfo *ci = L->ci;
|
||||||
|
CallInfo *next2; /* next's next */
|
||||||
|
/* while there are two nexts */
|
||||||
|
while (ci->next != NULL && (next2 = ci->next->next) != NULL) {
|
||||||
|
luaM_free(L, ci->next); /* free next */
|
||||||
|
L->nci--;
|
||||||
|
ci->next = next2; /* remove 'next' from the list */
|
||||||
|
next2->previous = ci;
|
||||||
|
ci = next2; /* keep next's next */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void stack_init (lua_State *L1, lua_State *L) {
|
||||||
|
int i; CallInfo *ci;
|
||||||
|
/* initialize stack array */
|
||||||
|
L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, TValue);
|
||||||
|
L1->stacksize = BASIC_STACK_SIZE;
|
||||||
|
for (i = 0; i < BASIC_STACK_SIZE; i++)
|
||||||
|
setnilvalue(L1->stack + i); /* erase new stack */
|
||||||
|
L1->top = L1->stack;
|
||||||
|
L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK;
|
||||||
|
/* initialize first ci */
|
||||||
|
ci = &L1->base_ci;
|
||||||
|
ci->next = ci->previous = NULL;
|
||||||
|
ci->callstatus = 0;
|
||||||
|
ci->func = L1->top;
|
||||||
|
setnilvalue(L1->top++); /* 'function' entry for this 'ci' */
|
||||||
|
ci->top = L1->top + LUA_MINSTACK;
|
||||||
|
L1->ci = ci;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void freestack (lua_State *L) {
|
||||||
|
if (L->stack == NULL)
|
||||||
|
return; /* stack not completely built yet */
|
||||||
|
L->ci = &L->base_ci; /* free the entire 'ci' list */
|
||||||
|
luaE_freeCI(L);
|
||||||
|
lua_assert(L->nci == 0);
|
||||||
|
luaM_freearray(L, L->stack, L->stacksize); /* free stack array */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Create registry table and its predefined values
|
||||||
|
*/
|
||||||
|
static void init_registry (lua_State *L, global_State *g) {
|
||||||
|
TValue temp;
|
||||||
|
/* create registry */
|
||||||
|
Table *registry = luaH_new(L);
|
||||||
|
sethvalue(L, &g->l_registry, registry);
|
||||||
|
luaH_resize(L, registry, LUA_RIDX_LAST, 0);
|
||||||
|
/* registry[LUA_RIDX_MAINTHREAD] = L */
|
||||||
|
setthvalue(L, &temp, L); /* temp = L */
|
||||||
|
luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);
|
||||||
|
/* registry[LUA_RIDX_GLOBALS] = table of globals */
|
||||||
|
sethvalue(L, &temp, luaH_new(L)); /* temp = new table (global table) */
|
||||||
|
luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** open parts of the state that may cause memory-allocation errors.
|
||||||
|
** ('g->version' != NULL flags that the state was completely build)
|
||||||
|
*/
|
||||||
|
static void f_luaopen (lua_State *L, void *ud) {
|
||||||
|
global_State *g = G(L);
|
||||||
|
UNUSED(ud);
|
||||||
|
stack_init(L, L); /* init stack */
|
||||||
|
init_registry(L, g);
|
||||||
|
luaS_init(L);
|
||||||
|
luaT_init(L);
|
||||||
|
luaX_init(L);
|
||||||
|
g->gcrunning = 1; /* allow gc */
|
||||||
|
g->version = lua_version(NULL);
|
||||||
|
luai_userstateopen(L);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** preinitialize a thread with consistent values without allocating
|
||||||
|
** any memory (to avoid errors)
|
||||||
|
*/
|
||||||
|
static void preinit_thread (lua_State *L, global_State *g) {
|
||||||
|
G(L) = g;
|
||||||
|
L->stack = NULL;
|
||||||
|
L->ci = NULL;
|
||||||
|
L->nci = 0;
|
||||||
|
L->stacksize = 0;
|
||||||
|
L->twups = L; /* thread has no upvalues */
|
||||||
|
L->errorJmp = NULL;
|
||||||
|
L->nCcalls = 0;
|
||||||
|
L->hook = NULL;
|
||||||
|
L->hookmask = 0;
|
||||||
|
L->basehookcount = 0;
|
||||||
|
L->allowhook = 1;
|
||||||
|
resethookcount(L);
|
||||||
|
L->openupval = NULL;
|
||||||
|
L->nny = 1;
|
||||||
|
L->status = LUA_OK;
|
||||||
|
L->errfunc = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void close_state (lua_State *L) {
|
||||||
|
global_State *g = G(L);
|
||||||
|
luaF_close(L, L->stack); /* close all upvalues for this thread */
|
||||||
|
luaC_freeallobjects(L); /* collect all objects */
|
||||||
|
if (g->version) /* closing a fully built state? */
|
||||||
|
luai_userstateclose(L);
|
||||||
|
luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
|
||||||
|
freestack(L);
|
||||||
|
lua_assert(gettotalbytes(g) == sizeof(LG));
|
||||||
|
(*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0); /* free main block */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API lua_State *lua_newthread (lua_State *L) {
|
||||||
|
global_State *g = G(L);
|
||||||
|
lua_State *L1;
|
||||||
|
lua_lock(L);
|
||||||
|
luaC_checkGC(L);
|
||||||
|
/* create new thread */
|
||||||
|
L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l;
|
||||||
|
L1->marked = luaC_white(g);
|
||||||
|
L1->tt = LUA_TTHREAD;
|
||||||
|
/* link it on list 'allgc' */
|
||||||
|
L1->next = g->allgc;
|
||||||
|
g->allgc = obj2gco(L1);
|
||||||
|
/* anchor it on L stack */
|
||||||
|
setthvalue(L, L->top, L1);
|
||||||
|
api_incr_top(L);
|
||||||
|
preinit_thread(L1, g);
|
||||||
|
L1->hookmask = L->hookmask;
|
||||||
|
L1->basehookcount = L->basehookcount;
|
||||||
|
L1->hook = L->hook;
|
||||||
|
resethookcount(L1);
|
||||||
|
/* initialize L1 extra space */
|
||||||
|
memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread),
|
||||||
|
LUA_EXTRASPACE);
|
||||||
|
luai_userstatethread(L, L1);
|
||||||
|
stack_init(L1, L); /* init stack */
|
||||||
|
lua_unlock(L);
|
||||||
|
return L1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaE_freethread (lua_State *L, lua_State *L1) {
|
||||||
|
LX *l = fromstate(L1);
|
||||||
|
luaF_close(L1, L1->stack); /* close all upvalues for this thread */
|
||||||
|
lua_assert(L1->openupval == NULL);
|
||||||
|
luai_userstatefree(L, L1);
|
||||||
|
freestack(L1);
|
||||||
|
luaM_free(L, l);
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef FEATURE_STATIC_LUASTATE
|
||||||
|
#undef FEATURE_STATIC_LUASTATE
|
||||||
|
//static LG LUAT_LG;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
|
||||||
|
int i;
|
||||||
|
lua_State *L;
|
||||||
|
global_State *g;
|
||||||
|
#ifdef FEATURE_STATIC_LUASTATE
|
||||||
|
LG *l = &LUAT_LG;
|
||||||
|
#else
|
||||||
|
LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));
|
||||||
|
if (l == NULL) return NULL;
|
||||||
|
#endif
|
||||||
|
L = &l->l.l;
|
||||||
|
g = &l->g;
|
||||||
|
L->next = NULL;
|
||||||
|
L->tt = LUA_TTHREAD;
|
||||||
|
g->currentwhite = bitmask(WHITE0BIT);
|
||||||
|
L->marked = luaC_white(g);
|
||||||
|
preinit_thread(L, g);
|
||||||
|
g->frealloc = f;
|
||||||
|
g->ud = ud;
|
||||||
|
g->mainthread = L;
|
||||||
|
g->seed = G_SEED_FIXED;//fixed seed. 2024.5.10 by wendal. makeseed(L);
|
||||||
|
g->gcrunning = 0; /* no GC while building state */
|
||||||
|
g->GCestimate = 0;
|
||||||
|
g->strt.size = g->strt.nuse = 0;
|
||||||
|
g->strt.hash = NULL;
|
||||||
|
setnilvalue(&g->l_registry);
|
||||||
|
g->panic = NULL;
|
||||||
|
g->version = NULL;
|
||||||
|
g->gcstate = GCSpause;
|
||||||
|
g->gckind = KGC_NORMAL;
|
||||||
|
g->allgc = g->finobj = g->tobefnz = g->fixedgc = NULL;
|
||||||
|
g->sweepgc = NULL;
|
||||||
|
g->gray = g->grayagain = NULL;
|
||||||
|
g->weak = g->ephemeron = g->allweak = NULL;
|
||||||
|
g->twups = NULL;
|
||||||
|
g->totalbytes = sizeof(LG);
|
||||||
|
g->GCdebt = 0;
|
||||||
|
g->gcfinnum = 0;
|
||||||
|
g->gcpause = LUAI_GCPAUSE;
|
||||||
|
g->gcstepmul = LUAI_GCMUL;
|
||||||
|
for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
|
||||||
|
if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
|
||||||
|
/* memory allocation error: free partial state */
|
||||||
|
close_state(L);
|
||||||
|
L = NULL;
|
||||||
|
}
|
||||||
|
return L;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
LUA_API void lua_close (lua_State *L) {
|
||||||
|
L = G(L)->mainthread; /* only the main thread can be closed */
|
||||||
|
lua_lock(L);
|
||||||
|
close_state(L);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lstring.c,v 2.56.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** String table (keeps all strings handled by Lua)
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lstring_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
|
||||||
|
|
||||||
|
#define MEMERRMSG "not enough memory"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to
|
||||||
|
** compute its hash
|
||||||
|
*/
|
||||||
|
#if !defined(LUAI_HASHLIMIT)
|
||||||
|
#define LUAI_HASHLIMIT 5
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** equality for long strings
|
||||||
|
*/
|
||||||
|
int luaS_eqlngstr (TString *a, TString *b) {
|
||||||
|
size_t len = a->u.lnglen;
|
||||||
|
lua_assert(a->tt == LUA_TLNGSTR && b->tt == LUA_TLNGSTR);
|
||||||
|
return (a == b) || /* same instance or... */
|
||||||
|
((len == b->u.lnglen) && /* equal length and ... */
|
||||||
|
(memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {
|
||||||
|
unsigned int h = seed ^ cast(unsigned int, l);
|
||||||
|
size_t step = (l >> LUAI_HASHLIMIT) + 1;
|
||||||
|
for (; l >= step; l -= step)
|
||||||
|
h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1]));
|
||||||
|
return h;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
unsigned int luaS_hashlongstr (TString *ts) {
|
||||||
|
lua_assert(ts->tt == LUA_TLNGSTR);
|
||||||
|
if (ts->extra == 0) { /* no hash? */
|
||||||
|
ts->hash = luaS_hash(getstr(ts), ts->u.lnglen, ts->hash);
|
||||||
|
ts->extra = 1; /* now it has its hash */
|
||||||
|
}
|
||||||
|
return ts->hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** resizes the string table
|
||||||
|
*/
|
||||||
|
void luaS_resize (lua_State *L, int newsize) {
|
||||||
|
int i;
|
||||||
|
stringtable *tb = &G(L)->strt;
|
||||||
|
if (newsize > tb->size) { /* grow table if needed */
|
||||||
|
luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
|
||||||
|
for (i = tb->size; i < newsize; i++)
|
||||||
|
tb->hash[i] = NULL;
|
||||||
|
}
|
||||||
|
for (i = 0; i < tb->size; i++) { /* rehash */
|
||||||
|
TString *p = tb->hash[i];
|
||||||
|
tb->hash[i] = NULL;
|
||||||
|
while (p) { /* for each node in the list */
|
||||||
|
TString *hnext = p->u.hnext; /* save next */
|
||||||
|
unsigned int h = lmod(p->hash, newsize); /* new position */
|
||||||
|
p->u.hnext = tb->hash[h]; /* chain it */
|
||||||
|
tb->hash[h] = p;
|
||||||
|
p = hnext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (newsize < tb->size) { /* shrink table if needed */
|
||||||
|
/* vanishing slice should be empty */
|
||||||
|
lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL);
|
||||||
|
luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
|
||||||
|
}
|
||||||
|
tb->size = newsize;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Clear API string cache. (Entries cannot be empty, so fill them with
|
||||||
|
** a non-collectable string.)
|
||||||
|
*/
|
||||||
|
void luaS_clearcache (global_State *g) {
|
||||||
|
int i, j;
|
||||||
|
for (i = 0; i < STRCACHE_N; i++)
|
||||||
|
for (j = 0; j < STRCACHE_M; j++) {
|
||||||
|
if (iswhite(g->strcache[i][j])) /* will entry be collected? */
|
||||||
|
g->strcache[i][j] = g->memerrmsg; /* replace it with something fixed */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Initialize the string table and the string cache
|
||||||
|
*/
|
||||||
|
void luaS_init (lua_State *L) {
|
||||||
|
global_State *g = G(L);
|
||||||
|
int i, j;
|
||||||
|
luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */
|
||||||
|
/* pre-create memory-error message */
|
||||||
|
g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
|
||||||
|
luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */
|
||||||
|
for (i = 0; i < STRCACHE_N; i++) /* fill cache with valid strings */
|
||||||
|
for (j = 0; j < STRCACHE_M; j++)
|
||||||
|
g->strcache[i][j] = g->memerrmsg;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** creates a new string object
|
||||||
|
*/
|
||||||
|
static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) {
|
||||||
|
TString *ts;
|
||||||
|
GCObject *o;
|
||||||
|
size_t totalsize; /* total size of TString object */
|
||||||
|
totalsize = sizelstring(l);
|
||||||
|
o = luaC_newobj(L, tag, totalsize);
|
||||||
|
ts = gco2ts(o);
|
||||||
|
ts->hash = h;
|
||||||
|
ts->extra = 0;
|
||||||
|
#if defined(__LUATOS_SMALL_RAM__) && defined(__LUATOS_SCRIPT_BASE__)
|
||||||
|
ts->static_flag = 0;
|
||||||
|
#endif
|
||||||
|
char* ptr = getstr(ts);
|
||||||
|
ptr[l] = '\0'; /* ending 0 */
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
TString *luaS_createlngstrobj (lua_State *L, size_t l) {
|
||||||
|
TString *ts = createstrobj(L, l, LUA_TLNGSTR, G(L)->seed);
|
||||||
|
ts->u.lnglen = l;
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaS_remove (lua_State *L, TString *ts) {
|
||||||
|
stringtable *tb = &G(L)->strt;
|
||||||
|
TString **p = &tb->hash[lmod(ts->hash, tb->size)];
|
||||||
|
while (*p != ts) /* find previous element */
|
||||||
|
p = &(*p)->u.hnext;
|
||||||
|
*p = (*p)->u.hnext; /* remove element from its list */
|
||||||
|
tb->nuse--;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
** checks whether short string exists and reuses it or creates a new one
|
||||||
|
*/
|
||||||
|
static TString *internshrstr (lua_State *L, const char *str, size_t l) {
|
||||||
|
TString *ts;
|
||||||
|
global_State *g = G(L);
|
||||||
|
unsigned int h = luaS_hash(str, l, g->seed);
|
||||||
|
TString **list = &g->strt.hash[lmod(h, g->strt.size)];
|
||||||
|
lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */
|
||||||
|
for (ts = *list; ts != NULL; ts = ts->u.hnext) {
|
||||||
|
if (l == ts->shrlen &&
|
||||||
|
(memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
|
||||||
|
/* found! */
|
||||||
|
if (isdead(g, ts)) /* dead (but not collected yet)? */
|
||||||
|
changewhite(ts); /* resurrect it */
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2) {
|
||||||
|
luaS_resize(L, g->strt.size * 2);
|
||||||
|
list = &g->strt.hash[lmod(h, g->strt.size)]; /* recompute with new size */
|
||||||
|
}
|
||||||
|
ts = createstrobj(L, l, LUA_TSHRSTR, h);
|
||||||
|
memcpy(getstr(ts), str, l * sizeof(char));
|
||||||
|
ts->shrlen = cast_byte(l);
|
||||||
|
ts->u.hnext = *list;
|
||||||
|
*list = ts;
|
||||||
|
g->strt.nuse++;
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** new string (with explicit length)
|
||||||
|
*/
|
||||||
|
TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
|
||||||
|
if (l <= LUAI_MAXSHORTLEN) /* short string? */
|
||||||
|
return internshrstr(L, str, l);
|
||||||
|
else {
|
||||||
|
TString *ts;
|
||||||
|
if (l >= (MAX_SIZE - sizeof(TString))/sizeof(char))
|
||||||
|
luaM_toobig(L, l, sizeof(char), "long string");
|
||||||
|
ts = luaS_createlngstrobj(L, l);
|
||||||
|
memcpy(getstr(ts), str, l * sizeof(char));
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Create or reuse a zero-terminated string, first checking in the
|
||||||
|
** cache (using the string address as a key). The cache can contain
|
||||||
|
** only zero-terminated strings, so it is safe to use 'strcmp' to
|
||||||
|
** check hits.
|
||||||
|
*/
|
||||||
|
TString *luaS_new (lua_State *L, const char *str) {
|
||||||
|
unsigned int i = point2uint(str) % STRCACHE_N; /* hash */
|
||||||
|
int j;
|
||||||
|
TString **p = G(L)->strcache[i];
|
||||||
|
for (j = 0; j < STRCACHE_M; j++) {
|
||||||
|
if (strcmp(str, getstr(p[j])) == 0) /* hit? */
|
||||||
|
return p[j]; /* that is it */
|
||||||
|
}
|
||||||
|
/* normal route */
|
||||||
|
for (j = STRCACHE_M - 1; j > 0; j--)
|
||||||
|
p[j] = p[j - 1]; /* move out last element */
|
||||||
|
/* new element is first in the list */
|
||||||
|
p[0] = luaS_newlstr(L, str, strlen(str));
|
||||||
|
return p[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Udata *luaS_newudata (lua_State *L, size_t s) {
|
||||||
|
Udata *u;
|
||||||
|
GCObject *o;
|
||||||
|
if (s > MAX_SIZE - sizeof(Udata))
|
||||||
|
luaM_toobig(L, s, 1, "userdata");
|
||||||
|
o = luaC_newobj(L, LUA_TUSERDATA, sizeludata(s));
|
||||||
|
u = gco2u(o);
|
||||||
|
u->len = s;
|
||||||
|
u->metatable = NULL;
|
||||||
|
setuservalue(L, u, luaO_nilobject);
|
||||||
|
return u;
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,921 @@
|
|||||||
|
/*
|
||||||
|
@module string
|
||||||
|
@summary 字符串操作函数
|
||||||
|
@tag LUAT_USE_GPIO
|
||||||
|
@demo string
|
||||||
|
*/
|
||||||
|
#include "luat_base.h"
|
||||||
|
#include "luat_mem.h"
|
||||||
|
#include "lua.h"
|
||||||
|
#include "lauxlib.h"
|
||||||
|
|
||||||
|
#define LUAT_LOG_TAG "str"
|
||||||
|
#include "luat_log.h"
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
#define IsHex(c) (((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')))
|
||||||
|
#define IsDigit(c) ((c >= '0') && (c <= '9'))
|
||||||
|
|
||||||
|
static const unsigned char hexchars[] = "0123456789ABCDEF";
|
||||||
|
void luat_str_tohexwithsep(const char* str, size_t len, const char* separator, size_t len_j, char* buff) {
|
||||||
|
for (size_t i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
char ch = *(str+i);
|
||||||
|
buff[i*(2+len_j)] = hexchars[(unsigned char)ch >> 4];
|
||||||
|
buff[i*(2+len_j)+1] = hexchars[(unsigned char)ch & 0xF];
|
||||||
|
for (size_t j = 0; j < len_j; j++){
|
||||||
|
buff[i*(2+len_j)+2+j] = separator[j];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void luat_str_tohex(const char* str, size_t len, char* buff) {
|
||||||
|
luat_str_tohexwithsep(str, len, NULL, 0, buff);
|
||||||
|
}
|
||||||
|
|
||||||
|
void luat_str_fromhex(const char* str, size_t len, char* buff) {
|
||||||
|
for (size_t i = 0; i < len/2; i++)
|
||||||
|
{
|
||||||
|
char a = *(str + i*2);
|
||||||
|
char b = *(str + i*2 + 1);
|
||||||
|
//printf("%d %c %c\r\n", i, a, b);
|
||||||
|
a = (a <= '9') ? a - '0' : (a & 0x7) + 9;
|
||||||
|
b = (b <= '9') ? b - '0' : (b & 0x7) + 9;
|
||||||
|
buff[i] = (a << 4) + b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t luat_str_fromhex_ex(const char* str, size_t len, char* buff) {
|
||||||
|
size_t out_len = 0;
|
||||||
|
uint8_t temp = 0;
|
||||||
|
uint8_t is_full = 0;
|
||||||
|
uint8_t a;
|
||||||
|
for(size_t i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
a = str[i];
|
||||||
|
if (IsDigit(a)||IsHex(a))
|
||||||
|
{
|
||||||
|
if (is_full)
|
||||||
|
{
|
||||||
|
temp = (temp << 4) + ((a <= '9') ? a - '0' : (a & 0x7) + 9);
|
||||||
|
buff[out_len] = (char)temp;
|
||||||
|
out_len++;
|
||||||
|
temp = 0;
|
||||||
|
is_full = 0;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
temp = ((a <= '9') ? a - '0' : (a & 0x7) + 9);
|
||||||
|
is_full = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
temp = 0;
|
||||||
|
is_full = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out_len;
|
||||||
|
}
|
||||||
|
|
||||||
|
void luat_str_ucs2_to_char(char* source, size_t size, char* dst2, size_t* outlen) {
|
||||||
|
char *buff = (char *)luat_heap_malloc(size + 2);
|
||||||
|
memset(buff, 0, size + 2);
|
||||||
|
luat_str_fromhex(source, size, buff);
|
||||||
|
uint16_t* tmp = (uint16_t*)buff;
|
||||||
|
char* dst = dst2;
|
||||||
|
uint16_t unicode = 0;
|
||||||
|
size_t dstlen = 0;
|
||||||
|
while (1) {
|
||||||
|
unicode = *tmp ++;
|
||||||
|
unicode = ((unicode >> 8) & 0xFF) + ((unicode & 0xFF) << 8);
|
||||||
|
if (unicode == 0)
|
||||||
|
break; // 终止了
|
||||||
|
if (unicode <= 0x0000007F) {
|
||||||
|
dst[dstlen++] = (unicode & 0x7F);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (unicode <= 0x000007FF) {
|
||||||
|
dst[dstlen++] = ((unicode >> 6) & 0x1F) | 0xC0;
|
||||||
|
dst[dstlen++] = (unicode & 0x3F) | 0x80;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (unicode <= 0x0000FFFF) {
|
||||||
|
dst[dstlen++] = ((unicode >> 12) & 0x0F) | 0xE0;
|
||||||
|
dst[dstlen++] = ((unicode >> 6) & 0x3F) | 0x80;
|
||||||
|
dst[dstlen++] = (unicode & 0x3F) | 0x80;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
*outlen = dstlen;
|
||||||
|
luat_heap_free(buff);
|
||||||
|
}
|
||||||
|
|
||||||
|
int luat_str_utf8_to_ucs2(char* source, size_t source_len, char* dst, size_t dstlen, size_t* outlen) {
|
||||||
|
uint16_t unicode = 0;
|
||||||
|
size_t tmplen = 0;
|
||||||
|
for (size_t i = 0; i < source_len; i++)
|
||||||
|
{
|
||||||
|
if(tmplen >= dstlen) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
// 首先是不是单字节
|
||||||
|
if (source[i] & 0x80) {
|
||||||
|
// 非ASCII编码
|
||||||
|
if (source[i] & 0xE0) { // 1110xxxx 10xxxxxx 10xxxxxx
|
||||||
|
unicode = ((source[i] & 0x0F) << 12) + ((source[i+1] & 0x3F) << 6) + (source[i+2] & 0x3F);
|
||||||
|
dst[tmplen++] = (unicode >> 8) & 0xFF;
|
||||||
|
dst[tmplen++] = unicode & 0xFF;
|
||||||
|
i+=2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (source[i] & 0xC0) { // 110xxxxx 10xxxxxx
|
||||||
|
unicode = ((source[i] & 0x1F) << 6) + (source[i+1] & 0x3F);
|
||||||
|
dst[tmplen++] = (unicode >> 8) & 0xFF;
|
||||||
|
dst[tmplen++] = unicode & 0xFF;
|
||||||
|
i++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
// 单个ASCII字符, 但需要扩展到2位
|
||||||
|
else {
|
||||||
|
// ASCII编码
|
||||||
|
dst[tmplen++] = 0x00;
|
||||||
|
dst[tmplen++] = source[i];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*outlen = tmplen;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
将字符串转成HEX
|
||||||
|
@api string.toHex(str, separator)
|
||||||
|
@string 需要转换的字符串
|
||||||
|
@string 分隔符, 默认为""
|
||||||
|
@return string HEX字符串
|
||||||
|
@return number HEX字符串的长度
|
||||||
|
@usage
|
||||||
|
string.toHex("\1\2\3") --> "010203" 6
|
||||||
|
string.toHex("123abc") --> "313233616263" 12
|
||||||
|
string.toHex("123abc", " ") --> "31 32 33 61 62 63 " 12
|
||||||
|
*/
|
||||||
|
int l_str_toHex (lua_State *L) {
|
||||||
|
size_t len;
|
||||||
|
const char *str = luaL_checklstring(L, 1, &len);
|
||||||
|
size_t len_j;
|
||||||
|
const char *separator = luaL_optlstring(L, 2, "", &len_j);
|
||||||
|
luaL_Buffer buff;
|
||||||
|
luaL_buffinitsize(L, &buff, (2+len_j)*len);
|
||||||
|
luat_str_tohexwithsep(str, len, separator, len_j, buff.b);
|
||||||
|
buff.n = len * (2 + len_j);
|
||||||
|
luaL_pushresult(&buff);
|
||||||
|
lua_pushinteger(L, len*2);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
将HEX转成字符串
|
||||||
|
@api string.fromHex(hex)
|
||||||
|
@string hex,16进制组成的串
|
||||||
|
@return string 字符串
|
||||||
|
@usage
|
||||||
|
string.fromHex("010203") --> "\1\2\3"
|
||||||
|
string.fromHex("313233616263") --> "123abc"
|
||||||
|
*/
|
||||||
|
int l_str_fromHex (lua_State *L) {
|
||||||
|
size_t len;
|
||||||
|
const char *str = luaL_checklstring(L, 1, &len);
|
||||||
|
luaL_Buffer buff;
|
||||||
|
luaL_buffinitsize(L, &buff, len / 2);
|
||||||
|
// luat_str_fromhex((char*)str, len, buff.b);
|
||||||
|
// buff.n = len / 2;
|
||||||
|
buff.n = luat_str_fromhex_ex(str, len, buff.b);
|
||||||
|
luaL_pushresult(&buff);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
按照指定分隔符分割字符串
|
||||||
|
@api string.split(str, delimiter, keepEmtry)
|
||||||
|
@string 输入字符串
|
||||||
|
@string 分隔符,可选,默认 ","
|
||||||
|
@bool 是否保留空白片段,默认为false,不保留. 2023.4.11之后的固件可用
|
||||||
|
@return table 分割后的字符串表
|
||||||
|
@usage
|
||||||
|
local tmp = string.split("123,233333,122")
|
||||||
|
log.info("tmp", json.encode(tmp))
|
||||||
|
local tmp = ("123,456,789"):split(',') --> {'123','456','789'}
|
||||||
|
log.info("tmp", json.encode(tmp))
|
||||||
|
|
||||||
|
-- 保留空片段, 2023.4.11之后的固件可用
|
||||||
|
local str = "/tmp//def/1234/"
|
||||||
|
local tmp = str:split("/", true)
|
||||||
|
log.info("str.split", #tmp, json.encode(tmp))
|
||||||
|
*/
|
||||||
|
int l_str_split (lua_State *L) {
|
||||||
|
size_t len = 0;
|
||||||
|
int keepEmtry = 0;
|
||||||
|
const char *str = luaL_checklstring(L, 1, &len);
|
||||||
|
if (len == 0) {
|
||||||
|
lua_newtable(L);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t dlen = 0;
|
||||||
|
const char *delimiters = luaL_optlstring(L, 2, ",", &dlen);
|
||||||
|
if (dlen < 1) {
|
||||||
|
delimiters = ",";
|
||||||
|
dlen = 1;
|
||||||
|
}
|
||||||
|
if (lua_isboolean(L, 3) && lua_toboolean(L, 3)) {
|
||||||
|
keepEmtry = 1;
|
||||||
|
}
|
||||||
|
lua_newtable(L);
|
||||||
|
int prev = -1;
|
||||||
|
size_t count = 1;
|
||||||
|
for (size_t i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
// LLOGD("d[%s] [%.*s] %d", delimiters, dlen, str+i, dlen);
|
||||||
|
if (!memcmp(delimiters, str+i, dlen)) {
|
||||||
|
// LLOGD("match %d %i %d",prev, i, keepEmtry);
|
||||||
|
if ((prev+1) != i || (keepEmtry)) {
|
||||||
|
lua_pushinteger(L, count);
|
||||||
|
lua_pushlstring(L, str + prev + 1, i - prev - 1);
|
||||||
|
// LLOGD("add %d [%.*s]", count, i - prev, str+prev);
|
||||||
|
lua_settable(L, -3);
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
i += (dlen - 1);
|
||||||
|
prev = i;
|
||||||
|
if (i == len - 1 && keepEmtry) {
|
||||||
|
lua_pushinteger(L, count);
|
||||||
|
lua_pushlstring(L, "", 0);
|
||||||
|
lua_settable(L, -3);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (i == len - 1) {
|
||||||
|
// 最后一个字符了
|
||||||
|
lua_pushinteger(L, count);
|
||||||
|
lua_pushlstring(L, str + prev + 1, len - prev - 1);
|
||||||
|
lua_settable(L, -3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
返回字符串tonumber的转义字符串(用来支持超过31位整数的转换)
|
||||||
|
@api string.toValue(str)
|
||||||
|
@string 输入字符串
|
||||||
|
@return string 转换后的二进制字符串
|
||||||
|
@return number 转换了多少个字符
|
||||||
|
@usage
|
||||||
|
string.toValue("123456") --> "\1\2\3\4\5\6" 6
|
||||||
|
string.toValue("123abc") --> "\1\2\3\a\b\c" 6
|
||||||
|
*/
|
||||||
|
int l_str_toValue (lua_State *L) {
|
||||||
|
size_t len = 0,i;
|
||||||
|
const char *s = luaL_checklstring(L, 1, &len);
|
||||||
|
if(len == 0)//没字符串
|
||||||
|
{
|
||||||
|
lua_pushlstring(L,NULL,0);
|
||||||
|
lua_pushinteger(L,0);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
luaL_Buffer buff;
|
||||||
|
luaL_buffinitsize(L, &buff, len);
|
||||||
|
char * stemp;
|
||||||
|
for(i=0;i<len;i++)
|
||||||
|
{
|
||||||
|
stemp = (char *)s + i;
|
||||||
|
luaL_addchar(&buff, (*stemp>'9'? *stemp+9 : *stemp) & 0x0f);
|
||||||
|
}
|
||||||
|
luaL_pushresult(&buff);
|
||||||
|
lua_pushinteger(L,len);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
将字符串进行url编码转换
|
||||||
|
@api string.urlEncode(data,mode,space,str_check)
|
||||||
|
@string 需要转换的字符串,必须填
|
||||||
|
@int url编码的转换标准,默认0, PHP标准, 1是RFC3986标准, -1是自定义标准
|
||||||
|
@int 空格的处理方式 0:' '转化为'+' 1:' '转换为"%20". 仅mode为-1时有效
|
||||||
|
@string str_check:不需要转换的字符,组成的字符串. 仅mode为-1时有效
|
||||||
|
@return string 返回转换后的字符串
|
||||||
|
@usage
|
||||||
|
-- mode可选值
|
||||||
|
-1 :自定义标准.为-1时,才会有后面的space和str_check
|
||||||
|
0 :默认标准php
|
||||||
|
1 :RFC3986标准,和默认的相比就是' '的转换方式不一样
|
||||||
|
这个参数不存在,按0:默认标准php处理
|
||||||
|
|
||||||
|
-- 将字符串进行url编码转换
|
||||||
|
log.info(string.urlEncode("123 abc+/")) -->> "123+abc%2B%2F"
|
||||||
|
|
||||||
|
log.info(string.urlEncode("123 abc+/",1)) -->> "123%20abc%2B%2F"
|
||||||
|
|
||||||
|
log.info(string.urlEncode("123 abc+/",-1,1,"/")) -->> "123%20abc%2B/"
|
||||||
|
log.info(string.urlEncode("123 abc+/",-1,0,"/")) -->> "123+abc%2B/"
|
||||||
|
log.info(string.urlEncode("123 abc+/",-1,0,"/ ")) -->> "123 abc%2B/"
|
||||||
|
*/
|
||||||
|
int l_str_urlEncode (lua_State *L) {
|
||||||
|
int argc = lua_gettop(L);
|
||||||
|
int mode = 0; //转换模式,-1:自定义标准,0:默认标准php,1:RFC3986标准,和默认的相比就是' '的转换方式不一样
|
||||||
|
int space = 0; //0:' '转化为'+', 1:' '转换为"%20"
|
||||||
|
size_t len_check = 0;
|
||||||
|
const char *str_check = NULL; //不需要转换的字符
|
||||||
|
size_t len = 0;
|
||||||
|
const char *str = luaL_checklstring(L, 1, &len);
|
||||||
|
if(argc == 1)
|
||||||
|
{
|
||||||
|
mode = 0;
|
||||||
|
}
|
||||||
|
else{
|
||||||
|
mode = luaL_checkinteger(L, 2);
|
||||||
|
}
|
||||||
|
if(mode == -1)
|
||||||
|
{
|
||||||
|
/* 自定义模式 */
|
||||||
|
space = luaL_checkinteger(L, 3);
|
||||||
|
str_check = luaL_checklstring(L, 4, &len_check);
|
||||||
|
}
|
||||||
|
if(mode == 1)
|
||||||
|
{
|
||||||
|
/* RFC3986 */
|
||||||
|
space = 1;
|
||||||
|
str_check = ".-_";
|
||||||
|
len_check = 3;
|
||||||
|
}
|
||||||
|
luaL_Buffer buff;
|
||||||
|
luaL_buffinitsize(L, &buff, len + 16);
|
||||||
|
if(str_check == NULL)
|
||||||
|
{
|
||||||
|
str_check = ".-*_";
|
||||||
|
len_check = 4;
|
||||||
|
}
|
||||||
|
for (size_t i = 0; i < len; i++)
|
||||||
|
{
|
||||||
|
char ch = *(str+i);
|
||||||
|
if((ch >= 'A' && ch <= 'Z') ||
|
||||||
|
(ch >= 'a' && ch <= 'z') ||
|
||||||
|
(ch >= '0' && ch <= '9')) {
|
||||||
|
luaL_addchar(&buff, ch);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
char result = 0;
|
||||||
|
for(size_t j = 0; j < len_check; j++)
|
||||||
|
{
|
||||||
|
if(ch == str_check[j])
|
||||||
|
{
|
||||||
|
result = 1;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(result == 1)
|
||||||
|
{
|
||||||
|
luaL_addchar(&buff, str[i]);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if(ch == ' ')
|
||||||
|
{
|
||||||
|
if(space == 0)
|
||||||
|
{
|
||||||
|
luaL_addchar(&buff, '+');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
luaL_addchar(&buff, '%');
|
||||||
|
luaL_addchar(&buff, hexchars[(unsigned char)str[i] >> 4]);
|
||||||
|
luaL_addchar(&buff, hexchars[(unsigned char)str[i] & 0x0F]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
luaL_pushresult(&buff);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------
|
||||||
|
// Base64
|
||||||
|
//-----------------------------------------------------------
|
||||||
|
|
||||||
|
static const unsigned char base64_enc_map[64] =
|
||||||
|
{
|
||||||
|
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
|
||||||
|
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
|
||||||
|
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
|
||||||
|
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
|
||||||
|
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
|
||||||
|
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
|
||||||
|
'8', '9', '+', '/'
|
||||||
|
};
|
||||||
|
|
||||||
|
static const unsigned char base64_dec_map[128] =
|
||||||
|
{
|
||||||
|
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
|
||||||
|
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
|
||||||
|
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
|
||||||
|
127, 127, 127, 127, 127, 127, 127, 127, 127, 127,
|
||||||
|
127, 127, 127, 62, 127, 127, 127, 63, 52, 53,
|
||||||
|
54, 55, 56, 57, 58, 59, 60, 61, 127, 127,
|
||||||
|
127, 64, 127, 127, 127, 0, 1, 2, 3, 4,
|
||||||
|
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
|
||||||
|
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||||
|
25, 127, 127, 127, 127, 127, 127, 26, 27, 28,
|
||||||
|
29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
|
||||||
|
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
|
||||||
|
49, 50, 51, 127, 127, 127, 127, 127
|
||||||
|
};
|
||||||
|
|
||||||
|
#define BASE64_SIZE_T_MAX ( (size_t) -1 ) /* SIZE_T_MAX is not standard */
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Encode a buffer into base64 format
|
||||||
|
*/
|
||||||
|
int luat_str_base64_encode( unsigned char *dst, size_t dlen, size_t *olen,
|
||||||
|
const unsigned char *src, size_t slen )
|
||||||
|
{
|
||||||
|
size_t i, n;
|
||||||
|
int C1, C2, C3;
|
||||||
|
unsigned char *p;
|
||||||
|
|
||||||
|
if( slen == 0 )
|
||||||
|
{
|
||||||
|
*olen = 0;
|
||||||
|
return( 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
n = slen / 3 + ( slen % 3 != 0 );
|
||||||
|
|
||||||
|
if( n > ( BASE64_SIZE_T_MAX - 1 ) / 4 )
|
||||||
|
{
|
||||||
|
*olen = BASE64_SIZE_T_MAX;
|
||||||
|
return( -1 );
|
||||||
|
}
|
||||||
|
|
||||||
|
n *= 4;
|
||||||
|
|
||||||
|
if( ( dlen < n + 1 ) || ( NULL == dst ) )
|
||||||
|
{
|
||||||
|
*olen = n + 1;
|
||||||
|
return( -1 );
|
||||||
|
}
|
||||||
|
|
||||||
|
n = ( slen / 3 ) * 3;
|
||||||
|
|
||||||
|
for( i = 0, p = dst; i < n; i += 3 )
|
||||||
|
{
|
||||||
|
C1 = *src++;
|
||||||
|
C2 = *src++;
|
||||||
|
C3 = *src++;
|
||||||
|
|
||||||
|
*p++ = base64_enc_map[(C1 >> 2) & 0x3F];
|
||||||
|
*p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];
|
||||||
|
*p++ = base64_enc_map[(((C2 & 15) << 2) + (C3 >> 6)) & 0x3F];
|
||||||
|
*p++ = base64_enc_map[C3 & 0x3F];
|
||||||
|
}
|
||||||
|
|
||||||
|
if( i < slen )
|
||||||
|
{
|
||||||
|
C1 = *src++;
|
||||||
|
C2 = ( ( i + 1 ) < slen ) ? *src++ : 0;
|
||||||
|
|
||||||
|
*p++ = base64_enc_map[(C1 >> 2) & 0x3F];
|
||||||
|
*p++ = base64_enc_map[(((C1 & 3) << 4) + (C2 >> 4)) & 0x3F];
|
||||||
|
|
||||||
|
if( ( i + 1 ) < slen )
|
||||||
|
*p++ = base64_enc_map[((C2 & 15) << 2) & 0x3F];
|
||||||
|
else *p++ = '=';
|
||||||
|
|
||||||
|
*p++ = '=';
|
||||||
|
}
|
||||||
|
|
||||||
|
*olen = p - dst;
|
||||||
|
*p = 0;
|
||||||
|
|
||||||
|
return( 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Decode a base64-formatted buffer
|
||||||
|
*/
|
||||||
|
#ifndef uint32_t
|
||||||
|
#define uint32_t unsigned int
|
||||||
|
#endif
|
||||||
|
int luat_str_base64_decode( unsigned char *dst, size_t dlen, size_t *olen,
|
||||||
|
const unsigned char *src, size_t slen )
|
||||||
|
{
|
||||||
|
size_t i, n;
|
||||||
|
uint32_t j, x;
|
||||||
|
unsigned char *p;
|
||||||
|
|
||||||
|
/* First pass: check for validity and get output length */
|
||||||
|
for( i = n = j = 0; i < slen; i++ )
|
||||||
|
{
|
||||||
|
/* Skip spaces before checking for EOL */
|
||||||
|
x = 0;
|
||||||
|
while( i < slen && src[i] == ' ' )
|
||||||
|
{
|
||||||
|
++i;
|
||||||
|
++x;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Spaces at end of buffer are OK */
|
||||||
|
if( i == slen )
|
||||||
|
break;
|
||||||
|
|
||||||
|
if( ( slen - i ) >= 2 &&
|
||||||
|
src[i] == '\r' && src[i + 1] == '\n' )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
if( src[i] == '\n' )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
/* Space inside a line is an error */
|
||||||
|
if( x != 0 )
|
||||||
|
return( -2 );
|
||||||
|
|
||||||
|
if( src[i] == '=' && ++j > 2 )
|
||||||
|
return( -2 );
|
||||||
|
|
||||||
|
if( src[i] > 127 || base64_dec_map[src[i]] == 127 )
|
||||||
|
return( -2 );
|
||||||
|
|
||||||
|
if( base64_dec_map[src[i]] < 64 && j != 0 )
|
||||||
|
return( -2 );
|
||||||
|
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if( n == 0 )
|
||||||
|
{
|
||||||
|
*olen = 0;
|
||||||
|
return( 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The following expression is to calculate the following formula without
|
||||||
|
* risk of integer overflow in n:
|
||||||
|
* n = ( ( n * 6 ) + 7 ) >> 3;
|
||||||
|
*/
|
||||||
|
n = ( 6 * ( n >> 3 ) ) + ( ( 6 * ( n & 0x7 ) + 7 ) >> 3 );
|
||||||
|
n -= j;
|
||||||
|
|
||||||
|
if( dst == NULL || dlen < n )
|
||||||
|
{
|
||||||
|
*olen = n;
|
||||||
|
return( -1 );
|
||||||
|
}
|
||||||
|
|
||||||
|
for( j = 3, n = x = 0, p = dst; i > 0; i--, src++ )
|
||||||
|
{
|
||||||
|
if( *src == '\r' || *src == '\n' || *src == ' ' )
|
||||||
|
continue;
|
||||||
|
|
||||||
|
j -= ( base64_dec_map[*src] == 64 );
|
||||||
|
x = ( x << 6 ) | ( base64_dec_map[*src] & 0x3F );
|
||||||
|
|
||||||
|
if( ++n == 4 )
|
||||||
|
{
|
||||||
|
n = 0;
|
||||||
|
if( j > 0 ) *p++ = (unsigned char)( x >> 16 );
|
||||||
|
if( j > 1 ) *p++ = (unsigned char)( x >> 8 );
|
||||||
|
if( j > 2 ) *p++ = (unsigned char)( x );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
*olen = p - dst;
|
||||||
|
|
||||||
|
return( 0 );
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
将字符串进行base64编码
|
||||||
|
@api string.toBase64(str)
|
||||||
|
@string 需要转换的字符串
|
||||||
|
@return string 解码后的字符串,如果解码失败会返回空字符串
|
||||||
|
*/
|
||||||
|
int l_str_toBase64(lua_State *L) {
|
||||||
|
size_t len = 0;
|
||||||
|
const char* str = luaL_checklstring(L, 1, &len);
|
||||||
|
if (len == 0) {
|
||||||
|
lua_pushstring(L, "");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
luaL_Buffer buff = {0};
|
||||||
|
luaL_buffinitsize(L, &buff, len * 1.5 + 1);
|
||||||
|
size_t olen = 0;
|
||||||
|
int re = luat_str_base64_encode((unsigned char *)buff.b, buff.size, &olen, (const unsigned char * )str, len);
|
||||||
|
if (re == 0) {
|
||||||
|
luaL_pushresultsize(&buff, olen);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
// 编码失败,返回空字符串, 可能性应该是0吧
|
||||||
|
lua_pushstring(L, "");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
将字符串进行base64解码
|
||||||
|
@api string.fromBase64(str)
|
||||||
|
@string 需要转换的字符串
|
||||||
|
@return string 解码后的字符串,如果解码失败会返回空字符串
|
||||||
|
*/
|
||||||
|
int l_str_fromBase64(lua_State *L) {
|
||||||
|
size_t len = 0;
|
||||||
|
const char* str = luaL_checklstring(L, 1, &len);
|
||||||
|
if (len == 0) {
|
||||||
|
lua_pushstring(L, "");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
luaL_Buffer buff = {0};
|
||||||
|
luaL_buffinitsize(L, &buff, len + 1);
|
||||||
|
size_t olen = 0;
|
||||||
|
int re = luat_str_base64_decode((unsigned char *)buff.b, buff.size, &olen, (const unsigned char * )str, len);
|
||||||
|
if (re == 0) {
|
||||||
|
luaL_pushresultsize(&buff, olen);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
// 编码失败,返回空字符串, 可能性应该是0吧
|
||||||
|
lua_pushstring(L, "");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////////////////////////////////
|
||||||
|
//// BASE32 /////
|
||||||
|
////////////////////////////////////////////
|
||||||
|
// Copyright 2010 Google Inc.
|
||||||
|
// Author: Markus Gutschke
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
int luat_str_base32_decode(const uint8_t *encoded, uint8_t *result, int bufSize) {
|
||||||
|
int buffer = 0;
|
||||||
|
int bitsLeft = 0;
|
||||||
|
int count = 0;
|
||||||
|
for (const uint8_t *ptr = encoded; count < bufSize && *ptr; ++ptr) {
|
||||||
|
uint8_t ch = *ptr;
|
||||||
|
if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
buffer <<= 5;
|
||||||
|
|
||||||
|
// Deal with commonly mistyped characters
|
||||||
|
if (ch == '0') {
|
||||||
|
ch = 'O';
|
||||||
|
} else if (ch == '1') {
|
||||||
|
ch = 'L';
|
||||||
|
} else if (ch == '8') {
|
||||||
|
ch = 'B';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Look up one base32 digit
|
||||||
|
if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
|
||||||
|
ch = (ch & 0x1F) - 1;
|
||||||
|
} else if (ch >= '2' && ch <= '7') {
|
||||||
|
ch -= '2' - 26;
|
||||||
|
} else {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer |= ch;
|
||||||
|
bitsLeft += 5;
|
||||||
|
if (bitsLeft >= 8) {
|
||||||
|
result[count++] = buffer >> (bitsLeft - 8);
|
||||||
|
bitsLeft -= 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (count < bufSize) {
|
||||||
|
result[count] = '\000';
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
int luat_str_base32_encode(const uint8_t *data, int length, uint8_t *result,
|
||||||
|
int bufSize) {
|
||||||
|
if (length < 0 || length > (1 << 28)) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
int count = 0;
|
||||||
|
if (length > 0) {
|
||||||
|
int buffer = data[0];
|
||||||
|
int next = 1;
|
||||||
|
int bitsLeft = 8;
|
||||||
|
while (count < bufSize && (bitsLeft > 0 || next < length)) {
|
||||||
|
if (bitsLeft < 5) {
|
||||||
|
if (next < length) {
|
||||||
|
buffer <<= 8;
|
||||||
|
buffer |= data[next++] & 0xFF;
|
||||||
|
bitsLeft += 8;
|
||||||
|
} else {
|
||||||
|
int pad = 5 - bitsLeft;
|
||||||
|
buffer <<= pad;
|
||||||
|
bitsLeft += pad;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int index = 0x1F & (buffer >> (bitsLeft - 5));
|
||||||
|
bitsLeft -= 5;
|
||||||
|
result[count++] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[index];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (count < bufSize) {
|
||||||
|
result[count] = '\000';
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
将字符串进行base32编码
|
||||||
|
@api string.toBase32(str)
|
||||||
|
@string 需要转换的字符串
|
||||||
|
@return string 解码后的字符串,如果解码失败会返回0长度字符串
|
||||||
|
*/
|
||||||
|
int l_str_toBase32(lua_State *L) {
|
||||||
|
size_t len = 0;
|
||||||
|
const char* str = luaL_checklstring(L, 1, &len);
|
||||||
|
if (len == 0) {
|
||||||
|
lua_pushstring(L, "");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
luaL_Buffer buff = {0};
|
||||||
|
luaL_buffinitsize(L, &buff, len * 2);
|
||||||
|
int rl = luat_str_base32_encode((const uint8_t * )str,len,(uint8_t *)buff.b,buff.size);
|
||||||
|
luaL_pushresultsize(&buff, rl);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
将字符串进行base32解码
|
||||||
|
@api string.fromBase32(str)
|
||||||
|
@string 需要转换的字符串
|
||||||
|
@return string 解码后的字符串,如果解码失败会返回0长度字符串
|
||||||
|
*/
|
||||||
|
int l_str_fromBase32(lua_State *L) {
|
||||||
|
size_t len = 0;
|
||||||
|
const char* str = luaL_checklstring(L, 1, &len);
|
||||||
|
if (len == 0) {
|
||||||
|
lua_pushstring(L, "");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
luaL_Buffer buff = {0};
|
||||||
|
luaL_buffinitsize(L, &buff, len + 1);
|
||||||
|
int rl = luat_str_base32_decode((const uint8_t * )str,(uint8_t *)buff.b,buff.size);
|
||||||
|
if (rl > 0 && rl <= len + 1) {
|
||||||
|
luaL_pushresultsize(&buff, rl);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushstring(L, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
判断字符串前缀
|
||||||
|
@api string.startsWith(str, prefix)
|
||||||
|
@string 需要检查的字符串
|
||||||
|
@string 前缀字符串
|
||||||
|
@return bool 真为true, 假为false
|
||||||
|
@usage
|
||||||
|
local str = "abc"
|
||||||
|
log.info("str", str:startsWith("a"))
|
||||||
|
log.info("str", str:startsWith("b"))
|
||||||
|
*/
|
||||||
|
int l_str_startsWith(lua_State *L) {
|
||||||
|
size_t str_len = 0;
|
||||||
|
size_t prefix_len = 0;
|
||||||
|
const char* str = luaL_checklstring(L, 1, &str_len);
|
||||||
|
const char* prefix = luaL_checklstring(L, 2, &prefix_len);
|
||||||
|
|
||||||
|
if (str_len < prefix_len) {
|
||||||
|
lua_pushboolean(L, 0);
|
||||||
|
}
|
||||||
|
else if (memcmp(str, prefix, prefix_len) == 0) {
|
||||||
|
lua_pushboolean(L, 1);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushboolean(L, 0);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
判断字符串后缀
|
||||||
|
@api string.endsWith(str, suffix)
|
||||||
|
@string 需要检查的字符串
|
||||||
|
@string 后缀字符串
|
||||||
|
@return bool 真为true, 假为false
|
||||||
|
@usage
|
||||||
|
local str = "abc"
|
||||||
|
log.info("str", str:endsWith("c"))
|
||||||
|
log.info("str", str:endsWith("b"))
|
||||||
|
*/
|
||||||
|
int l_str_endsWith(lua_State *L) {
|
||||||
|
size_t str_len = 0;
|
||||||
|
size_t suffix_len = 0;
|
||||||
|
const char* str = luaL_checklstring(L, 1, &str_len);
|
||||||
|
const char* suffix = luaL_checklstring(L, 2, &suffix_len);
|
||||||
|
|
||||||
|
// LLOGD("%s %d : %s %d", str, str_len, suffix, suffix_len);
|
||||||
|
|
||||||
|
if (str_len < suffix_len) {
|
||||||
|
lua_pushboolean(L, 0);
|
||||||
|
}
|
||||||
|
else if (memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0) {
|
||||||
|
lua_pushboolean(L, 1);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushboolean(L, 0);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#include "lstate.h"
|
||||||
|
|
||||||
|
int l_str_strs(lua_State *L) {
|
||||||
|
for (size_t i = 0; i < STRCACHE_N; i++)
|
||||||
|
{
|
||||||
|
TString **p = G(L)->strcache[i];
|
||||||
|
for (size_t j = 0; j < STRCACHE_M; j++) {
|
||||||
|
if (p[j]->tt == LUA_TSHRSTR)
|
||||||
|
LLOGD(">> %s", getstr(p[j]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int l_str_trim_impl(lua_State *L, int ltrim, int rtrim) {
|
||||||
|
size_t str_len = 0;
|
||||||
|
const char* str = luaL_checklstring(L, 1, &str_len);
|
||||||
|
if (str_len == 0) {
|
||||||
|
lua_pushvalue(L, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
int begin = 0;
|
||||||
|
int end = str_len;
|
||||||
|
if (ltrim) {
|
||||||
|
for (; begin <= end; begin++)
|
||||||
|
{
|
||||||
|
//LLOGD("ltrim %02X %d %d", str[begin], begin, end);
|
||||||
|
if(str[begin] != ' ' &&
|
||||||
|
str[begin] != '\t' &&
|
||||||
|
str[begin] != '\n' &&
|
||||||
|
str[begin] != '\r')
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rtrim) {
|
||||||
|
for (; begin < end; end--)
|
||||||
|
{
|
||||||
|
//LLOGD("rtrim %02X %d %d", str[end], begin, end);
|
||||||
|
if(str[end - 1] != ' ' &&
|
||||||
|
str[end - 1] != '\t' &&
|
||||||
|
str[end - 1] != '\n' &&
|
||||||
|
str[end - 1] != '\r')
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (begin == end) {
|
||||||
|
lua_pushliteral(L, "");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushlstring(L, str + begin, end - begin);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
裁剪字符串,去除头尾的空格
|
||||||
|
@api string.trim(str, ltrim, rtrim)
|
||||||
|
@string 需要处理的字符串
|
||||||
|
@bool 清理前缀,默认为true
|
||||||
|
@bool 清理后缀,默认为true
|
||||||
|
@return string 清理后的字符串
|
||||||
|
@usage
|
||||||
|
local str = "\r\nabc\r\n"
|
||||||
|
log.info("str", string.trim(str)) -- 打印 "abc"
|
||||||
|
log.info("str", str:trim()) -- 打印 "abc"
|
||||||
|
log.info("str", #string.trim(str, false, true)) -- 仅裁剪后缀,所以长度是5
|
||||||
|
*/
|
||||||
|
int l_str_trim(lua_State *L) {
|
||||||
|
int ltrim = 1;
|
||||||
|
int rtrim = 1;
|
||||||
|
if (lua_isboolean(L, 2))
|
||||||
|
ltrim = lua_toboolean(L, 2);
|
||||||
|
if (lua_isboolean(L, 3))
|
||||||
|
rtrim = lua_toboolean(L, 3);
|
||||||
|
|
||||||
|
return l_str_trim_impl(L, ltrim, rtrim);
|
||||||
|
}
|
||||||
@@ -0,0 +1,688 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ltable.c,v 2.118.1.4 2018/06/08 16:22:51 roberto Exp $
|
||||||
|
** Lua tables (hash)
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define ltable_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Implementation of tables (aka arrays, objects, or hash tables).
|
||||||
|
** Tables keep its elements in two parts: an array part and a hash part.
|
||||||
|
** Non-negative integer keys are all candidates to be kept in the array
|
||||||
|
** part. The actual size of the array is the largest 'n' such that
|
||||||
|
** more than half the slots between 1 and n are in use.
|
||||||
|
** Hash uses a mix of chained scatter table with Brent's variation.
|
||||||
|
** A main invariant of these tables is that, if an element is not
|
||||||
|
** in its main position (i.e. the 'original' position that its hash gives
|
||||||
|
** to it), then the colliding element is in its own main position.
|
||||||
|
** Hence even when the load factor reaches 100%, performance remains good.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <math.h>
|
||||||
|
#include <limits.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lgc.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
#include "ltable.h"
|
||||||
|
#include "lvm.h"
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is
|
||||||
|
** the largest integer such that MAXASIZE fits in an unsigned int.
|
||||||
|
*/
|
||||||
|
#define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1)
|
||||||
|
#define MAXASIZE (1u << MAXABITS)
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Maximum size of hash part is 2^MAXHBITS. MAXHBITS is the largest
|
||||||
|
** integer such that 2^MAXHBITS fits in a signed int. (Note that the
|
||||||
|
** maximum number of elements in a table, 2^MAXABITS + 2^MAXHBITS, still
|
||||||
|
** fits comfortably in an unsigned int.)
|
||||||
|
*/
|
||||||
|
#define MAXHBITS (MAXABITS - 1)
|
||||||
|
|
||||||
|
|
||||||
|
#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
|
||||||
|
|
||||||
|
#define hashstr(t,str) hashpow2(t, (str)->hash)
|
||||||
|
#define hashboolean(t,p) hashpow2(t, p)
|
||||||
|
#define hashint(t,i) hashpow2(t, i)
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** for some types, it is better to avoid modulus by power of 2, as
|
||||||
|
** they tend to have many 2 factors.
|
||||||
|
*/
|
||||||
|
#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
|
||||||
|
|
||||||
|
|
||||||
|
#define hashpointer(t,p) hashmod(t, point2uint(p))
|
||||||
|
|
||||||
|
|
||||||
|
#define dummynode (&dummynode_)
|
||||||
|
|
||||||
|
static const Node dummynode_ = {
|
||||||
|
{NILCONSTANT}, /* value */
|
||||||
|
{{NILCONSTANT, 0}} /* key */
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Hash for floating-point numbers.
|
||||||
|
** The main computation should be just
|
||||||
|
** n = frexp(n, &i); return (n * INT_MAX) + i
|
||||||
|
** but there are some numerical subtleties.
|
||||||
|
** In a two-complement representation, INT_MAX does not has an exact
|
||||||
|
** representation as a float, but INT_MIN does; because the absolute
|
||||||
|
** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the
|
||||||
|
** absolute value of the product 'frexp * -INT_MIN' is smaller or equal
|
||||||
|
** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when
|
||||||
|
** adding 'i'; the use of '~u' (instead of '-u') avoids problems with
|
||||||
|
** INT_MIN.
|
||||||
|
*/
|
||||||
|
#if !defined(l_hashfloat)
|
||||||
|
static int l_hashfloat (lua_Number n) {
|
||||||
|
int i;
|
||||||
|
lua_Integer ni;
|
||||||
|
n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN);
|
||||||
|
if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */
|
||||||
|
lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
else { /* normal case */
|
||||||
|
unsigned int u = cast(unsigned int, i) + cast(unsigned int, ni);
|
||||||
|
return cast_int(u <= cast(unsigned int, INT_MAX) ? u : ~u);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** returns the 'main' position of an element in a table (that is, the index
|
||||||
|
** of its hash value)
|
||||||
|
*/
|
||||||
|
static Node *mainposition (const Table *t, const TValue *key) {
|
||||||
|
switch (ttype(key)) {
|
||||||
|
case LUA_TNUMINT:
|
||||||
|
return hashint(t, ivalue(key));
|
||||||
|
case LUA_TNUMFLT:
|
||||||
|
return hashmod(t, l_hashfloat(fltvalue(key)));
|
||||||
|
case LUA_TSHRSTR:
|
||||||
|
return hashstr(t, tsvalue(key));
|
||||||
|
case LUA_TLNGSTR:
|
||||||
|
return hashpow2(t, luaS_hashlongstr(tsvalue(key)));
|
||||||
|
case LUA_TBOOLEAN:
|
||||||
|
return hashboolean(t, bvalue(key));
|
||||||
|
case LUA_TLIGHTUSERDATA:
|
||||||
|
return hashpointer(t, pvalue(key));
|
||||||
|
case LUA_TLCF:
|
||||||
|
return hashpointer(t, fvalue(key));
|
||||||
|
default:
|
||||||
|
lua_assert(!ttisdeadkey(key));
|
||||||
|
return hashpointer(t, gcvalue(key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** returns the index for 'key' if 'key' is an appropriate key to live in
|
||||||
|
** the array part of the table, 0 otherwise.
|
||||||
|
*/
|
||||||
|
static unsigned int arrayindex (const TValue *key) {
|
||||||
|
if (ttisinteger(key)) {
|
||||||
|
lua_Integer k = ivalue(key);
|
||||||
|
if (0 < k && (lua_Unsigned)k <= MAXASIZE)
|
||||||
|
return cast(unsigned int, k); /* 'key' is an appropriate array index */
|
||||||
|
}
|
||||||
|
return 0; /* 'key' did not match some condition */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** returns the index of a 'key' for table traversals. First goes all
|
||||||
|
** elements in the array part, then elements in the hash part. The
|
||||||
|
** beginning of a traversal is signaled by 0.
|
||||||
|
*/
|
||||||
|
static unsigned int findindex (lua_State *L, Table *t, StkId key) {
|
||||||
|
unsigned int i;
|
||||||
|
if (ttisnil(key)) return 0; /* first iteration */
|
||||||
|
i = arrayindex(key);
|
||||||
|
if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */
|
||||||
|
return i; /* yes; that's the index */
|
||||||
|
else {
|
||||||
|
int nx;
|
||||||
|
Node *n = mainposition(t, key);
|
||||||
|
for (;;) { /* check whether 'key' is somewhere in the chain */
|
||||||
|
/* key may be dead already, but it is ok to use it in 'next' */
|
||||||
|
if (luaV_rawequalobj(gkey(n), key) ||
|
||||||
|
(ttisdeadkey(gkey(n)) && iscollectable(key) &&
|
||||||
|
deadvalue(gkey(n)) == gcvalue(key))) {
|
||||||
|
i = cast_int(n - gnode(t, 0)); /* key index in hash table */
|
||||||
|
/* hash elements are numbered after array ones */
|
||||||
|
return (i + 1) + t->sizearray;
|
||||||
|
}
|
||||||
|
nx = gnext(n);
|
||||||
|
if (nx == 0)
|
||||||
|
luaG_runerror(L, "invalid key to 'next'"); /* key not found */
|
||||||
|
else n += nx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaH_next (lua_State *L, Table *t, StkId key) {
|
||||||
|
unsigned int i = findindex(L, t, key); /* find original element */
|
||||||
|
for (; i < t->sizearray; i++) { /* try first array part */
|
||||||
|
if (!ttisnil(&t->array[i])) { /* a non-nil value? */
|
||||||
|
setivalue(key, i + 1);
|
||||||
|
setobj2s(L, key+1, &t->array[i]);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) { /* hash part */
|
||||||
|
if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
|
||||||
|
setobj2s(L, key, gkey(gnode(t, i)));
|
||||||
|
setobj2s(L, key+1, gval(gnode(t, i)));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0; /* no more elements */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** {=============================================================
|
||||||
|
** Rehash
|
||||||
|
** ==============================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Compute the optimal size for the array part of table 't'. 'nums' is a
|
||||||
|
** "count array" where 'nums[i]' is the number of integers in the table
|
||||||
|
** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of
|
||||||
|
** integer keys in the table and leaves with the number of keys that
|
||||||
|
** will go to the array part; return the optimal size.
|
||||||
|
*/
|
||||||
|
static unsigned int computesizes (unsigned int nums[], unsigned int *pna) {
|
||||||
|
int i;
|
||||||
|
unsigned int twotoi; /* 2^i (candidate for optimal size) */
|
||||||
|
unsigned int a = 0; /* number of elements smaller than 2^i */
|
||||||
|
unsigned int na = 0; /* number of elements to go to array part */
|
||||||
|
unsigned int optimal = 0; /* optimal size for array part */
|
||||||
|
/* loop while keys can fill more than half of total size */
|
||||||
|
for (i = 0, twotoi = 1;
|
||||||
|
twotoi > 0 && *pna > twotoi / 2;
|
||||||
|
i++, twotoi *= 2) {
|
||||||
|
if (nums[i] > 0) {
|
||||||
|
a += nums[i];
|
||||||
|
if (a > twotoi/2) { /* more than half elements present? */
|
||||||
|
optimal = twotoi; /* optimal size (till now) */
|
||||||
|
na = a; /* all elements up to 'optimal' will go to array part */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal);
|
||||||
|
*pna = na;
|
||||||
|
return optimal;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int countint (const TValue *key, unsigned int *nums) {
|
||||||
|
unsigned int k = arrayindex(key);
|
||||||
|
if (k != 0) { /* is 'key' an appropriate array index? */
|
||||||
|
nums[luaO_ceillog2(k)]++; /* count as such */
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Count keys in array part of table 't': Fill 'nums[i]' with
|
||||||
|
** number of keys that will go into corresponding slice and return
|
||||||
|
** total number of non-nil keys.
|
||||||
|
*/
|
||||||
|
static unsigned int numusearray (const Table *t, unsigned int *nums) {
|
||||||
|
int lg;
|
||||||
|
unsigned int ttlg; /* 2^lg */
|
||||||
|
unsigned int ause = 0; /* summation of 'nums' */
|
||||||
|
unsigned int i = 1; /* count to traverse all array keys */
|
||||||
|
/* traverse each slice */
|
||||||
|
for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
|
||||||
|
unsigned int lc = 0; /* counter */
|
||||||
|
unsigned int lim = ttlg;
|
||||||
|
if (lim > t->sizearray) {
|
||||||
|
lim = t->sizearray; /* adjust upper limit */
|
||||||
|
if (i > lim)
|
||||||
|
break; /* no more elements to count */
|
||||||
|
}
|
||||||
|
/* count elements in range (2^(lg - 1), 2^lg] */
|
||||||
|
for (; i <= lim; i++) {
|
||||||
|
if (!ttisnil(&t->array[i-1]))
|
||||||
|
lc++;
|
||||||
|
}
|
||||||
|
nums[lg] += lc;
|
||||||
|
ause += lc;
|
||||||
|
}
|
||||||
|
return ause;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) {
|
||||||
|
int totaluse = 0; /* total number of elements */
|
||||||
|
int ause = 0; /* elements added to 'nums' (can go to array part) */
|
||||||
|
int i = sizenode(t);
|
||||||
|
while (i--) {
|
||||||
|
Node *n = &t->node[i];
|
||||||
|
if (!ttisnil(gval(n))) {
|
||||||
|
ause += countint(gkey(n), nums);
|
||||||
|
totaluse++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*pna += ause;
|
||||||
|
return totaluse;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void setarrayvector (lua_State *L, Table *t, unsigned int size) {
|
||||||
|
unsigned int i;
|
||||||
|
luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
|
||||||
|
for (i=t->sizearray; i<size; i++)
|
||||||
|
setnilvalue(&t->array[i]);
|
||||||
|
t->sizearray = size;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void setnodevector (lua_State *L, Table *t, unsigned int size) {
|
||||||
|
if (size == 0) { /* no elements to hash part? */
|
||||||
|
t->node = cast(Node *, dummynode); /* use common 'dummynode' */
|
||||||
|
t->lsizenode = 0;
|
||||||
|
t->lastfree = NULL; /* signal that it is using dummy node */
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
int i;
|
||||||
|
int lsize = luaO_ceillog2(size);
|
||||||
|
if (lsize > MAXHBITS)
|
||||||
|
luaG_runerror(L, "table overflow");
|
||||||
|
size = twoto(lsize);
|
||||||
|
t->node = luaM_newvector(L, size, Node);
|
||||||
|
for (i = 0; i < (int)size; i++) {
|
||||||
|
Node *n = gnode(t, i);
|
||||||
|
gnext(n) = 0;
|
||||||
|
setnilvalue(wgkey(n));
|
||||||
|
setnilvalue(gval(n));
|
||||||
|
}
|
||||||
|
t->lsizenode = cast_byte(lsize);
|
||||||
|
t->lastfree = gnode(t, size); /* all positions are free */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
Table *t;
|
||||||
|
unsigned int nhsize;
|
||||||
|
} AuxsetnodeT;
|
||||||
|
|
||||||
|
|
||||||
|
static void auxsetnode (lua_State *L, void *ud) {
|
||||||
|
AuxsetnodeT *asn = cast(AuxsetnodeT *, ud);
|
||||||
|
setnodevector(L, asn->t, asn->nhsize);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
|
||||||
|
unsigned int nhsize) {
|
||||||
|
unsigned int i;
|
||||||
|
int j;
|
||||||
|
AuxsetnodeT asn;
|
||||||
|
unsigned int oldasize = t->sizearray;
|
||||||
|
int oldhsize = allocsizenode(t);
|
||||||
|
Node *nold = t->node; /* save old hash ... */
|
||||||
|
if (nasize > oldasize) /* array part must grow? */
|
||||||
|
setarrayvector(L, t, nasize);
|
||||||
|
/* create new hash part with appropriate size */
|
||||||
|
asn.t = t; asn.nhsize = nhsize;
|
||||||
|
if (luaD_rawrunprotected(L, auxsetnode, &asn) != LUA_OK) { /* mem. error? */
|
||||||
|
setarrayvector(L, t, oldasize); /* array back to its original size */
|
||||||
|
luaD_throw(L, LUA_ERRMEM); /* rethrow memory error */
|
||||||
|
}
|
||||||
|
if (nasize < oldasize) { /* array part must shrink? */
|
||||||
|
t->sizearray = nasize;
|
||||||
|
/* re-insert elements from vanishing slice */
|
||||||
|
for (i=nasize; i<oldasize; i++) {
|
||||||
|
if (!ttisnil(&t->array[i]))
|
||||||
|
luaH_setint(L, t, i + 1, &t->array[i]);
|
||||||
|
}
|
||||||
|
/* shrink array */
|
||||||
|
luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
|
||||||
|
}
|
||||||
|
/* re-insert elements from hash part */
|
||||||
|
for (j = oldhsize - 1; j >= 0; j--) {
|
||||||
|
Node *old = nold + j;
|
||||||
|
if (!ttisnil(gval(old))) {
|
||||||
|
/* doesn't need barrier/invalidate cache, as entry was
|
||||||
|
already present in the table */
|
||||||
|
setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (oldhsize > 0) /* not the dummy node? */
|
||||||
|
luaM_freearray(L, nold, cast(size_t, oldhsize)); /* free old hash */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
|
||||||
|
int nsize = allocsizenode(t);
|
||||||
|
luaH_resize(L, t, nasize, nsize);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
|
||||||
|
*/
|
||||||
|
static void rehash (lua_State *L, Table *t, const TValue *ek) {
|
||||||
|
unsigned int asize; /* optimal size for array part */
|
||||||
|
unsigned int na; /* number of keys in the array part */
|
||||||
|
unsigned int nums[MAXABITS + 1];
|
||||||
|
int i;
|
||||||
|
int totaluse;
|
||||||
|
for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */
|
||||||
|
na = numusearray(t, nums); /* count keys in array part */
|
||||||
|
totaluse = na; /* all those keys are integer keys */
|
||||||
|
totaluse += numusehash(t, nums, &na); /* count keys in hash part */
|
||||||
|
/* count extra key */
|
||||||
|
na += countint(ek, nums);
|
||||||
|
totaluse++;
|
||||||
|
/* compute new size for array part */
|
||||||
|
asize = computesizes(nums, &na);
|
||||||
|
/* resize the table to new computed sizes */
|
||||||
|
luaH_resize(L, t, asize, totaluse - na);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** }=============================================================
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
Table *luaH_new (lua_State *L) {
|
||||||
|
GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
|
||||||
|
Table *t = gco2t(o);
|
||||||
|
t->metatable = NULL;
|
||||||
|
t->flags = cast_byte(~0);
|
||||||
|
t->array = NULL;
|
||||||
|
t->sizearray = 0;
|
||||||
|
setnodevector(L, t, 0);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaH_free (lua_State *L, Table *t) {
|
||||||
|
if (!isdummy(t))
|
||||||
|
luaM_freearray(L, t->node, cast(size_t, sizenode(t)));
|
||||||
|
luaM_freearray(L, t->array, t->sizearray);
|
||||||
|
luaM_free(L, t);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static Node *getfreepos (Table *t) {
|
||||||
|
if (!isdummy(t)) {
|
||||||
|
while (t->lastfree > t->node) {
|
||||||
|
t->lastfree--;
|
||||||
|
if (ttisnil(gkey(t->lastfree)))
|
||||||
|
return t->lastfree;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NULL; /* could not find a free place */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** inserts a new key into a hash table; first, check whether key's main
|
||||||
|
** position is free. If not, check whether colliding node is in its main
|
||||||
|
** position or not: if it is not, move colliding node to an empty place and
|
||||||
|
** put new key in its main position; otherwise (colliding node is in its main
|
||||||
|
** position), new key goes to an empty position.
|
||||||
|
*/
|
||||||
|
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
|
||||||
|
Node *mp;
|
||||||
|
TValue aux;
|
||||||
|
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
|
||||||
|
else if (ttisfloat(key)) {
|
||||||
|
lua_Integer k;
|
||||||
|
if (luaV_tointeger(key, &k, 0)) { /* does index fit in an integer? */
|
||||||
|
setivalue(&aux, k);
|
||||||
|
key = &aux; /* insert it as an integer */
|
||||||
|
}
|
||||||
|
else if (luai_numisnan(fltvalue(key)))
|
||||||
|
luaG_runerror(L, "table index is NaN");
|
||||||
|
}
|
||||||
|
mp = mainposition(t, key);
|
||||||
|
if (!ttisnil(gval(mp)) || isdummy(t)) { /* main position is taken? */
|
||||||
|
Node *othern;
|
||||||
|
Node *f = getfreepos(t); /* get a free place */
|
||||||
|
if (f == NULL) { /* cannot find a free place? */
|
||||||
|
rehash(L, t, key); /* grow table */
|
||||||
|
/* whatever called 'newkey' takes care of TM cache */
|
||||||
|
return luaH_set(L, t, key); /* insert key into grown table */
|
||||||
|
}
|
||||||
|
lua_assert(!isdummy(t));
|
||||||
|
othern = mainposition(t, gkey(mp));
|
||||||
|
if (othern != mp) { /* is colliding node out of its main position? */
|
||||||
|
/* yes; move colliding node into free position */
|
||||||
|
while (othern + gnext(othern) != mp) /* find previous */
|
||||||
|
othern += gnext(othern);
|
||||||
|
gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */
|
||||||
|
*f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
|
||||||
|
if (gnext(mp) != 0) {
|
||||||
|
gnext(f) += cast_int(mp - f); /* correct 'next' */
|
||||||
|
gnext(mp) = 0; /* now 'mp' is free */
|
||||||
|
}
|
||||||
|
setnilvalue(gval(mp));
|
||||||
|
}
|
||||||
|
else { /* colliding node is in its own main position */
|
||||||
|
/* new node will go into free position */
|
||||||
|
if (gnext(mp) != 0)
|
||||||
|
gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */
|
||||||
|
else lua_assert(gnext(f) == 0);
|
||||||
|
gnext(mp) = cast_int(f - mp);
|
||||||
|
mp = f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setnodekey(L, &mp->i_key, key);
|
||||||
|
luaC_barrierback(L, t, key);
|
||||||
|
lua_assert(ttisnil(gval(mp)));
|
||||||
|
return gval(mp);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** search function for integers
|
||||||
|
*/
|
||||||
|
const TValue *luaH_getint (Table *t, lua_Integer key) {
|
||||||
|
/* (1 <= key && key <= t->sizearray) */
|
||||||
|
if (l_castS2U(key) - 1 < t->sizearray)
|
||||||
|
return &t->array[key - 1];
|
||||||
|
else {
|
||||||
|
Node *n = hashint(t, key);
|
||||||
|
for (;;) { /* check whether 'key' is somewhere in the chain */
|
||||||
|
if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key)
|
||||||
|
return gval(n); /* that's it */
|
||||||
|
else {
|
||||||
|
int nx = gnext(n);
|
||||||
|
if (nx == 0) break;
|
||||||
|
n += nx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return luaO_nilobject;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** search function for short strings
|
||||||
|
*/
|
||||||
|
const TValue *luaH_getshortstr (Table *t, TString *key) {
|
||||||
|
Node *n = hashstr(t, key);
|
||||||
|
lua_assert(key->tt == LUA_TSHRSTR);
|
||||||
|
for (;;) { /* check whether 'key' is somewhere in the chain */
|
||||||
|
const TValue *k = gkey(n);
|
||||||
|
if (ttisshrstring(k) && eqshrstr(tsvalue(k), key))
|
||||||
|
return gval(n); /* that's it */
|
||||||
|
else {
|
||||||
|
int nx = gnext(n);
|
||||||
|
if (nx == 0)
|
||||||
|
return luaO_nilobject; /* not found */
|
||||||
|
n += nx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** "Generic" get version. (Not that generic: not valid for integers,
|
||||||
|
** which may be in array part, nor for floats with integral values.)
|
||||||
|
*/
|
||||||
|
static const TValue *getgeneric (Table *t, const TValue *key) {
|
||||||
|
Node *n = mainposition(t, key);
|
||||||
|
for (;;) { /* check whether 'key' is somewhere in the chain */
|
||||||
|
if (luaV_rawequalobj(gkey(n), key))
|
||||||
|
return gval(n); /* that's it */
|
||||||
|
else {
|
||||||
|
int nx = gnext(n);
|
||||||
|
if (nx == 0)
|
||||||
|
return luaO_nilobject; /* not found */
|
||||||
|
n += nx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const TValue *luaH_getstr (Table *t, TString *key) {
|
||||||
|
if (key->tt == LUA_TSHRSTR)
|
||||||
|
return luaH_getshortstr(t, key);
|
||||||
|
else { /* for long strings, use generic case */
|
||||||
|
TValue ko;
|
||||||
|
setsvalue(cast(lua_State *, NULL), &ko, key);
|
||||||
|
return getgeneric(t, &ko);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** main search function
|
||||||
|
*/
|
||||||
|
const TValue *luaH_get (Table *t, const TValue *key) {
|
||||||
|
switch (ttype(key)) {
|
||||||
|
case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));
|
||||||
|
case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
|
||||||
|
case LUA_TNIL: return luaO_nilobject;
|
||||||
|
case LUA_TNUMFLT: {
|
||||||
|
lua_Integer k;
|
||||||
|
if (luaV_tointeger(key, &k, 0)) /* index is int? */
|
||||||
|
return luaH_getint(t, k); /* use specialized version */
|
||||||
|
/* else... */
|
||||||
|
} /* FALLTHROUGH */
|
||||||
|
default:
|
||||||
|
return getgeneric(t, key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** beware: when using this function you probably need to check a GC
|
||||||
|
** barrier and invalidate the TM cache.
|
||||||
|
*/
|
||||||
|
TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
|
||||||
|
const TValue *p = luaH_get(t, key);
|
||||||
|
if (p != luaO_nilobject)
|
||||||
|
return cast(TValue *, p);
|
||||||
|
else return luaH_newkey(L, t, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
|
||||||
|
const TValue *p = luaH_getint(t, key);
|
||||||
|
TValue *cell;
|
||||||
|
if (p != luaO_nilobject)
|
||||||
|
cell = cast(TValue *, p);
|
||||||
|
else {
|
||||||
|
TValue k;
|
||||||
|
setivalue(&k, key);
|
||||||
|
cell = luaH_newkey(L, t, &k);
|
||||||
|
}
|
||||||
|
setobj2t(L, cell, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static lua_Unsigned unbound_search (Table *t, lua_Unsigned j) {
|
||||||
|
lua_Unsigned i = j; /* i is zero or a present index */
|
||||||
|
j++;
|
||||||
|
/* find 'i' and 'j' such that i is present and j is not */
|
||||||
|
while (!ttisnil(luaH_getint(t, j))) {
|
||||||
|
i = j;
|
||||||
|
if (j > l_castS2U(LUA_MAXINTEGER) / 2) { /* overflow? */
|
||||||
|
/* table was built with bad purposes: resort to linear search */
|
||||||
|
i = 1;
|
||||||
|
while (!ttisnil(luaH_getint(t, i))) i++;
|
||||||
|
return i - 1;
|
||||||
|
}
|
||||||
|
j *= 2;
|
||||||
|
}
|
||||||
|
/* now do a binary search between them */
|
||||||
|
while (j - i > 1) {
|
||||||
|
lua_Unsigned m = (i+j)/2;
|
||||||
|
if (ttisnil(luaH_getint(t, m))) j = m;
|
||||||
|
else i = m;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Try to find a boundary in table 't'. A 'boundary' is an integer index
|
||||||
|
** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
|
||||||
|
*/
|
||||||
|
lua_Unsigned luaH_getn (Table *t) {
|
||||||
|
unsigned int j = t->sizearray;
|
||||||
|
if (j > 0 && ttisnil(&t->array[j - 1])) {
|
||||||
|
/* there is a boundary in the array part: (binary) search for it */
|
||||||
|
unsigned int i = 0;
|
||||||
|
while (j - i > 1) {
|
||||||
|
unsigned int m = (i+j)/2;
|
||||||
|
if (ttisnil(&t->array[m - 1])) j = m;
|
||||||
|
else i = m;
|
||||||
|
}
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
/* else must find a boundary in hash part */
|
||||||
|
else if (isdummy(t)) /* hash part is empty? */
|
||||||
|
return j; /* that is easy... */
|
||||||
|
else return unbound_search(t, j);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(LUA_DEBUG)
|
||||||
|
|
||||||
|
Node *luaH_mainposition (const Table *t, const TValue *key) {
|
||||||
|
return mainposition(t, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
int luaH_isdummy (const Table *t) { return isdummy(t); }
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,450 @@
|
|||||||
|
/*
|
||||||
|
** $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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* }====================================================== */
|
||||||
|
|
||||||
|
#include "rotable2.h"
|
||||||
|
static const rotable_Reg_t tab_funcs[] = {
|
||||||
|
{"concat", ROREG_FUNC(tconcat)},
|
||||||
|
#if defined(LUA_COMPAT_MAXN)
|
||||||
|
{"maxn", ROREG_FUNC(maxn)},
|
||||||
|
#endif
|
||||||
|
{"insert", ROREG_FUNC(tinsert)},
|
||||||
|
{"pack", ROREG_FUNC(pack)},
|
||||||
|
{"unpack", ROREG_FUNC(unpack)},
|
||||||
|
{"remove", ROREG_FUNC(tremove)},
|
||||||
|
{"move", ROREG_FUNC(tmove)},
|
||||||
|
{"sort", ROREG_FUNC(sort)},
|
||||||
|
{NULL, ROREG_INT(0) }
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_table (lua_State *L) {
|
||||||
|
luat_newlib2(L, tab_funcs);
|
||||||
|
#if defined(LUA_COMPAT_UNPACK)
|
||||||
|
/* _G.unpack = table.unpack */
|
||||||
|
lua_getfield(L, -1, "unpack");
|
||||||
|
lua_setglobal(L, "unpack");
|
||||||
|
#endif
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
/*
|
||||||
|
** $Id: ltm.c,v 2.38.1.1 2017/04/19 17:39:34 roberto Exp $
|
||||||
|
** Tag methods
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define ltm_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
#include "ltable.h"
|
||||||
|
#include "ltm.h"
|
||||||
|
#include "lvm.h"
|
||||||
|
|
||||||
|
|
||||||
|
static const char udatatypename[] = "userdata";
|
||||||
|
|
||||||
|
LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = {
|
||||||
|
"no value",
|
||||||
|
"nil", "boolean", udatatypename, "number",
|
||||||
|
"string", "table", "function", udatatypename, "thread",
|
||||||
|
"proto" /* this last case is used for tests only */
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
void luaT_init (lua_State *L) {
|
||||||
|
static const char *const luaT_eventname[] = { /* ORDER TM */
|
||||||
|
"__index", "__newindex",
|
||||||
|
"__gc", "__mode", "__len", "__eq",
|
||||||
|
"__add", "__sub", "__mul", "__mod", "__pow",
|
||||||
|
"__div", "__idiv",
|
||||||
|
"__band", "__bor", "__bxor", "__shl", "__shr",
|
||||||
|
"__unm", "__bnot", "__lt", "__le",
|
||||||
|
"__concat", "__call"
|
||||||
|
};
|
||||||
|
int i;
|
||||||
|
for (i=0; i<TM_N; i++) {
|
||||||
|
G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
|
||||||
|
luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** function to be used with macro "fasttm": optimized for absence of
|
||||||
|
** tag methods
|
||||||
|
*/
|
||||||
|
const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {
|
||||||
|
const TValue *tm = luaH_getshortstr(events, ename);
|
||||||
|
lua_assert(event <= TM_EQ);
|
||||||
|
if (ttisnil(tm)) { /* no tag method? */
|
||||||
|
events->flags |= cast_byte(1u<<event); /* cache this fact */
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
else return tm;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
|
||||||
|
Table *mt;
|
||||||
|
switch (ttnov(o)) {
|
||||||
|
case LUA_TTABLE:
|
||||||
|
mt = hvalue(o)->metatable;
|
||||||
|
break;
|
||||||
|
case LUA_TUSERDATA:
|
||||||
|
mt = uvalue(o)->metatable;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
mt = G(L)->mt[ttnov(o)];
|
||||||
|
}
|
||||||
|
return (mt ? luaH_getshortstr(mt, G(L)->tmname[event]) : luaO_nilobject);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Return the name of the type of an object. For tables and userdata
|
||||||
|
** with metatable, use their '__name' metafield, if present.
|
||||||
|
*/
|
||||||
|
const char *luaT_objtypename (lua_State *L, const TValue *o) {
|
||||||
|
Table *mt;
|
||||||
|
if ((ttistable(o) && (mt = hvalue(o)->metatable) != NULL) ||
|
||||||
|
(ttisfulluserdata(o) && (mt = uvalue(o)->metatable) != NULL)) {
|
||||||
|
const TValue *name = luaH_getshortstr(mt, luaS_new(L, "__name"));
|
||||||
|
if (ttisstring(name)) /* is '__name' a string? */
|
||||||
|
return getstr(tsvalue(name)); /* use it as type name */
|
||||||
|
}
|
||||||
|
return ttypename(ttnov(o)); /* else use standard type name */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
|
||||||
|
const TValue *p2, TValue *p3, int hasres) {
|
||||||
|
ptrdiff_t result = savestack(L, p3);
|
||||||
|
StkId func = L->top;
|
||||||
|
setobj2s(L, func, f); /* push function (assume EXTRA_STACK) */
|
||||||
|
setobj2s(L, func + 1, p1); /* 1st argument */
|
||||||
|
setobj2s(L, func + 2, p2); /* 2nd argument */
|
||||||
|
L->top += 3;
|
||||||
|
if (!hasres) /* no result? 'p3' is third argument */
|
||||||
|
setobj2s(L, L->top++, p3); /* 3rd argument */
|
||||||
|
/* metamethod may yield only when called from Lua code */
|
||||||
|
if (isLua(L->ci))
|
||||||
|
luaD_call(L, func, hasres);
|
||||||
|
else
|
||||||
|
luaD_callnoyield(L, func, hasres);
|
||||||
|
if (hasres) { /* if has result, move it to its place */
|
||||||
|
p3 = restorestack(L, result);
|
||||||
|
setobjs2s(L, p3, --L->top);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaT_callbinTM (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;
|
||||||
|
luaT_callTM(L, tm, p1, p2, res, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||||
|
StkId res, TMS event) {
|
||||||
|
if (!luaT_callbinTM(L, p1, p2, res, event)) {
|
||||||
|
switch (event) {
|
||||||
|
case TM_CONCAT:
|
||||||
|
luaG_concaterror(L, p1, p2);
|
||||||
|
/* call never returns, but to avoid warnings: *//* FALLTHROUGH */
|
||||||
|
case TM_BAND: case TM_BOR: case TM_BXOR:
|
||||||
|
case TM_SHL: case TM_SHR: case TM_BNOT: {
|
||||||
|
lua_Number dummy;
|
||||||
|
if (tonumber(p1, &dummy) && tonumber(p2, &dummy))
|
||||||
|
luaG_tointerror(L, p1, p2);
|
||||||
|
else
|
||||||
|
luaG_opinterror(L, p1, p2, "perform bitwise operation on");
|
||||||
|
}
|
||||||
|
/* calls never return, but to avoid warnings: *//* FALLTHROUGH */
|
||||||
|
default:
|
||||||
|
luaG_opinterror(L, p1, p2, "perform arithmetic on");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||||
|
TMS event) {
|
||||||
|
if (!luaT_callbinTM(L, p1, p2, L->top, event))
|
||||||
|
return -1; /* no metamethod */
|
||||||
|
else
|
||||||
|
return !l_isfalse(L->top);
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,818 @@
|
|||||||
|
/*
|
||||||
|
|
||||||
|
B G E T
|
||||||
|
|
||||||
|
Buffer allocator
|
||||||
|
|
||||||
|
Designed and implemented in April of 1972 by John Walker, based on the
|
||||||
|
Case Algol OPRO$ algorithm implemented in 1966.
|
||||||
|
|
||||||
|
Reimplemented in 1975 by John Walker for the Interdata 70.
|
||||||
|
Reimplemented in 1977 by John Walker for the Marinchip 9900.
|
||||||
|
Reimplemented in 1982 by Duff Kurland for the Intel 8080.
|
||||||
|
|
||||||
|
Portable C version implemented in September of 1990 by an older, wiser
|
||||||
|
instance of the original implementor.
|
||||||
|
|
||||||
|
Souped up and/or weighed down slightly shortly thereafter by Greg
|
||||||
|
Lutz.
|
||||||
|
|
||||||
|
AMIX edition, including the new compaction call-back option, prepared
|
||||||
|
by John Walker in July of 1992.
|
||||||
|
|
||||||
|
Bug in built-in test program fixed, ANSI compiler warnings eradicated,
|
||||||
|
buffer pool validator implemented, and guaranteed repeatable test
|
||||||
|
added by John Walker in October of 1995.
|
||||||
|
|
||||||
|
This program is in the public domain.
|
||||||
|
|
||||||
|
1. This is the book of the generations of Adam. In the day that God
|
||||||
|
created man, in the likeness of God made he him;
|
||||||
|
2. Male and female created he them; and blessed them, and called
|
||||||
|
their name Adam, in the day when they were created.
|
||||||
|
3. And Adam lived an hundred and thirty years, and begat a son in
|
||||||
|
his own likeness, and after his image; and called his name Seth:
|
||||||
|
4. And the days of Adam after he had begotten Seth were eight
|
||||||
|
hundred years: and he begat sons and daughters:
|
||||||
|
5. And all the days that Adam lived were nine hundred and thirty
|
||||||
|
years: and he died.
|
||||||
|
6. And Seth lived an hundred and five years, and begat Enos:
|
||||||
|
7. And Seth lived after he begat Enos eight hundred and seven years,
|
||||||
|
and begat sons and daughters:
|
||||||
|
8. And all the days of Seth were nine hundred and twelve years: and
|
||||||
|
he died.
|
||||||
|
9. And Enos lived ninety years, and begat Cainan:
|
||||||
|
10. And Enos lived after he begat Cainan eight hundred and fifteen
|
||||||
|
years, and begat sons and daughters:
|
||||||
|
11. And all the days of Enos were nine hundred and five years: and
|
||||||
|
he died.
|
||||||
|
12. And Cainan lived seventy years and begat Mahalaleel:
|
||||||
|
13. And Cainan lived after he begat Mahalaleel eight hundred and
|
||||||
|
forty years, and begat sons and daughters:
|
||||||
|
14. And all the days of Cainan were nine hundred and ten years: and
|
||||||
|
he died.
|
||||||
|
15. And Mahalaleel lived sixty and five years, and begat Jared:
|
||||||
|
16. And Mahalaleel lived after he begat Jared eight hundred and
|
||||||
|
thirty years, and begat sons and daughters:
|
||||||
|
17. And all the days of Mahalaleel were eight hundred ninety and
|
||||||
|
five years: and he died.
|
||||||
|
18. And Jared lived an hundred sixty and two years, and he begat
|
||||||
|
Enoch:
|
||||||
|
19. And Jared lived after he begat Enoch eight hundred years, and
|
||||||
|
begat sons and daughters:
|
||||||
|
20. And all the days of Jared were nine hundred sixty and two years:
|
||||||
|
and he died.
|
||||||
|
21. And Enoch lived sixty and five years, and begat Methuselah:
|
||||||
|
22. And Enoch walked with God after he begat Methuselah three
|
||||||
|
hundred years, and begat sons and daughters:
|
||||||
|
23. And all the days of Enoch were three hundred sixty and five
|
||||||
|
years:
|
||||||
|
24. And Enoch walked with God: and he was not; for God took him.
|
||||||
|
25. And Methuselah lived an hundred eighty and seven years, and
|
||||||
|
begat Lamech.
|
||||||
|
26. And Methuselah lived after he begat Lamech seven hundred eighty
|
||||||
|
and two years, and begat sons and daughters:
|
||||||
|
27. And all the days of Methuselah were nine hundred sixty and nine
|
||||||
|
years: and he died.
|
||||||
|
28. And Lamech lived an hundred eighty and two years, and begat a
|
||||||
|
son:
|
||||||
|
29. And he called his name Noah, saying, This same shall comfort us
|
||||||
|
concerning our work and toil of our hands, because of the ground
|
||||||
|
which the LORD hath cursed.
|
||||||
|
30. And Lamech lived after he begat Noah five hundred ninety and
|
||||||
|
five years, and begat sons and daughters:
|
||||||
|
31. And all the days of Lamech were seven hundred seventy and seven
|
||||||
|
years: and he died.
|
||||||
|
32. And Noah was five hundred years old: and Noah begat Shem, Ham,
|
||||||
|
and Japheth.
|
||||||
|
|
||||||
|
And buffers begat buffers, and links begat links, and buffer pools
|
||||||
|
begat links to chains of buffer pools containing buffers, and lo the
|
||||||
|
buffers and links and pools of buffers and pools of links to chains of
|
||||||
|
pools of buffers were fruitful and they multiplied and the Operating
|
||||||
|
System looked down upon them and said that it was Good.
|
||||||
|
|
||||||
|
|
||||||
|
INTRODUCTION
|
||||||
|
============
|
||||||
|
|
||||||
|
BGET is a comprehensive memory allocation package which is easily
|
||||||
|
configured to the needs of an application. BGET is efficient in
|
||||||
|
both the time needed to allocate and release buffers and in the
|
||||||
|
memory overhead required for buffer pool management. It
|
||||||
|
automatically consolidates contiguous space to minimise
|
||||||
|
fragmentation. BGET is configured by compile-time definitions,
|
||||||
|
Major options include:
|
||||||
|
|
||||||
|
* A built-in test program to exercise BGET and
|
||||||
|
demonstrate how the various functions are used.
|
||||||
|
|
||||||
|
* Allocation by either the "first fit" or "best fit"
|
||||||
|
method.
|
||||||
|
|
||||||
|
* Wiping buffers at release time to catch code which
|
||||||
|
references previously released storage.
|
||||||
|
|
||||||
|
* Built-in routines to dump individual buffers or the
|
||||||
|
entire buffer pool.
|
||||||
|
|
||||||
|
* Retrieval of allocation and pool size statistics.
|
||||||
|
|
||||||
|
* Quantisation of buffer sizes to a power of two to
|
||||||
|
satisfy hardware alignment constraints.
|
||||||
|
|
||||||
|
* Automatic pool compaction, growth, and shrinkage by
|
||||||
|
means of call-backs to user defined functions.
|
||||||
|
|
||||||
|
Applications of BGET can range from storage management in
|
||||||
|
ROM-based embedded programs to providing the framework upon which
|
||||||
|
a multitasking system incorporating garbage collection is
|
||||||
|
constructed. BGET incorporates extensive internal consistency
|
||||||
|
checking using the <assert.h> mechanism; all these checks can be
|
||||||
|
turned off by compiling with NDEBUG defined, yielding a version of
|
||||||
|
BGET with minimal size and maximum speed.
|
||||||
|
|
||||||
|
The basic algorithm underlying BGET has withstood the test of
|
||||||
|
time; more than 25 years have passed since the first
|
||||||
|
implementation of this code. And yet, it is substantially more
|
||||||
|
efficient than the native allocation schemes of many operating
|
||||||
|
systems: the Macintosh and Microsoft Windows to name two, on which
|
||||||
|
programs have obtained substantial speed-ups by layering BGET as
|
||||||
|
an application level memory manager atop the underlying system's.
|
||||||
|
|
||||||
|
BGET has been implemented on the largest mainframes and the lowest
|
||||||
|
of microprocessors. It has served as the core for multitasking
|
||||||
|
operating systems, multi-thread applications, embedded software in
|
||||||
|
data network switching processors, and a host of C programs. And
|
||||||
|
while it has accreted flexibility and additional options over the
|
||||||
|
years, it remains fast, memory efficient, portable, and easy to
|
||||||
|
integrate into your program.
|
||||||
|
|
||||||
|
|
||||||
|
BGET IMPLEMENTATION ASSUMPTIONS
|
||||||
|
===============================
|
||||||
|
|
||||||
|
BGET is written in as portable a dialect of C as possible. The
|
||||||
|
only fundamental assumption about the underlying hardware
|
||||||
|
architecture is that memory is allocated is a linear array which
|
||||||
|
can be addressed as a vector of C "char" objects. On segmented
|
||||||
|
address space architectures, this generally means that BGET should
|
||||||
|
be used to allocate storage within a single segment (although some
|
||||||
|
compilers simulate linear address spaces on segmented
|
||||||
|
architectures). On segmented architectures, then, BGET buffer
|
||||||
|
pools may not be larger than a segment, but since BGET allows any
|
||||||
|
number of separate buffer pools, there is no limit on the total
|
||||||
|
storage which can be managed, only on the largest individual
|
||||||
|
object which can be allocated. Machines with a linear address
|
||||||
|
architecture, such as the VAX, 680x0, Sparc, MIPS, or the Intel
|
||||||
|
80386 and above in native mode, may use BGET without restriction.
|
||||||
|
|
||||||
|
|
||||||
|
GETTING STARTED WITH BGET
|
||||||
|
=========================
|
||||||
|
|
||||||
|
Although BGET can be configured in a multitude of fashions, there
|
||||||
|
are three basic ways of working with BGET. The functions
|
||||||
|
mentioned below are documented in the following section. Please
|
||||||
|
excuse the forward references which are made in the interest of
|
||||||
|
providing a roadmap to guide you to the BGET functions you're
|
||||||
|
likely to need.
|
||||||
|
|
||||||
|
Embedded Applications
|
||||||
|
---------------------
|
||||||
|
|
||||||
|
Embedded applications typically have a fixed area of memory
|
||||||
|
dedicated to buffer allocation (often in a separate RAM address
|
||||||
|
space distinct from the ROM that contains the executable code).
|
||||||
|
To use BGET in such an environment, simply call bpool() with the
|
||||||
|
start address and length of the buffer pool area in RAM, then
|
||||||
|
allocate buffers with bget() and release them with brel().
|
||||||
|
Embedded applications with very limited RAM but abundant CPU speed
|
||||||
|
may benefit by configuring BGET for BestFit allocation (which is
|
||||||
|
usually not worth it in other environments).
|
||||||
|
|
||||||
|
Malloc() Emulation
|
||||||
|
------------------
|
||||||
|
|
||||||
|
If the C library malloc() function is too slow, not present in
|
||||||
|
your development environment (for example, an a native Windows or
|
||||||
|
Macintosh program), or otherwise unsuitable, you can replace it
|
||||||
|
with BGET. Initially define a buffer pool of an appropriate size
|
||||||
|
with bpool()--usually obtained by making a call to the operating
|
||||||
|
system's low-level memory allocator. Then allocate buffers with
|
||||||
|
bget(), bgetz(), and bgetr() (the last two permit the allocation
|
||||||
|
of buffers initialised to zero and [inefficient] re-allocation of
|
||||||
|
existing buffers for compatibility with C library functions).
|
||||||
|
Release buffers by calling brel(). If a buffer allocation request
|
||||||
|
fails, obtain more storage from the underlying operating system,
|
||||||
|
add it to the buffer pool by another call to bpool(), and continue
|
||||||
|
execution.
|
||||||
|
|
||||||
|
Automatic Storage Management
|
||||||
|
----------------------------
|
||||||
|
|
||||||
|
You can use BGET as your application's native memory manager and
|
||||||
|
implement automatic storage pool expansion, contraction, and
|
||||||
|
optionally application-specific memory compaction by compiling
|
||||||
|
BGET with the BECtl variable defined, then calling bectl() and
|
||||||
|
supplying functions for storage compaction, acquisition, and
|
||||||
|
release, as well as a standard pool expansion increment. All of
|
||||||
|
these functions are optional (although it doesn't make much sense
|
||||||
|
to provide a release function without an acquisition function,
|
||||||
|
does it?). Once the call-back functions have been defined with
|
||||||
|
bectl(), you simply use bget() and brel() to allocate and release
|
||||||
|
storage as before. You can supply an initial buffer pool with
|
||||||
|
bpool() or rely on automatic allocation to acquire the entire
|
||||||
|
pool. When a call on bget() cannot be satisfied, BGET first
|
||||||
|
checks if a compaction function has been supplied. If so, it is
|
||||||
|
called (with the space required to satisfy the allocation request
|
||||||
|
and a sequence number to allow the compaction routine to be called
|
||||||
|
successively without looping). If the compaction function is able
|
||||||
|
to free any storage (it needn't know whether the storage it freed
|
||||||
|
was adequate) it should return a nonzero value, whereupon BGET
|
||||||
|
will retry the allocation request and, if it fails again, call the
|
||||||
|
compaction function again with the next-higher sequence number.
|
||||||
|
|
||||||
|
If the compaction function returns zero, indicating failure to
|
||||||
|
free space, or no compaction function is defined, BGET next tests
|
||||||
|
whether a non-NULL allocation function was supplied to bectl().
|
||||||
|
If so, that function is called with an argument indicating how
|
||||||
|
many bytes of additional space are required. This will be the
|
||||||
|
standard pool expansion increment supplied in the call to bectl()
|
||||||
|
unless the original bget() call requested a buffer larger than
|
||||||
|
this; buffers larger than the standard pool block can be managed
|
||||||
|
"off the books" by BGET in this mode. If the allocation function
|
||||||
|
succeeds in obtaining the storage, it returns a pointer to the new
|
||||||
|
block and BGET expands the buffer pool; if it fails, the
|
||||||
|
allocation request fails and returns NULL to the caller. If a
|
||||||
|
non-NULL release function is supplied, expansion blocks which
|
||||||
|
become totally empty are released to the global free pool by
|
||||||
|
passing their addresses to the release function.
|
||||||
|
|
||||||
|
Equipped with appropriate allocation, release, and compaction
|
||||||
|
functions, BGET can be used as part of very sophisticated memory
|
||||||
|
management strategies, including garbage collection. (Note,
|
||||||
|
however, that BGET is *not* a garbage collector by itself, and
|
||||||
|
that developing such a system requires much additional logic and
|
||||||
|
careful design of the application's memory allocation strategy.)
|
||||||
|
|
||||||
|
|
||||||
|
BGET FUNCTION DESCRIPTIONS
|
||||||
|
==========================
|
||||||
|
|
||||||
|
Functions implemented in this file (some are enabled by certain of
|
||||||
|
the optional settings below):
|
||||||
|
|
||||||
|
void bpool(void *buffer, bufsize len);
|
||||||
|
|
||||||
|
Create a buffer pool of <len> bytes, using the storage starting at
|
||||||
|
<buffer>. You can call bpool() subsequently to contribute
|
||||||
|
additional storage to the overall buffer pool.
|
||||||
|
|
||||||
|
void *bget(bufsize size);
|
||||||
|
|
||||||
|
Allocate a buffer of <size> bytes. The address of the buffer is
|
||||||
|
returned, or NULL if insufficient memory was available to allocate
|
||||||
|
the buffer.
|
||||||
|
|
||||||
|
void *bgetz(bufsize size);
|
||||||
|
|
||||||
|
Allocate a buffer of <size> bytes and clear it to all zeroes. The
|
||||||
|
address of the buffer is returned, or NULL if insufficient memory
|
||||||
|
was available to allocate the buffer.
|
||||||
|
|
||||||
|
void *bgetr(void *buffer, bufsize newsize);
|
||||||
|
|
||||||
|
Reallocate a buffer previously allocated by bget(), changing its
|
||||||
|
size to <newsize> and preserving all existing data. NULL is
|
||||||
|
returned if insufficient memory is available to reallocate the
|
||||||
|
buffer, in which case the original buffer remains intact.
|
||||||
|
|
||||||
|
void brel(void *buf);
|
||||||
|
|
||||||
|
Return the buffer <buf>, previously allocated by bget(), to the
|
||||||
|
free space pool.
|
||||||
|
|
||||||
|
void bectl(int (*compact)(bufsize sizereq, int sequence),
|
||||||
|
void *(*acquire)(bufsize size),
|
||||||
|
void (*release)(void *buf),
|
||||||
|
bufsize pool_incr);
|
||||||
|
|
||||||
|
Expansion control: specify functions through which the package may
|
||||||
|
compact storage (or take other appropriate action) when an
|
||||||
|
allocation request fails, and optionally automatically acquire
|
||||||
|
storage for expansion blocks when necessary, and release such
|
||||||
|
blocks when they become empty. If <compact> is non-NULL, whenever
|
||||||
|
a buffer allocation request fails, the <compact> function will be
|
||||||
|
called with arguments specifying the number of bytes (total buffer
|
||||||
|
size, including header overhead) required to satisfy the
|
||||||
|
allocation request, and a sequence number indicating the number of
|
||||||
|
consecutive calls on <compact> attempting to satisfy this
|
||||||
|
allocation request. The sequence number is 1 for the first call
|
||||||
|
on <compact> for a given allocation request, and increments on
|
||||||
|
subsequent calls, permitting the <compact> function to take
|
||||||
|
increasingly dire measures in an attempt to free up storage. If
|
||||||
|
the <compact> function returns a nonzero value, the allocation
|
||||||
|
attempt is re-tried. If <compact> returns 0 (as it must if it
|
||||||
|
isn't able to release any space or add storage to the buffer
|
||||||
|
pool), the allocation request fails, which can trigger automatic
|
||||||
|
pool expansion if the <acquire> argument is non-NULL. At the time
|
||||||
|
the <compact> function is called, the state of the buffer
|
||||||
|
allocator is identical to that at the moment the allocation
|
||||||
|
request was made; consequently, the <compact> function may call
|
||||||
|
brel(), bpool(), bstats(), and/or directly manipulate the buffer
|
||||||
|
pool in any manner which would be valid were the application in
|
||||||
|
control. This does not, however, relieve the <compact> function
|
||||||
|
of the need to ensure that whatever actions it takes do not change
|
||||||
|
things underneath the application that made the allocation
|
||||||
|
request. For example, a <compact> function that released a buffer
|
||||||
|
in the process of being reallocated with bgetr() would lead to
|
||||||
|
disaster. Implementing a safe and effective <compact> mechanism
|
||||||
|
requires careful design of an application's memory architecture,
|
||||||
|
and cannot generally be easily retrofitted into existing code.
|
||||||
|
|
||||||
|
If <acquire> is non-NULL, that function will be called whenever an
|
||||||
|
allocation request fails. If the <acquire> function succeeds in
|
||||||
|
allocating the requested space and returns a pointer to the new
|
||||||
|
area, allocation will proceed using the expanded buffer pool. If
|
||||||
|
<acquire> cannot obtain the requested space, it should return NULL
|
||||||
|
and the entire allocation process will fail. <pool_incr>
|
||||||
|
specifies the normal expansion block size. Providing an <acquire>
|
||||||
|
function will cause subsequent bget() requests for buffers too
|
||||||
|
large to be managed in the linked-block scheme (in other words,
|
||||||
|
larger than <pool_incr> minus the buffer overhead) to be satisfied
|
||||||
|
directly by calls to the <acquire> function. Automatic release of
|
||||||
|
empty pool blocks will occur only if all pool blocks in the system
|
||||||
|
are the size given by <pool_incr>.
|
||||||
|
|
||||||
|
void bstats(bufsize *curalloc, bufsize *totfree,
|
||||||
|
bufsize *maxfree, unsigned long *nget, unsigned long *nrel);
|
||||||
|
|
||||||
|
The amount of space currently allocated is stored into the
|
||||||
|
variable pointed to by <curalloc>. The total free space (sum of
|
||||||
|
all free blocks in the pool) is stored into the variable pointed
|
||||||
|
to by <totfree>, and the size of the largest single block in the
|
||||||
|
free space pool is stored into the variable pointed to by
|
||||||
|
<maxfree>. The variables pointed to by <nget> and <nrel> are
|
||||||
|
filled, respectively, with the number of successful (non-NULL
|
||||||
|
return) bget() calls and the number of brel() calls.
|
||||||
|
|
||||||
|
void bstatse(bufsize *pool_incr, unsigned long *npool,
|
||||||
|
unsigned long *npget, unsigned long *nprel,
|
||||||
|
unsigned long *ndget, unsigned long *ndrel);
|
||||||
|
|
||||||
|
Extended statistics: The expansion block size will be stored into
|
||||||
|
the variable pointed to by <pool_incr>, or the negative thereof if
|
||||||
|
automatic expansion block releases are disabled. The number of
|
||||||
|
currently active pool blocks will be stored into the variable
|
||||||
|
pointed to by <npool>. The variables pointed to by <npget> and
|
||||||
|
<nprel> will be filled with, respectively, the number of expansion
|
||||||
|
block acquisitions and releases which have occurred. The
|
||||||
|
variables pointed to by <ndget> and <ndrel> will be filled with
|
||||||
|
the number of bget() and brel() calls, respectively, managed
|
||||||
|
through blocks directly allocated by the acquisition and release
|
||||||
|
functions.
|
||||||
|
|
||||||
|
void bufdump(void *buf);
|
||||||
|
|
||||||
|
The buffer pointed to by <buf> is dumped on standard output.
|
||||||
|
|
||||||
|
void bpoold(void *pool, int dumpalloc, int dumpfree);
|
||||||
|
|
||||||
|
All buffers in the buffer pool <pool>, previously initialised by a
|
||||||
|
call on bpool(), are listed in ascending memory address order. If
|
||||||
|
<dumpalloc> is nonzero, the contents of allocated buffers are
|
||||||
|
dumped; if <dumpfree> is nonzero, the contents of free blocks are
|
||||||
|
dumped.
|
||||||
|
|
||||||
|
int bpoolv(void *pool);
|
||||||
|
|
||||||
|
The named buffer pool, previously initialised by a call on
|
||||||
|
bpool(), is validated for bad pointers, overwritten data, etc. If
|
||||||
|
compiled with NDEBUG not defined, any error generates an assertion
|
||||||
|
failure. Otherwise 1 is returned if the pool is valid, 0 if an
|
||||||
|
error is found.
|
||||||
|
|
||||||
|
|
||||||
|
BGET CONFIGURATION
|
||||||
|
==================
|
||||||
|
*/
|
||||||
|
|
||||||
|
#if 0
|
||||||
|
#define TestProg 20000 /* Generate built-in test program
|
||||||
|
if defined. The value specifies
|
||||||
|
how many buffer allocation attempts
|
||||||
|
the test program should make. */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/* Declare the interface, including the requested buffer size type,
|
||||||
|
bufsize. */
|
||||||
|
|
||||||
|
#include "luat_bget.h"
|
||||||
|
|
||||||
|
|
||||||
|
void luat_bget_init(luat_bget_t* bg) {
|
||||||
|
memset(bg, 0 , sizeof(luat_bget_t));
|
||||||
|
//bg->freelist.bh.prevfree = 0;
|
||||||
|
//bg->freelist.bh.bsize = 0;
|
||||||
|
bg->freelist.ql.blink = &bg->freelist;
|
||||||
|
bg->freelist.ql.flink = &bg->freelist;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* Minimum allocation quantum: */
|
||||||
|
|
||||||
|
#define QLSize (sizeof(struct qlinks))
|
||||||
|
#define SizeQ ((SizeQuant > QLSize) ? SizeQuant : QLSize)
|
||||||
|
|
||||||
|
#define V (void) /* To denote unwanted returned values */
|
||||||
|
|
||||||
|
/* End sentinel: value placed in bsize field of dummy block delimiting
|
||||||
|
end of pool block. The most negative number which will fit in a
|
||||||
|
bufsize, defined in a way that the compiler will accept. */
|
||||||
|
|
||||||
|
#define ESent ((bufsize) (-(((1L << (sizeof(bufsize) * 8 - 2)) - 1) * 2) - 2))
|
||||||
|
#define _assert_(x)
|
||||||
|
/* BGET -- Allocate a buffer. */
|
||||||
|
|
||||||
|
void *luat_bget(luat_bget_t* bg, bufsize requested_size)
|
||||||
|
{
|
||||||
|
bufsize size = requested_size;
|
||||||
|
struct bfhead *b;
|
||||||
|
#ifdef BestFit
|
||||||
|
struct bfhead *best;
|
||||||
|
#endif
|
||||||
|
void *buf;
|
||||||
|
#ifdef BECtl
|
||||||
|
int compactseq = 0;
|
||||||
|
#endif
|
||||||
|
_assert_(size >= 0);
|
||||||
|
if (!size)
|
||||||
|
{
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (size < (bufsize)SizeQ) { /* Need at least room for the */
|
||||||
|
size = SizeQ; /* queue links. */
|
||||||
|
}
|
||||||
|
#ifdef SizeQuant
|
||||||
|
#if SizeQuant > 1
|
||||||
|
size = (size + (SizeQuant - 1)) & (~(SizeQuant - 1));
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
size += sizeof(struct bhead); /* Add overhead in allocated buffer
|
||||||
|
to size required. */
|
||||||
|
|
||||||
|
#ifdef BECtl
|
||||||
|
/* If a compact function was provided in the call to bectl(), wrap
|
||||||
|
a loop around the allocation process to allow compaction to
|
||||||
|
intervene in case we don't find a suitable buffer in the chain. */
|
||||||
|
|
||||||
|
while (1) {
|
||||||
|
#endif
|
||||||
|
b = bg->freelist.ql.flink;
|
||||||
|
#ifdef BestFit
|
||||||
|
best = &bg->freelist;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/* Scan the free list searching for the first buffer big enough
|
||||||
|
to hold the requested size buffer. */
|
||||||
|
|
||||||
|
#ifdef BestFit
|
||||||
|
while (b != &bg->freelist) {
|
||||||
|
if (b->bh.bsize >= size) {
|
||||||
|
if ((best == &bg->freelist) || (b->bh.bsize < best->bh.bsize)) {
|
||||||
|
best = b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b = b->ql.flink; /* Link to next buffer */
|
||||||
|
}
|
||||||
|
b = best;
|
||||||
|
#endif /* BestFit */
|
||||||
|
|
||||||
|
while (b != &bg->freelist) {
|
||||||
|
if ((bufsize) b->bh.bsize >= size) {
|
||||||
|
|
||||||
|
/* Buffer is big enough to satisfy the request. Allocate it
|
||||||
|
to the caller. We must decide whether the buffer is large
|
||||||
|
enough to split into the part given to the caller and a
|
||||||
|
free buffer that remains on the free list, or whether the
|
||||||
|
entire buffer should be removed from the free list and
|
||||||
|
given to the caller in its entirety. We only split the
|
||||||
|
buffer if enough room remains for a header plus the minimum
|
||||||
|
quantum of allocation. */
|
||||||
|
|
||||||
|
if ((b->bh.bsize - size) > (bufsize)(SizeQ + (sizeof(struct bhead)))) {
|
||||||
|
struct bhead *ba, *bn;
|
||||||
|
|
||||||
|
ba = BH(((char *) b) + (b->bh.bsize - size));
|
||||||
|
bn = BH(((char *) ba) + size);
|
||||||
|
_assert_(bn->prevfree == b->bh.bsize);
|
||||||
|
/* Subtract size from length of free block. */
|
||||||
|
b->bh.bsize -= size;
|
||||||
|
/* Link allocated buffer to the previous free buffer. */
|
||||||
|
ba->prevfree = b->bh.bsize;
|
||||||
|
/* Plug negative size into user buffer. */
|
||||||
|
ba->bsize = -(bufsize) size;
|
||||||
|
/* Mark buffer after this one not preceded by free block. */
|
||||||
|
bn->prevfree = 0;
|
||||||
|
|
||||||
|
#ifdef BufStats
|
||||||
|
bg->totalloc += size;
|
||||||
|
if (bg->totalloc > bg->maxalloc)
|
||||||
|
{
|
||||||
|
bg->maxalloc = bg->totalloc;
|
||||||
|
}
|
||||||
|
bg->numget++; /* Increment number of bget() calls */
|
||||||
|
#endif
|
||||||
|
buf = (void *) ((((char *) ba) + sizeof(struct bhead)));
|
||||||
|
return buf;
|
||||||
|
} else {
|
||||||
|
struct bhead *ba;
|
||||||
|
|
||||||
|
ba = BH(((char *) b) + b->bh.bsize);
|
||||||
|
_assert_(ba->prevfree == b->bh.bsize);
|
||||||
|
|
||||||
|
/* The buffer isn't big enough to split. Give the whole
|
||||||
|
shebang to the caller and remove it from the free list. */
|
||||||
|
|
||||||
|
_assert_(b->ql.blink->ql.flink == b);
|
||||||
|
_assert_(b->ql.flink->ql.blink == b);
|
||||||
|
b->ql.blink->ql.flink = b->ql.flink;
|
||||||
|
b->ql.flink->ql.blink = b->ql.blink;
|
||||||
|
|
||||||
|
#ifdef BufStats
|
||||||
|
bg->totalloc += b->bh.bsize;
|
||||||
|
if (bg->totalloc > bg->maxalloc)
|
||||||
|
{
|
||||||
|
bg->maxalloc = bg->totalloc;
|
||||||
|
}
|
||||||
|
bg->numget++; /* Increment number of bget() calls */
|
||||||
|
#endif
|
||||||
|
/* Negate size to mark buffer allocated. */
|
||||||
|
b->bh.bsize = -(b->bh.bsize);
|
||||||
|
|
||||||
|
/* Zero the back pointer in the next buffer in memory
|
||||||
|
to indicate that this buffer is allocated. */
|
||||||
|
ba->prevfree = 0;
|
||||||
|
|
||||||
|
/* Give user buffer starting at queue links. */
|
||||||
|
buf = (void *) &(b->ql);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b = b->ql.flink; /* Link to next buffer */
|
||||||
|
}
|
||||||
|
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* BGETZ -- Allocate a buffer and clear its contents to zero. We clear
|
||||||
|
the entire contents of the buffer to zero, not just the
|
||||||
|
region requested by the caller. */
|
||||||
|
|
||||||
|
void *luat_bgetz(luat_bget_t* bg, bufsize size)
|
||||||
|
{
|
||||||
|
char *buf = (char *) luat_bget(bg, size);
|
||||||
|
|
||||||
|
if (buf != NULL) {
|
||||||
|
struct bhead *b;
|
||||||
|
bufsize rsize;
|
||||||
|
|
||||||
|
b = BH(buf - sizeof(struct bhead));
|
||||||
|
rsize = -(b->bsize);
|
||||||
|
if (rsize == 0) {
|
||||||
|
struct bdhead *bd;
|
||||||
|
|
||||||
|
bd = BDH(buf - sizeof(struct bdhead));
|
||||||
|
rsize = bd->tsize - sizeof(struct bdhead);
|
||||||
|
} else {
|
||||||
|
rsize -= sizeof(struct bhead);
|
||||||
|
}
|
||||||
|
_assert_(rsize >= size);
|
||||||
|
memset(buf, 0, (MemSize) rsize);
|
||||||
|
}
|
||||||
|
return ((void *) buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* BGETR -- Reallocate a buffer. This is a minimal implementation,
|
||||||
|
simply in terms of brel() and bget(). It could be
|
||||||
|
enhanced to allow the buffer to grow into adjacent free
|
||||||
|
blocks and to avoid moving data unnecessarily. */
|
||||||
|
|
||||||
|
void *luat_bgetr(luat_bget_t* bg, void *buf, bufsize size)
|
||||||
|
{
|
||||||
|
void *nbuf;
|
||||||
|
bufsize osize; /* Old size of buffer */
|
||||||
|
struct bhead *b;
|
||||||
|
|
||||||
|
if ((nbuf = luat_bget(bg, size)) == NULL) { /* Acquire new buffer */
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
if (buf == NULL) {
|
||||||
|
return nbuf;
|
||||||
|
}
|
||||||
|
b = BH(((char *) buf) - sizeof(struct bhead));
|
||||||
|
osize = -b->bsize;
|
||||||
|
|
||||||
|
osize -= sizeof(struct bhead);
|
||||||
|
_assert_(osize > 0);
|
||||||
|
V memcpy((char *) nbuf, (char *) buf, /* Copy the data */
|
||||||
|
(MemSize) ((size < osize) ? size : osize));
|
||||||
|
luat_brel(bg, buf);
|
||||||
|
return nbuf;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* BREL -- Release a buffer. */
|
||||||
|
|
||||||
|
void luat_brel(luat_bget_t* bg, void *buf)
|
||||||
|
{
|
||||||
|
struct bfhead *b, *bn;
|
||||||
|
|
||||||
|
b = BFH(((char *) buf) - sizeof(struct bhead));
|
||||||
|
#ifdef BufStats
|
||||||
|
bg->numrel++; /* Increment number of brel() calls */
|
||||||
|
#endif
|
||||||
|
_assert_(buf != NULL);
|
||||||
|
if (!buf)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buffer size must be negative, indicating that the buffer is
|
||||||
|
allocated. */
|
||||||
|
|
||||||
|
if (b->bh.bsize >= 0) {
|
||||||
|
bn = NULL;
|
||||||
|
}
|
||||||
|
_assert_(b->bh.bsize < 0);
|
||||||
|
|
||||||
|
/* Back pointer in next buffer must be zero, indicating the
|
||||||
|
same thing: */
|
||||||
|
|
||||||
|
_assert_(BH((char *) b - b->bh.bsize)->prevfree == 0);
|
||||||
|
|
||||||
|
#ifdef BufStats
|
||||||
|
bg->totalloc += b->bh.bsize;
|
||||||
|
_assert_(bg->totalloc >= 0);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* If the back link is nonzero, the previous buffer is free. */
|
||||||
|
|
||||||
|
if (b->bh.prevfree != 0) {
|
||||||
|
|
||||||
|
/* The previous buffer is free. Consolidate this buffer with it
|
||||||
|
by adding the length of this buffer to the previous free
|
||||||
|
buffer. Note that we subtract the size in the buffer being
|
||||||
|
released, since it's negative to indicate that the buffer is
|
||||||
|
allocated. */
|
||||||
|
|
||||||
|
register bufsize size = b->bh.bsize;
|
||||||
|
|
||||||
|
/* Make the previous buffer the one we're working on. */
|
||||||
|
_assert_(BH((char *) b - b->bh.prevfree)->bsize == b->bh.prevfree);
|
||||||
|
b = BFH(((char *) b) - b->bh.prevfree);
|
||||||
|
b->bh.bsize -= size;
|
||||||
|
} else {
|
||||||
|
|
||||||
|
/* The previous buffer isn't allocated. Insert this buffer
|
||||||
|
on the free list as an isolated free block. */
|
||||||
|
|
||||||
|
_assert_(bg->freelist.ql.blink->ql.flink == &bg->freelist);
|
||||||
|
_assert_(bg->freelist.ql.flink->ql.blink == &bg->freelist);
|
||||||
|
b->ql.flink = &bg->freelist;
|
||||||
|
b->ql.blink = bg->freelist.ql.blink;
|
||||||
|
bg->freelist.ql.blink = b;
|
||||||
|
b->ql.blink->ql.flink = b;
|
||||||
|
b->bh.bsize = -b->bh.bsize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Now we look at the next buffer in memory, located by advancing from
|
||||||
|
the start of this buffer by its size, to see if that buffer is
|
||||||
|
free. If it is, we combine this buffer with the next one in
|
||||||
|
memory, dechaining the second buffer from the free list. */
|
||||||
|
|
||||||
|
bn = BFH(((char *) b) + b->bh.bsize);
|
||||||
|
if (bn->bh.bsize > 0) {
|
||||||
|
|
||||||
|
/* The buffer is free. Remove it from the free list and add
|
||||||
|
its size to that of our buffer. */
|
||||||
|
|
||||||
|
_assert_(BH((char *) bn + bn->bh.bsize)->prevfree == bn->bh.bsize);
|
||||||
|
_assert_(bn->ql.blink->ql.flink == bn);
|
||||||
|
_assert_(bn->ql.flink->ql.blink == bn);
|
||||||
|
bn->ql.blink->ql.flink = bn->ql.flink;
|
||||||
|
bn->ql.flink->ql.blink = bn->ql.blink;
|
||||||
|
b->bh.bsize += bn->bh.bsize;
|
||||||
|
|
||||||
|
/* Finally, advance to the buffer that follows the newly
|
||||||
|
consolidated free block. We must set its backpointer to the
|
||||||
|
head of the consolidated free block. We know the next block
|
||||||
|
must be an allocated block because the process of recombination
|
||||||
|
guarantees that two free blocks will never be contiguous in
|
||||||
|
memory. */
|
||||||
|
|
||||||
|
bn = BFH(((char *) b) + b->bh.bsize);
|
||||||
|
}
|
||||||
|
#ifdef FreeWipe
|
||||||
|
V memset(((char *) b) + sizeof(struct bfhead), 0x55,
|
||||||
|
(MemSize) (b->bh.bsize - sizeof(struct bfhead)));
|
||||||
|
#endif
|
||||||
|
_assert_(bn->bh.bsize < 0);
|
||||||
|
|
||||||
|
/* The next buffer is allocated. Set the backpointer in it to point
|
||||||
|
to this buffer; the previous free buffer in memory. */
|
||||||
|
|
||||||
|
bn->bh.prevfree = b->bh.bsize;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* BPOOL -- Add a region of memory to the buffer pool. */
|
||||||
|
|
||||||
|
void luat_bpool(luat_bget_t* bg, void *buf, bufsize len)
|
||||||
|
{
|
||||||
|
struct bfhead *b = BFH(buf);
|
||||||
|
struct bhead *bn;
|
||||||
|
|
||||||
|
#ifdef SizeQuant
|
||||||
|
len &= ~(SizeQuant - 1);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/* Since the block is initially occupied by a single free buffer,
|
||||||
|
it had better not be (much) larger than the largest buffer
|
||||||
|
whose size we can store in bhead.bsize. */
|
||||||
|
|
||||||
|
_assert_(len - sizeof(struct bhead) <= -((bufsize) ESent + 1));
|
||||||
|
|
||||||
|
/* Clear the backpointer at the start of the block to indicate that
|
||||||
|
there is no free block prior to this one. That blocks
|
||||||
|
recombination when the first block in memory is released. */
|
||||||
|
|
||||||
|
b->bh.prevfree = 0;
|
||||||
|
|
||||||
|
/* Chain the new block to the free list. */
|
||||||
|
|
||||||
|
_assert_(bg->freelist.ql.blink->ql.flink == &bg->freelist);
|
||||||
|
_assert_(bg->freelist.ql.flink->ql.blink == &bg->freelist);
|
||||||
|
b->ql.flink = &bg->freelist;
|
||||||
|
b->ql.blink = bg->freelist.ql.blink;
|
||||||
|
bg->freelist.ql.blink = b;
|
||||||
|
b->ql.blink->ql.flink = b;
|
||||||
|
|
||||||
|
/* Create a dummy allocated buffer at the end of the pool. This dummy
|
||||||
|
buffer is seen when a buffer at the end of the pool is released and
|
||||||
|
blocks recombination of the last buffer with the dummy buffer at
|
||||||
|
the end. The length in the dummy buffer is set to the largest
|
||||||
|
negative number to denote the end of the pool for diagnostic
|
||||||
|
routines (this specific value is not counted on by the actual
|
||||||
|
allocation and release functions). */
|
||||||
|
|
||||||
|
len -= sizeof(struct bhead);
|
||||||
|
b->bh.bsize = (bufsize) len;
|
||||||
|
#ifdef FreeWipe
|
||||||
|
V memset(((char *) b) + sizeof(struct bfhead), 0x55,
|
||||||
|
(MemSize) (len - sizeof(struct bfhead)));
|
||||||
|
#endif
|
||||||
|
bn = BH(((char *) b) + len);
|
||||||
|
bn->prevfree = (bufsize) len;
|
||||||
|
/* Definition of ESent assumes two's complement! */
|
||||||
|
_assert_((~0) == -1);
|
||||||
|
bn->bsize = ESent;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef BufStats
|
||||||
|
|
||||||
|
/* BSTATS -- Return buffer allocation free space statistics. */
|
||||||
|
|
||||||
|
void luat_bstats(luat_bget_t* bg, bufsize *curalloc, bufsize *totfree, bufsize *maxfree, unsigned long *nget, unsigned long *nrel)
|
||||||
|
{
|
||||||
|
struct bfhead *b = bg->freelist.ql.flink;
|
||||||
|
|
||||||
|
*nget = bg->numget;
|
||||||
|
*nrel = bg->numrel;
|
||||||
|
*curalloc = bg->totalloc;
|
||||||
|
*totfree = 0;
|
||||||
|
*maxfree = -1;
|
||||||
|
while (b != &bg->freelist) {
|
||||||
|
_assert_(b->bh.bsize > 0);
|
||||||
|
*totfree += b->bh.bsize;
|
||||||
|
if (b->bh.bsize > *maxfree) {
|
||||||
|
*maxfree = b->bh.bsize;
|
||||||
|
}
|
||||||
|
b = b->ql.flink; /* Link to next buffer */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bufsize luat_bstatsmaxget(luat_bget_t* bg)
|
||||||
|
{
|
||||||
|
return bg->maxalloc;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif /* BufStats */
|
||||||
@@ -0,0 +1,514 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lundump.c,v 2.44.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** load precompiled Lua chunks
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lundump_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "ldebug.h"
|
||||||
|
#include "ldo.h"
|
||||||
|
#include "lfunc.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lobject.h"
|
||||||
|
#include "lstring.h"
|
||||||
|
#include "lundump.h"
|
||||||
|
#include "lzio.h"
|
||||||
|
|
||||||
|
#include "luat_base.h"
|
||||||
|
#include "luat_fs.h"
|
||||||
|
|
||||||
|
#define LUAT_LOG_TAG "undump"
|
||||||
|
#include "luat_log.h"
|
||||||
|
|
||||||
|
#define LUAT_UNDUMP_DEBUG 0
|
||||||
|
|
||||||
|
// 未开启VFS就不能使用mmap
|
||||||
|
#ifndef LUAT_USE_FS_VFS
|
||||||
|
#ifdef LUAT_USE_MEMORY_OPTIMIZATION_CODE_MMAP
|
||||||
|
#undef LUAT_USE_MEMORY_OPTIMIZATION_CODE_MMAP
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(luai_verifycode)
|
||||||
|
/* verifier hook signature is luai_verifycode(L, f): the old (L, b, f) form
|
||||||
|
** referenced a nonexistent 'buff' at the call site, so a custom verifier
|
||||||
|
** could never be compiled in */
|
||||||
|
#define luai_verifycode(L,f) /* empty */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
size_t ptr_offset = 0;
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
size_t code_size = 0;
|
||||||
|
size_t code_max = 0;
|
||||||
|
size_t proto_size = 0;
|
||||||
|
size_t const_size = 0;
|
||||||
|
size_t debug_size = 0;
|
||||||
|
size_t str_size = 0;
|
||||||
|
size_t max_pc = 0;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
lua_State *L;
|
||||||
|
ZIO *Z;
|
||||||
|
const char *name;
|
||||||
|
} LoadState;
|
||||||
|
|
||||||
|
|
||||||
|
static l_noret error(LoadState *S, const char *why) {
|
||||||
|
luaO_pushfstring(S->L, "%s: %s precompiled chunk", S->name, why);
|
||||||
|
luaD_throw(S->L, LUA_ERRSYNTAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** All high-level loads go through LoadVector; you can change it to
|
||||||
|
** adapt to the endianness of the input
|
||||||
|
*/
|
||||||
|
#define LoadVector(S,b,n) LoadBlock(S,b,(n)*sizeof((b)[0]))
|
||||||
|
|
||||||
|
static void LoadBlock (LoadState *S, void *b, size_t size) {
|
||||||
|
ptr_offset += size;
|
||||||
|
if (luaZ_read(S->Z, b, size) != 0)
|
||||||
|
error(S, "truncated");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#define LoadVar(S,x) LoadVector(S,&x,1)
|
||||||
|
|
||||||
|
|
||||||
|
static lu_byte LoadByte (LoadState *S) {
|
||||||
|
lu_byte x;
|
||||||
|
LoadVar(S, x);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int LoadInt (LoadState *S) {
|
||||||
|
int x;
|
||||||
|
LoadVar(S, x);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static lua_Number LoadNumber (LoadState *S) {
|
||||||
|
lua_Number x;
|
||||||
|
LoadVar(S, x);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static lua_Integer LoadInteger (LoadState *S) {
|
||||||
|
lua_Integer x;
|
||||||
|
LoadVar(S, x);
|
||||||
|
return x;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifndef LoadF
|
||||||
|
typedef struct LoadF {
|
||||||
|
int n; /* number of pre-read characters */
|
||||||
|
FILE *f; /* file being read */
|
||||||
|
char buff[BUFSIZ]; /* area for reading file */
|
||||||
|
} LoadF;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(__LUATOS_SMALL_RAM__) && defined(__LUATOS_SCRIPT_BASE__)
|
||||||
|
/*
|
||||||
|
** creates a new string object
|
||||||
|
*/
|
||||||
|
static TString *static_createstrobj (lua_State *L, size_t l, int tag, unsigned int h) {
|
||||||
|
TString *ts;
|
||||||
|
GCObject *o;
|
||||||
|
o = luaC_newobj(L, tag, sizeof(TString) + l);
|
||||||
|
ts = gco2ts(o);
|
||||||
|
ts->hash = h;
|
||||||
|
ts->extra = 0;
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
** checks whether short string exists and reuses it or creates a new one
|
||||||
|
*/
|
||||||
|
static TString *static_internshrstr (lua_State *L, const char *str, size_t l) {
|
||||||
|
TString *ts;
|
||||||
|
global_State *g = G(L);
|
||||||
|
unsigned int h = luaS_hash(str, l, g->seed);
|
||||||
|
TString **list = &g->strt.hash[lmod(h, g->strt.size)];
|
||||||
|
lua_assert(str != NULL); /* otherwise 'memcmp'/'memcpy' are undefined */
|
||||||
|
for (ts = *list; ts != NULL; ts = ts->u.hnext) {
|
||||||
|
if (l == ts->shrlen &&
|
||||||
|
(memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
|
||||||
|
/* found! */
|
||||||
|
if (isdead(g, ts)) /* dead (but not collected yet)? */
|
||||||
|
changewhite(ts); /* resurrect it */
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2) {
|
||||||
|
luaS_resize(L, g->strt.size * 2);
|
||||||
|
list = &g->strt.hash[lmod(h, g->strt.size)]; /* recompute with new size */
|
||||||
|
}
|
||||||
|
ts = static_createstrobj(L, 4, LUA_TSHRSTR, h);
|
||||||
|
ts->static_flag = 1;
|
||||||
|
memcpy(cast(char *, (ts)) + sizeof(UTString), &str, 4);
|
||||||
|
ts->shrlen = cast_byte(l);
|
||||||
|
ts->u.hnext = *list;
|
||||||
|
*list = ts;
|
||||||
|
g->strt.nuse++;
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static TString *LoadString (LoadState *S, Proto *p) {
|
||||||
|
size_t size = LoadByte(S);
|
||||||
|
TString *ts;
|
||||||
|
if (size == 0xFF)
|
||||||
|
LoadVar(S, size);
|
||||||
|
#if defined(__LUATOS_SMALL_RAM__) && defined(__LUATOS_SCRIPT_BASE__)
|
||||||
|
char* ptr = (char*)luat_vfs_mmap(((LoadF*)S->Z->data)->f);
|
||||||
|
uint32_t offset;
|
||||||
|
if (ptr && size) {
|
||||||
|
offset = (uint32_t)ptr + ptr_offset - __LUATOS_SCRIPT_BASE__;
|
||||||
|
char temp[128];
|
||||||
|
uint32_t done_len = size;
|
||||||
|
do {
|
||||||
|
if (done_len > sizeof(temp)){
|
||||||
|
LoadVector(S, temp, sizeof(temp));
|
||||||
|
done_len -= sizeof(temp);
|
||||||
|
} else {
|
||||||
|
LoadVector(S, temp, done_len);
|
||||||
|
done_len = 0;
|
||||||
|
}
|
||||||
|
}while(done_len);
|
||||||
|
if (--size <= LUAI_MAXSHORTLEN) { /* short string? */
|
||||||
|
ts = static_internshrstr(S->L, offset + __LUATOS_SCRIPT_BASE__, size);
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
str_size+= (4 + sizeof(TString) + (8 - 1)) & (~(8 - 1));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
else { /* long string */
|
||||||
|
ts = static_createstrobj(S->L, 0, LUA_TLNGSTR, G(S->L)->seed);
|
||||||
|
ts->static_flag = (offset >> 15) + 1;
|
||||||
|
ts->u.static_offset = offset & 0x00007fff;
|
||||||
|
ts->u.lnglen = size;
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
str_size+= (sizeof(TString) + (8 - 1)) & (~(8 - 1));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
size = 0;
|
||||||
|
#else
|
||||||
|
if (size == 0)
|
||||||
|
return NULL;
|
||||||
|
else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */
|
||||||
|
char buff[LUAI_MAXSHORTLEN];
|
||||||
|
LoadVector(S, buff, size);
|
||||||
|
ts = luaS_newlstr(S->L, buff, size);
|
||||||
|
}
|
||||||
|
else { /* long string */
|
||||||
|
if (size > (SIZE_MAX / 2))
|
||||||
|
error(S, "string size overflow");
|
||||||
|
ts = luaS_createlngstrobj(S->L, size);
|
||||||
|
setsvalue2n(S->L, S->L->top, ts); /* anchor it while loading */
|
||||||
|
luaD_inctop(S->L);
|
||||||
|
LoadVector(S, getstr(ts), size); /* load directly in final place */
|
||||||
|
S->L->top--; /* pop anchored string */
|
||||||
|
}
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
str_size+= (size + sizeof(TString) + (8 - 1)) & (~(8 - 1));
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
luaC_objbarrier(S->L, p, ts);
|
||||||
|
|
||||||
|
|
||||||
|
return ts;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
static void LoadCode (LoadState *S, Proto *f) {
|
||||||
|
int n = LoadInt(S);
|
||||||
|
f->sizecode = n;
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
code_max += n * sizeof(Instruction);
|
||||||
|
#endif
|
||||||
|
#ifdef LUAT_USE_MEMORY_OPTIMIZATION_CODE_MMAP
|
||||||
|
#if LUAT_UNDUMP_DEBUG
|
||||||
|
// LLOGD("try mmap %p %p %p", S, S->Z, S->Z->data);
|
||||||
|
#endif
|
||||||
|
char* ptr = (char*)luat_fs_mmap(((LoadF*)S->Z->data)->f);
|
||||||
|
Instruction inst[1];
|
||||||
|
if (ptr) {
|
||||||
|
f->code = (Instruction*)(ptr + ptr_offset);
|
||||||
|
for (size_t i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
LoadVector(S, &inst, 1);
|
||||||
|
}
|
||||||
|
#if LUAT_UNDUMP_DEBUG
|
||||||
|
LLOGD("code in rom");
|
||||||
|
#endif
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
// 调试时务必打开
|
||||||
|
#if LUAT_UNDUMP_DEBUG
|
||||||
|
LLOGD("code in ram");
|
||||||
|
code_size += ((n * sizeof(Instruction)) + (8 - 1)) & (~(8 - 1));
|
||||||
|
#endif
|
||||||
|
f->code = luaM_newvector(S->L, n, Instruction);
|
||||||
|
LoadVector(S, f->code, n);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void LoadFunction(LoadState *S, Proto *f, TString *psource);
|
||||||
|
|
||||||
|
|
||||||
|
static void LoadConstants (LoadState *S, Proto *f) {
|
||||||
|
int i;
|
||||||
|
int n = LoadInt(S);
|
||||||
|
f->k = luaM_newvector(S->L, n, TValue);
|
||||||
|
f->sizek = n;
|
||||||
|
for (i = 0; i < n; i++)
|
||||||
|
setnilvalue(&f->k[i]);
|
||||||
|
for (i = 0; i < n; i++) {
|
||||||
|
TValue *o = &f->k[i];
|
||||||
|
int t = LoadByte(S);
|
||||||
|
switch (t) {
|
||||||
|
case LUA_TNIL:
|
||||||
|
setnilvalue(o);
|
||||||
|
break;
|
||||||
|
case LUA_TBOOLEAN:
|
||||||
|
setbvalue(o, LoadByte(S));
|
||||||
|
break;
|
||||||
|
case LUA_TNUMFLT:
|
||||||
|
setfltvalue(o, LoadNumber(S));
|
||||||
|
break;
|
||||||
|
case LUA_TNUMINT:
|
||||||
|
setivalue(o, LoadInteger(S));
|
||||||
|
break;
|
||||||
|
case LUA_TSHRSTR:
|
||||||
|
case LUA_TLNGSTR:
|
||||||
|
setsvalue2n(S->L, o, LoadString(S, f));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
lua_assert(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
const_size += (n * sizeof(TValue) + (8 - 1)) & (~(8 - 1));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void LoadProtos (LoadState *S, Proto *f) {
|
||||||
|
int i;
|
||||||
|
int n = LoadInt(S);
|
||||||
|
f->p = luaM_newvector(S->L, n, Proto *);
|
||||||
|
f->sizep = n;
|
||||||
|
for (i = 0; i < n; i++)
|
||||||
|
f->p[i] = NULL;
|
||||||
|
for (i = 0; i < n; i++) {
|
||||||
|
f->p[i] = luaF_newproto(S->L);
|
||||||
|
luaC_objbarrier(S->L, f, f->p[i]);
|
||||||
|
LoadFunction(S, f->p[i], f->source);
|
||||||
|
}
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
proto_size += (sizeof(Proto) + (8 - 1)) & (~(8 - 1));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void LoadUpvalues (LoadState *S, Proto *f) {
|
||||||
|
int i, n;
|
||||||
|
n = LoadInt(S);
|
||||||
|
f->upvalues = luaM_newvector(S->L, n, Upvaldesc);
|
||||||
|
f->sizeupvalues = n;
|
||||||
|
for (i = 0; i < n; i++)
|
||||||
|
f->upvalues[i].name = NULL;
|
||||||
|
for (i = 0; i < n; i++) {
|
||||||
|
f->upvalues[i].instack = LoadByte(S);
|
||||||
|
f->upvalues[i].idx = LoadByte(S);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void LoadDebug (LoadState *S, Proto *f) {
|
||||||
|
int i, n;
|
||||||
|
n = LoadInt(S);
|
||||||
|
f->sizelineinfo = n;
|
||||||
|
f->lineinfo = NULL;
|
||||||
|
#ifdef LUAT_USE_MEMORY_OPTIMIZATION_CODE_MMAP
|
||||||
|
if (n > 0) {
|
||||||
|
uint8_t* ptr = (uint8_t*)luat_fs_mmap(((LoadF*)S->Z->data)->f);
|
||||||
|
int inst[1];
|
||||||
|
if (ptr) {
|
||||||
|
f->lineinfo = (int*)(ptr + ptr_offset);
|
||||||
|
for (size_t i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
LoadVector(S, &inst, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
if (n > 0 && f->lineinfo == NULL) {
|
||||||
|
f->lineinfo = luaM_newvector(S->L, n, int);
|
||||||
|
LoadVector(S, f->lineinfo, n);
|
||||||
|
}
|
||||||
|
// #ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
// debug_size += (f->sizelineinfo * sizeof(int) + (8 - 1)) & (~(8 - 1));
|
||||||
|
// #endif
|
||||||
|
// #endif
|
||||||
|
n = LoadInt(S);
|
||||||
|
f->locvars = luaM_newvector(S->L, n, LocVar);
|
||||||
|
f->sizelocvars = n;
|
||||||
|
for (i = 0; i < n; i++)
|
||||||
|
f->locvars[i].varname = NULL;
|
||||||
|
for (i = 0; i < n; i++) {
|
||||||
|
f->locvars[i].varname = LoadString(S, f);
|
||||||
|
f->locvars[i].startpc = LoadInt(S);
|
||||||
|
f->locvars[i].endpc = LoadInt(S);
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
if (f->locvars[i].startpc > max_pc)
|
||||||
|
{
|
||||||
|
max_pc = f->locvars[i].startpc;
|
||||||
|
}
|
||||||
|
if (f->locvars[i].endpc > max_pc)
|
||||||
|
{
|
||||||
|
max_pc = f->locvars[i].endpc;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
n = LoadInt(S);
|
||||||
|
if (n > f->sizeupvalues) /* stripped chunk: n may be 0 while sizeupvalues > 0 */
|
||||||
|
error(S, "bad upvalue names count");
|
||||||
|
for (i = 0; i < n; i++)
|
||||||
|
f->upvalues[i].name = LoadString(S, f);
|
||||||
|
|
||||||
|
#ifdef LUAT_UNDUMP_DEBUG
|
||||||
|
debug_size += f->sizelocvars * (sizeof(LocVar) + (8 - 1)) & (~(8 - 1));
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void LoadFunction (LoadState *S, Proto *f, TString *psource) {
|
||||||
|
f->source = LoadString(S, f);
|
||||||
|
if (f->source == NULL) /* no source in dump? */
|
||||||
|
f->source = psource; /* reuse parent's source */
|
||||||
|
f->linedefined = LoadInt(S);
|
||||||
|
f->lastlinedefined = LoadInt(S);
|
||||||
|
f->numparams = LoadByte(S);
|
||||||
|
f->is_vararg = LoadByte(S);
|
||||||
|
f->maxstacksize = LoadByte(S);
|
||||||
|
LoadCode(S, f);
|
||||||
|
LoadConstants(S, f);
|
||||||
|
LoadUpvalues(S, f);
|
||||||
|
LoadProtos(S, f);
|
||||||
|
LoadDebug(S, f);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void checkliteral (LoadState *S, const char *s, const char *msg) {
|
||||||
|
char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */
|
||||||
|
size_t len = strlen(s);
|
||||||
|
LoadVector(S, buff, len);
|
||||||
|
if (memcmp(s, buff, len) != 0)
|
||||||
|
error(S, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void fchecksize (LoadState *S, size_t size, const char *tname) {
|
||||||
|
if (LoadByte(S) != size) {
|
||||||
|
LLOGD("固件和脚本的bit位不匹配,请连同底层固件重新下载");
|
||||||
|
error(S, luaO_pushfstring(S->L, "%s size mismatch in", tname));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#define checksize(S,t) fchecksize(S,sizeof(t),#t)
|
||||||
|
|
||||||
|
static void checkHeader (LoadState *S) {
|
||||||
|
checkliteral(S, LUA_SIGNATURE + 1, "not a"); /* 1st char already checked */
|
||||||
|
if (LoadByte(S) != LUAC_VERSION)
|
||||||
|
error(S, "version mismatch in");
|
||||||
|
if (LoadByte(S) != LUAC_FORMAT)
|
||||||
|
error(S, "format mismatch in");
|
||||||
|
checkliteral(S, LUAC_DATA, "corrupted");
|
||||||
|
checksize(S, int);
|
||||||
|
checksize(S, size_t);
|
||||||
|
checksize(S, Instruction);
|
||||||
|
checksize(S, lua_Integer);
|
||||||
|
checksize(S, lua_Number);
|
||||||
|
if (LoadInteger(S) != LUAC_INT)
|
||||||
|
error(S, "endianness mismatch in");
|
||||||
|
if (LoadNumber(S) != LUAC_NUM)
|
||||||
|
error(S, "float format mismatch in");
|
||||||
|
}
|
||||||
|
|
||||||
|
extern void luat_os_print_heapinfo(const char* tag);
|
||||||
|
|
||||||
|
/*
|
||||||
|
** load precompiled chunk
|
||||||
|
*/
|
||||||
|
LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) {
|
||||||
|
LoadState S;
|
||||||
|
LClosure *cl;
|
||||||
|
TString *ts = NULL;
|
||||||
|
|
||||||
|
// 复位偏移量数据
|
||||||
|
ptr_offset = 0;
|
||||||
|
ptr_offset ++; // 之前的方法已经读取了一个字节
|
||||||
|
if (*name == '@' || *name == '=')
|
||||||
|
S.name = name + 1;
|
||||||
|
else if (*name == LUA_SIGNATURE[0])
|
||||||
|
S.name = "binary string";
|
||||||
|
else
|
||||||
|
S.name = name;
|
||||||
|
S.L = L;
|
||||||
|
S.Z = Z;
|
||||||
|
checkHeader(&S);
|
||||||
|
cl = luaF_newLclosure(L, LoadByte(&S));
|
||||||
|
setclLvalue(L, L->top, cl);
|
||||||
|
luaD_inctop(L);
|
||||||
|
cl->p = luaF_newproto(L);
|
||||||
|
luaC_objbarrier(L, cl, cl->p); // add by wendal, refer: https://github.com/lua/lua/commit/f5eb809d3f1da13683cd02184042e67228206205
|
||||||
|
if (*name == '@') {
|
||||||
|
// 既然是从文件加载,那它就能作为调试信息中的源文件名
|
||||||
|
size_t size = strlen(name);
|
||||||
|
if (size > 0 && size <= LUAI_MAXSHORTLEN) {
|
||||||
|
ts = luaS_newlstr(S.L, name, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LoadFunction(&S, cl->p, ts);
|
||||||
|
|
||||||
|
lua_assert(cl->nupvalues == cl->p->sizeupvalues);
|
||||||
|
luai_verifycode(L, cl->p);
|
||||||
|
|
||||||
|
// 打印各部分的内存消耗
|
||||||
|
#if LUAT_UNDUMP_DEBUG
|
||||||
|
LLOGD("str_size %d", str_size);
|
||||||
|
LLOGD("debug_size %d", debug_size);
|
||||||
|
LLOGD("const_size now %d", const_size);
|
||||||
|
LLOGD("code_size now %d", code_size);
|
||||||
|
LLOGD("code max now %d", code_max);
|
||||||
|
LLOGD("ptr_offset %d", ptr_offset);
|
||||||
|
LLOGD("proto size now %d", proto_size);
|
||||||
|
LLOGD("max pc %d", max_pc);
|
||||||
|
luat_os_print_heapinfo("func");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
return cl;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lutf8lib.c,v 1.16.1.1 2017/04/19 17:29:57 roberto Exp $
|
||||||
|
** Standard library for UTF-8 manipulation
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lutf8lib_c
|
||||||
|
#define LUA_LIB
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <assert.h>
|
||||||
|
#include <limits.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "lauxlib.h"
|
||||||
|
#include "lualib.h"
|
||||||
|
|
||||||
|
#define MAXUNICODE 0x10FFFF
|
||||||
|
|
||||||
|
#define iscont(p) ((*(p) & 0xC0) == 0x80)
|
||||||
|
|
||||||
|
|
||||||
|
/* from strlib */
|
||||||
|
/* translate a relative string position: negative means back from end */
|
||||||
|
static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
|
||||||
|
if (pos >= 0) return pos;
|
||||||
|
else if (0u - (size_t)pos > len) return 0;
|
||||||
|
else return (lua_Integer)len + pos + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.
|
||||||
|
*/
|
||||||
|
static const char *utf8_decode (const char *o, int *val) {
|
||||||
|
static const unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};
|
||||||
|
const unsigned char *s = (const unsigned char *)o;
|
||||||
|
unsigned int c = s[0];
|
||||||
|
unsigned int res = 0; /* final result */
|
||||||
|
if (c < 0x80) /* ascii? */
|
||||||
|
res = c;
|
||||||
|
else {
|
||||||
|
int count = 0; /* to count number of continuation bytes */
|
||||||
|
while (c & 0x40) { /* still have continuation bytes? */
|
||||||
|
int cc = s[++count]; /* read next byte */
|
||||||
|
if ((cc & 0xC0) != 0x80) /* not a continuation byte? */
|
||||||
|
return NULL; /* invalid byte sequence */
|
||||||
|
res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
|
||||||
|
c <<= 1; /* to test next bit */
|
||||||
|
}
|
||||||
|
res |= ((c & 0x7F) << (count * 5)); /* add first byte */
|
||||||
|
if (count > 3 || res > MAXUNICODE || res <= limits[count])
|
||||||
|
return NULL; /* invalid byte sequence */
|
||||||
|
s += count; /* skip continuation bytes read */
|
||||||
|
}
|
||||||
|
if (val) *val = res;
|
||||||
|
return (const char *)s + 1; /* +1 to include first byte */
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** utf8len(s [, i [, j]]) --> number of characters that start in the
|
||||||
|
** range [i,j], or nil + current position if 's' is not well formed in
|
||||||
|
** that interval
|
||||||
|
*/
|
||||||
|
static int utflen (lua_State *L) {
|
||||||
|
int n = 0;
|
||||||
|
size_t len;
|
||||||
|
const char *s = luaL_checklstring(L, 1, &len);
|
||||||
|
lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
|
||||||
|
lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
|
||||||
|
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
|
||||||
|
"initial position out of string");
|
||||||
|
luaL_argcheck(L, --posj < (lua_Integer)len, 3,
|
||||||
|
"final position out of string");
|
||||||
|
while (posi <= posj) {
|
||||||
|
const char *s1 = utf8_decode(s + posi, NULL);
|
||||||
|
if (s1 == NULL) { /* conversion error? */
|
||||||
|
lua_pushnil(L); /* return nil ... */
|
||||||
|
lua_pushinteger(L, posi + 1); /* ... and current position */
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
posi = s1 - s;
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
lua_pushinteger(L, n);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** codepoint(s, [i, [j]]) -> returns codepoints for all characters
|
||||||
|
** that start in the range [i,j]
|
||||||
|
*/
|
||||||
|
static int codepoint (lua_State *L) {
|
||||||
|
size_t len;
|
||||||
|
const char *s = luaL_checklstring(L, 1, &len);
|
||||||
|
lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
|
||||||
|
lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
|
||||||
|
int n;
|
||||||
|
const char *se;
|
||||||
|
luaL_argcheck(L, posi >= 1, 2, "out of range");
|
||||||
|
luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range");
|
||||||
|
if (posi > pose) return 0; /* empty interval; return no values */
|
||||||
|
if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */
|
||||||
|
return luaL_error(L, "string slice too long");
|
||||||
|
n = (int)(pose - posi) + 1;
|
||||||
|
luaL_checkstack(L, n, "string slice too long");
|
||||||
|
n = 0;
|
||||||
|
se = s + pose;
|
||||||
|
for (s += posi - 1; s < se;) {
|
||||||
|
int code;
|
||||||
|
s = utf8_decode(s, &code);
|
||||||
|
if (s == NULL)
|
||||||
|
return luaL_error(L, "invalid UTF-8 code");
|
||||||
|
lua_pushinteger(L, code);
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void pushutfchar (lua_State *L, int arg) {
|
||||||
|
lua_Integer code = luaL_checkinteger(L, arg);
|
||||||
|
luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, "value out of range");
|
||||||
|
lua_pushfstring(L, "%U", (long)code);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** utfchar(n1, n2, ...) -> char(n1)..char(n2)...
|
||||||
|
*/
|
||||||
|
static int utfchar (lua_State *L) {
|
||||||
|
int n = lua_gettop(L); /* number of arguments */
|
||||||
|
if (n == 1) /* optimize common case of single char */
|
||||||
|
pushutfchar(L, 1);
|
||||||
|
else {
|
||||||
|
int i;
|
||||||
|
luaL_Buffer b;
|
||||||
|
luaL_buffinit(L, &b);
|
||||||
|
for (i = 1; i <= n; i++) {
|
||||||
|
pushutfchar(L, i);
|
||||||
|
luaL_addvalue(&b);
|
||||||
|
}
|
||||||
|
luaL_pushresult(&b);
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
** offset(s, n, [i]) -> index where n-th character counting from
|
||||||
|
** position 'i' starts; 0 means character at 'i'.
|
||||||
|
*/
|
||||||
|
static int byteoffset (lua_State *L) {
|
||||||
|
size_t len;
|
||||||
|
const char *s = luaL_checklstring(L, 1, &len);
|
||||||
|
lua_Integer n = luaL_checkinteger(L, 2);
|
||||||
|
lua_Integer posi = (n >= 0) ? 1 : len + 1;
|
||||||
|
posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
|
||||||
|
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
|
||||||
|
"position out of range");
|
||||||
|
if (n == 0) {
|
||||||
|
/* find beginning of current byte sequence */
|
||||||
|
while (posi > 0 && iscont(s + posi)) posi--;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (iscont(s + posi))
|
||||||
|
return luaL_error(L, "initial position is a continuation byte");
|
||||||
|
if (n < 0) {
|
||||||
|
while (n < 0 && posi > 0) { /* move back */
|
||||||
|
do { /* find beginning of previous character */
|
||||||
|
posi--;
|
||||||
|
} while (posi > 0 && iscont(s + posi));
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
n--; /* do not move for 1st character */
|
||||||
|
while (n > 0 && posi < (lua_Integer)len) {
|
||||||
|
do { /* find beginning of next character */
|
||||||
|
posi++;
|
||||||
|
} while (iscont(s + posi)); /* (cannot pass final '\0') */
|
||||||
|
n--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (n == 0) /* did it find given character? */
|
||||||
|
lua_pushinteger(L, posi + 1);
|
||||||
|
else /* no such character */
|
||||||
|
lua_pushnil(L);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int iter_aux (lua_State *L) {
|
||||||
|
size_t len;
|
||||||
|
const char *s = luaL_checklstring(L, 1, &len);
|
||||||
|
lua_Integer n = lua_tointeger(L, 2) - 1;
|
||||||
|
if (n < 0) /* first iteration? */
|
||||||
|
n = 0; /* start from here */
|
||||||
|
else if (n < (lua_Integer)len) {
|
||||||
|
n++; /* skip current byte */
|
||||||
|
while (iscont(s + n)) n++; /* and its continuations */
|
||||||
|
}
|
||||||
|
if (n >= (lua_Integer)len)
|
||||||
|
return 0; /* no more codepoints */
|
||||||
|
else {
|
||||||
|
int code;
|
||||||
|
const char *next = utf8_decode(s + n, &code);
|
||||||
|
if (next == NULL || iscont(next))
|
||||||
|
return luaL_error(L, "invalid UTF-8 code");
|
||||||
|
lua_pushinteger(L, n + 1);
|
||||||
|
lua_pushinteger(L, code);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int iter_codes (lua_State *L) {
|
||||||
|
luaL_checkstring(L, 1);
|
||||||
|
lua_pushcfunction(L, iter_aux);
|
||||||
|
lua_pushvalue(L, 1);
|
||||||
|
lua_pushinteger(L, 0);
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* pattern to match a single UTF-8 character */
|
||||||
|
#define UTF8PATT "[\0-\x7F\xC2-\xF4][\x80-\xBF]*"
|
||||||
|
|
||||||
|
#include "rotable2.h"
|
||||||
|
static const rotable_Reg_t funcs[] = {
|
||||||
|
{"offset", ROREG_FUNC(byteoffset)},
|
||||||
|
{"codepoint", ROREG_FUNC(codepoint)},
|
||||||
|
{"char", ROREG_FUNC(utfchar)},
|
||||||
|
{"len", ROREG_FUNC(utflen)},
|
||||||
|
{"codes", ROREG_FUNC(iter_codes)},
|
||||||
|
/* placeholders */
|
||||||
|
{"charpattern", ROREG_STR(UTF8PATT)},
|
||||||
|
{NULL, ROREG_INT(0)}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
LUAMOD_API int luaopen_utf8 (lua_State *L) {
|
||||||
|
rotable2_newlib(L, funcs);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,68 @@
|
|||||||
|
/*
|
||||||
|
** $Id: lzio.c,v 1.37.1.1 2017/04/19 17:20:42 roberto Exp $
|
||||||
|
** Buffered streams
|
||||||
|
** See Copyright Notice in lua.h
|
||||||
|
*/
|
||||||
|
|
||||||
|
#define lzio_c
|
||||||
|
#define LUA_CORE
|
||||||
|
|
||||||
|
#include "lprefix.h"
|
||||||
|
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
|
||||||
|
#include "lua.h"
|
||||||
|
|
||||||
|
#include "llimits.h"
|
||||||
|
#include "lmem.h"
|
||||||
|
#include "lstate.h"
|
||||||
|
#include "lzio.h"
|
||||||
|
|
||||||
|
|
||||||
|
int luaZ_fill (ZIO *z) {
|
||||||
|
size_t size;
|
||||||
|
lua_State *L = z->L;
|
||||||
|
const char *buff;
|
||||||
|
lua_unlock(L);
|
||||||
|
buff = z->reader(L, z->data, &size);
|
||||||
|
lua_lock(L);
|
||||||
|
if (buff == NULL || size == 0)
|
||||||
|
return EOZ;
|
||||||
|
z->n = size - 1; /* discount char being returned */
|
||||||
|
z->p = buff;
|
||||||
|
return cast_uchar(*(z->p++));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
|
||||||
|
z->L = L;
|
||||||
|
z->reader = reader;
|
||||||
|
z->data = data;
|
||||||
|
z->n = 0;
|
||||||
|
z->p = NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/* --------------------------------------------------------------- read --- */
|
||||||
|
size_t luaZ_read (ZIO *z, void *b, size_t n) {
|
||||||
|
while (n) {
|
||||||
|
size_t m;
|
||||||
|
if (z->n == 0) { /* no bytes in buffer? */
|
||||||
|
if (luaZ_fill(z) == EOZ) /* try to read more */
|
||||||
|
return n; /* no more input; return number of missing bytes */
|
||||||
|
else {
|
||||||
|
z->n++; /* luaZ_fill consumed first byte; put it back */
|
||||||
|
z->p--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
|
||||||
|
memcpy(b, z->p, m);
|
||||||
|
z->n -= m;
|
||||||
|
z->p += m;
|
||||||
|
b = (char *)b + m;
|
||||||
|
n -= m;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
|
||||||
|
/**
|
||||||
|
* rotable 实现 lua下的只读table, 用于通常只用于库的注册.</p>
|
||||||
|
* 从原理上说, 是声明一个userdata内存块, 然后通过元表,将其伪装成table.<p/>
|
||||||
|
* 因为元表是共享的,而userdata内存块也很小(小于30字节),而且不会与方法的数量有关, 节省大量内存.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include "lua.h"
|
||||||
|
#include "rotable.h"
|
||||||
|
|
||||||
|
|
||||||
|
/* The lookup code uses binary search on sorted `rotable_Reg` arrays
|
||||||
|
* to find functions/methods. For a small number of elements a linear
|
||||||
|
* search might be faster. */
|
||||||
|
#ifndef ROTABLE_BINSEARCH_MIN
|
||||||
|
# define ROTABLE_BINSEARCH_MIN 5
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
#if LUA_VERSION_NUM < 503
|
||||||
|
/* on Lua 5.3 we use a lightuserdata in the uservalue of the
|
||||||
|
* userdata to hold the pointer to the luaL_Reg structure. Older
|
||||||
|
* Lua versions have to store it in the userdata payload. */
|
||||||
|
rotable_Reg const* p;
|
||||||
|
#endif
|
||||||
|
/* number of elements in the luaL_Reg array *if* it is sorted by
|
||||||
|
* name. We can use binary search in this case. Otherwise we need
|
||||||
|
* linear searches anyway and we can scan for the final `{NULL,0}`
|
||||||
|
* entry. `n` is 0 in this case. */
|
||||||
|
int n;
|
||||||
|
} rotable;
|
||||||
|
|
||||||
|
|
||||||
|
static char const unique_address[ 1 ] = { 0 };
|
||||||
|
|
||||||
|
|
||||||
|
static int reg_compare(void const* a, void const* b) {
|
||||||
|
return strcmp( (char const*)a, ((rotable_Reg const*)b)->name );
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static rotable* check_rotable( lua_State* L, int idx, char const* func ) {
|
||||||
|
rotable* t = (rotable*)lua_touserdata( L, idx );
|
||||||
|
if( t ) {
|
||||||
|
if( lua_getmetatable( L, idx ) ) {
|
||||||
|
lua_pushlightuserdata( L, (void*)unique_address );
|
||||||
|
lua_rawget( L, LUA_REGISTRYINDEX );
|
||||||
|
if( !lua_rawequal( L, -1, -2 ) )
|
||||||
|
t = 0;
|
||||||
|
lua_pop( L, 2 );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if( !t ) {
|
||||||
|
char const* type = lua_typename( L, lua_type( L, idx ) );
|
||||||
|
if( lua_type( L, idx ) == LUA_TLIGHTUSERDATA ) {
|
||||||
|
type = "light userdata";
|
||||||
|
} else if( lua_getmetatable( L, idx ) ) {
|
||||||
|
lua_getfield( L, -1, "__name" );
|
||||||
|
lua_replace( L, -2 ); /* we don't need the metatable anymore */
|
||||||
|
if( lua_type( L, -1 ) == LUA_TSTRING )
|
||||||
|
type = lua_tostring( L, -1 );
|
||||||
|
}
|
||||||
|
lua_pushfstring( L, "bad argument #%d to '%s' "
|
||||||
|
"(rotable expected, got %s)", idx, func, type );
|
||||||
|
lua_error( L );
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static rotable_Reg const* find_key( rotable_Reg const* p, int n,
|
||||||
|
char const* s ) {
|
||||||
|
if( s ) {
|
||||||
|
//if( n >= ROTABLE_BINSEARCH_MIN ) { /* binary search */
|
||||||
|
// return (rotable_Reg const*)bsearch( s, p, n, sizeof( *p ), reg_compare );
|
||||||
|
//} else { /* use linear scan */
|
||||||
|
for( ; p->name != NULL; ++p ) {
|
||||||
|
if( 0 == reg_compare( s, p ) )
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_func_index( lua_State* L ) {
|
||||||
|
char const* s = lua_tostring( L, 2 );
|
||||||
|
rotable_Reg const* p = (rotable_Reg const*)lua_touserdata( L, lua_upvalueindex( 1 ) );
|
||||||
|
rotable_Reg const* p2 = p;
|
||||||
|
int n = lua_tointeger( L, lua_upvalueindex( 2 ) );
|
||||||
|
p = find_key( p, n, s );
|
||||||
|
if( p ) {
|
||||||
|
if (p->func)
|
||||||
|
lua_pushcfunction( L, p->func );
|
||||||
|
else
|
||||||
|
lua_pushinteger(L, p->value);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// 看看第一个方法是不是__index, 如果是的话, 调用之
|
||||||
|
if (p2->name != NULL && !strcmp("__index", p2->name)) {
|
||||||
|
lua_pushcfunction(L, p2->func);
|
||||||
|
lua_pushvalue(L, 2);
|
||||||
|
lua_call(L, 1, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
lua_pushnil( L );
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_udata_index( lua_State* L ) {
|
||||||
|
rotable* t = (rotable*)lua_touserdata( L, 1 );
|
||||||
|
char const* s = lua_tostring( L, 2 );
|
||||||
|
#if LUA_VERSION_NUM < 503
|
||||||
|
rotable_Reg const* p = t->p;
|
||||||
|
#else
|
||||||
|
rotable_Reg const* p = 0;
|
||||||
|
lua_getuservalue( L, 1 );
|
||||||
|
p = (rotable_Reg const*)lua_touserdata( L, -1 );
|
||||||
|
rotable_Reg const* p2 = p;
|
||||||
|
#endif
|
||||||
|
p = find_key( p, t->n, s );
|
||||||
|
if( p ) {
|
||||||
|
if (p->func)
|
||||||
|
lua_pushcfunction( L, p->func );
|
||||||
|
else
|
||||||
|
lua_pushinteger(L, p->value);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// 看看第一个方法是不是__index, 如果是的话, 调用之
|
||||||
|
if (p2->name != NULL && !strcmp("__index", p2->name)) {
|
||||||
|
lua_pushcfunction(L, p2->func);
|
||||||
|
lua_pushvalue(L, 2);
|
||||||
|
lua_call(L, 1, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
lua_pushnil( L );
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_udata_len( lua_State* L ) {
|
||||||
|
lua_pushinteger( L, 0 );
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_iter( lua_State* L ) {
|
||||||
|
check_rotable( L, 1, "__pairs iterator" );
|
||||||
|
char const* s = lua_tostring( L, 2 );
|
||||||
|
rotable_Reg const* q = 0;
|
||||||
|
#if LUA_VERSION_NUM < 503
|
||||||
|
rotable_Reg const* p = t->p;
|
||||||
|
#else
|
||||||
|
rotable_Reg const* p = 0;
|
||||||
|
lua_getuservalue( L, 1 );
|
||||||
|
p = (rotable_Reg const*)lua_touserdata( L, -1 );
|
||||||
|
#endif
|
||||||
|
if( s ) {
|
||||||
|
// if( t->n >= ROTABLE_BINSEARCH_MIN ) { /* binary search */
|
||||||
|
// q = (rotable_Reg const*)bsearch( s, p, t->n, sizeof( *p ), reg_compare );
|
||||||
|
// if( q )
|
||||||
|
// ++q;
|
||||||
|
// else
|
||||||
|
// q = p + t->n;
|
||||||
|
// } else { /* use linear scan */
|
||||||
|
for( q = p; q->name != NULL; ++q ) {
|
||||||
|
if( 0 == reg_compare( s, q ) ) {
|
||||||
|
++q;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// }
|
||||||
|
} else
|
||||||
|
q = p;
|
||||||
|
if (q == NULL || q->name == NULL) {
|
||||||
|
|
||||||
|
}
|
||||||
|
else if( q->func ) {
|
||||||
|
lua_pushstring( L, q->name );
|
||||||
|
lua_pushcfunction( L, q->func );
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lua_pushstring( L, q->name );
|
||||||
|
lua_pushinteger( L, q->value );
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_udata_pairs( lua_State* L ) {
|
||||||
|
lua_pushcfunction( L, rotable_iter );
|
||||||
|
lua_pushvalue( L, 1 );
|
||||||
|
lua_pushnil( L );
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 与lua_newlib对应的函数, 用于生成一个库table,区别是lua_newlib生成普通table,这个函数生成rotable.
|
||||||
|
*/
|
||||||
|
|
||||||
|
void rotable_newlib( lua_State* L, void const* v ) {
|
||||||
|
rotable_Reg const* reg = (rotable_Reg const*)v;
|
||||||
|
rotable* t = (rotable*)lua_newuserdata( L, sizeof( *t ) );
|
||||||
|
lua_pushlightuserdata( L, (void*)unique_address );
|
||||||
|
lua_rawget( L, LUA_REGISTRYINDEX );
|
||||||
|
if( !lua_istable( L, -1 ) ) {
|
||||||
|
lua_pop( L, 1 );
|
||||||
|
lua_createtable( L, 0, 5 );
|
||||||
|
lua_pushcfunction( L, rotable_udata_index );
|
||||||
|
lua_setfield( L, -2, "__index" );
|
||||||
|
lua_pushcfunction( L, rotable_udata_len );
|
||||||
|
lua_setfield( L, -2, "__len" );
|
||||||
|
lua_pushcfunction( L, rotable_udata_pairs );
|
||||||
|
lua_setfield( L, -2, "__pairs" );
|
||||||
|
lua_pushboolean( L, 0 );
|
||||||
|
lua_setfield( L, -2, "__metatable" );
|
||||||
|
lua_pushliteral( L, "rotable" );
|
||||||
|
lua_setfield( L, -2, "__name" );
|
||||||
|
lua_pushlightuserdata( L, (void*)unique_address );
|
||||||
|
lua_pushvalue( L, -2 );
|
||||||
|
lua_rawset( L, LUA_REGISTRYINDEX );
|
||||||
|
}
|
||||||
|
lua_setmetatable( L, -2 );
|
||||||
|
#if LUA_VERSION_NUM < 503
|
||||||
|
t->p = reg;
|
||||||
|
#else
|
||||||
|
lua_pushlightuserdata( L, (void*)reg );
|
||||||
|
lua_setuservalue( L, -2 );
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为自定义对象也生成rotable形式的元表, 这个形式比rotable_newlib需要更多内存,但起码是一个解决办法.
|
||||||
|
*/
|
||||||
|
void rotable_newidx( lua_State* L, void const* v ) {
|
||||||
|
lua_pushlightuserdata( L, (void*)v);
|
||||||
|
lua_pushcclosure( L, rotable_func_index, 1 );
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
|
||||||
|
/**
|
||||||
|
* rotable 实现 lua下的只读table, 用于通常只用于库的注册.</p>
|
||||||
|
* 从原理上说, 是声明一个userdata内存块, 然后通过元表,将其伪装成table.<p/>
|
||||||
|
* 因为元表是共享的,而userdata内存块也很小(小于30字节),而且不会与方法的数量有关, 节省大量内存.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
#include <stddef.h>
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include "lua.h"
|
||||||
|
#include "rotable2.h"
|
||||||
|
|
||||||
|
|
||||||
|
/* The lookup code uses binary search on sorted `rotable_Reg` arrays
|
||||||
|
* to find functions/methods. For a small number of elements a linear
|
||||||
|
* search might be faster. */
|
||||||
|
#ifndef ROTABLE_BINSEARCH_MIN
|
||||||
|
# define ROTABLE_BINSEARCH_MIN 5
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
int n;
|
||||||
|
} rotable;
|
||||||
|
|
||||||
|
|
||||||
|
static char const unique_address[ 1 ] = { 0 };
|
||||||
|
|
||||||
|
|
||||||
|
static int reg_compare(void const* a, void const* b) {
|
||||||
|
return strcmp( (char const*)a, ((const rotable_Reg_t*)b)->name );
|
||||||
|
}
|
||||||
|
|
||||||
|
static int rotable_push_rovalue(lua_State *L, const rotable_Reg_t* q) {
|
||||||
|
switch (q->value.type)
|
||||||
|
{
|
||||||
|
case LUA_TFUNCTION:
|
||||||
|
lua_pushcfunction( L, q->value.value.func );
|
||||||
|
break;
|
||||||
|
case LUA_TINTEGER:
|
||||||
|
lua_pushinteger( L, q->value.value.intvalue );
|
||||||
|
break;
|
||||||
|
case LUA_TSTRING:
|
||||||
|
lua_pushstring( L, q->value.value.strvalue );
|
||||||
|
break;
|
||||||
|
case LUA_TNUMBER:
|
||||||
|
lua_pushnumber( L, q->value.value.numvalue );
|
||||||
|
break;
|
||||||
|
case LUA_TLIGHTUSERDATA:
|
||||||
|
lua_pushlightuserdata(L, q->value.value.ptr);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static rotable* check_rotable( lua_State* L, int idx, char const* func ) {
|
||||||
|
rotable* t = (rotable*)lua_touserdata( L, idx );
|
||||||
|
if( t ) {
|
||||||
|
if( lua_getmetatable( L, idx ) ) {
|
||||||
|
lua_pushlightuserdata( L, (void*)unique_address );
|
||||||
|
lua_rawget( L, LUA_REGISTRYINDEX );
|
||||||
|
if( !lua_rawequal( L, -1, -2 ) )
|
||||||
|
t = 0;
|
||||||
|
lua_pop( L, 2 );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if( !t ) {
|
||||||
|
char const* type = lua_typename( L, lua_type( L, idx ) );
|
||||||
|
if( lua_type( L, idx ) == LUA_TLIGHTUSERDATA ) {
|
||||||
|
type = "light userdata";
|
||||||
|
} else if( lua_getmetatable( L, idx ) ) {
|
||||||
|
lua_getfield( L, -1, "__name" );
|
||||||
|
lua_replace( L, -2 ); /* we don't need the metatable anymore */
|
||||||
|
if( lua_type( L, -1 ) == LUA_TSTRING )
|
||||||
|
type = lua_tostring( L, -1 );
|
||||||
|
}
|
||||||
|
lua_pushfstring( L, "bad argument #%d to '%s' "
|
||||||
|
"(rotable expected, got %s)", idx, func, type );
|
||||||
|
lua_error( L );
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static const rotable_Reg_t* find_key( const rotable_Reg_t* p, int n,
|
||||||
|
char const* s ) {
|
||||||
|
(void)n;
|
||||||
|
if( s ) {
|
||||||
|
for( ; p->name != NULL; ++p ) {
|
||||||
|
if( 0 == reg_compare( s, p ) )
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_func_index( lua_State* L ) {
|
||||||
|
char const* s = lua_tostring( L, 2 );
|
||||||
|
const rotable_Reg_t* p = (const rotable_Reg_t*)lua_touserdata( L, lua_upvalueindex( 1 ) );
|
||||||
|
const rotable_Reg_t* p2 = p;
|
||||||
|
int n = lua_tointeger( L, lua_upvalueindex( 2 ) );
|
||||||
|
p = find_key( p, n, s );
|
||||||
|
if( p ) {
|
||||||
|
rotable_push_rovalue(L, p);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// 看看第一个方法是不是__index, 如果是的话, 调用之
|
||||||
|
if (p2->name != NULL && !strcmp("__index", p2->name)) {
|
||||||
|
lua_pushcfunction(L, p2->value.value.func);
|
||||||
|
lua_pushvalue(L, 2);
|
||||||
|
lua_call(L, 1, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
lua_pushnil( L );
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_udata_index( lua_State* L ) {
|
||||||
|
rotable* t = (rotable*)lua_touserdata( L, 1 );
|
||||||
|
char const* s = lua_tostring( L, 2 );
|
||||||
|
const rotable_Reg_t* p = 0;
|
||||||
|
lua_getuservalue( L, 1 );
|
||||||
|
p = (const rotable_Reg_t*)lua_touserdata( L, -1 );
|
||||||
|
const rotable_Reg_t* p2 = p;
|
||||||
|
p = find_key( p, t->n, s );
|
||||||
|
if( p ) {
|
||||||
|
if (rotable_push_rovalue(L, p)) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// 看看第一个方法是不是__index, 如果是的话, 调用之
|
||||||
|
if (p2->name != NULL && !strcmp("__index", p2->name)) {
|
||||||
|
lua_pushcfunction(L, p2->value.value.func);
|
||||||
|
lua_pushvalue(L, 2);
|
||||||
|
lua_call(L, 1, 1);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
lua_pushnil( L );
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_udata_len( lua_State* L ) {
|
||||||
|
lua_pushinteger( L, 0 );
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_iter( lua_State* L ) {
|
||||||
|
check_rotable( L, 1, "__pairs iterator" );
|
||||||
|
char const* key;
|
||||||
|
const rotable_Reg_t* q = 0;
|
||||||
|
const rotable_Reg_t* p = 0;
|
||||||
|
|
||||||
|
int isnil = lua_isnil(L, 2);
|
||||||
|
lua_getuservalue( L, 1 );
|
||||||
|
p = (const rotable_Reg_t*)lua_touserdata( L, -1 );
|
||||||
|
|
||||||
|
if (isnil) {
|
||||||
|
lua_pushstring(L, p->name);
|
||||||
|
rotable_push_rovalue(L, p);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
key = lua_tostring(L, 2);
|
||||||
|
|
||||||
|
for( q = p; q->name != NULL; ++q ) {
|
||||||
|
if( 0 == reg_compare( key, q ) ) {
|
||||||
|
++q;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (q == NULL || q->name == NULL) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
lua_pushstring( L, q->name );
|
||||||
|
rotable_push_rovalue(L, q);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static int rotable_udata_pairs( lua_State* L ) {
|
||||||
|
lua_pushcfunction( L, rotable_iter );
|
||||||
|
lua_pushvalue( L, 1 );
|
||||||
|
lua_pushnil( L );
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 与lua_newlib对应的函数, 用于生成一个库table,区别是lua_newlib生成普通table,这个函数生成rotable.
|
||||||
|
*/
|
||||||
|
#include "lgc.h"
|
||||||
|
void rotable2_newlib( lua_State* L, void const* v ) {
|
||||||
|
const rotable_Reg_t* reg = (const rotable_Reg_t*)v;
|
||||||
|
rotable* t = (rotable*)lua_newuserdata( L, sizeof( *t ) );
|
||||||
|
luaC_fix(L, L->l_G->allgc);
|
||||||
|
lua_pushlightuserdata( L, (void*)unique_address );
|
||||||
|
lua_rawget( L, LUA_REGISTRYINDEX );
|
||||||
|
if( !lua_istable( L, -1 ) ) {
|
||||||
|
lua_pop( L, 1 );
|
||||||
|
lua_createtable( L, 0, 5 );
|
||||||
|
lua_pushcfunction( L, rotable_udata_index );
|
||||||
|
lua_setfield( L, -2, "__index" );
|
||||||
|
lua_pushcfunction( L, rotable_udata_len );
|
||||||
|
lua_setfield( L, -2, "__len" );
|
||||||
|
lua_pushcfunction( L, rotable_udata_pairs );
|
||||||
|
lua_setfield( L, -2, "__pairs" );
|
||||||
|
lua_pushboolean( L, 0 );
|
||||||
|
lua_setfield( L, -2, "__metatable" );
|
||||||
|
lua_pushliteral( L, "rotable" );
|
||||||
|
lua_setfield( L, -2, "__name" );
|
||||||
|
lua_pushlightuserdata( L, (void*)unique_address );
|
||||||
|
lua_pushvalue( L, -2 );
|
||||||
|
lua_rawset( L, LUA_REGISTRYINDEX );
|
||||||
|
}
|
||||||
|
lua_setmetatable( L, -2 );
|
||||||
|
#if LUA_VERSION_NUM < 503
|
||||||
|
t->p = reg;
|
||||||
|
#else
|
||||||
|
lua_pushlightuserdata( L, (void*)reg );
|
||||||
|
lua_setuservalue( L, -2 );
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为自定义对象也生成rotable形式的元表, 这个形式比rotable_newlib需要更多内存,但起码是一个解决办法.
|
||||||
|
*/
|
||||||
|
void rotable2_newidx( lua_State* L, void const* v ) {
|
||||||
|
lua_pushlightuserdata( L, (void*)v);
|
||||||
|
lua_pushcclosure( L, rotable_func_index, 1 );
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
Air510W模组,可以搭配Air780EHM或者Air780EHV来使用,LuatOS软件二次开发的demo参考:
|
||||||
|
Air780EHM_Air780EHV_Air780EGH/demo/gnss/Air780EHM_Air780EHV+510W
|
||||||
|
|
||||||
|
|
||||||
|
Air530W模组,可以搭配Air780EHM或者Air780EHV来使用,LuatOS软件二次开发的demo参考:
|
||||||
|
Air780EHM_Air780EHV_Air780EGH/demo/gnss/Air780EHM_Air780EHV+530W
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
# LuatOS-Air780EPM
|
||||||
|
|
||||||
|
## 介绍
|
||||||
|
|
||||||
|
本代码库 是 合宙 Air780EPM 模组的代码中心, 包括演示代码demo, 案例代码project等
|
||||||
|
|
||||||
|
如需查阅文档, 请访问合宙文档中心的[Air780EPM模块文档中心](https://docs.openluat.com/air780epm/)
|
||||||
|
|
||||||
|
## 目录说明
|
||||||
|
|
||||||
|
* demo [演示代码](demo/)
|
||||||
|
* project [案例代码](project/)
|
||||||
|
|
||||||
|
## 固件说明
|
||||||
|
|
||||||
|
[Air780EPM固件版本说明](https://docs.openluat.com/air780epm/luatos/firmware/version/)
|
||||||
|
|
||||||
|
## demo使用说明
|
||||||
|
|
||||||
|
[**JT808**]:本demo演示使用string.pack与unpack函数,实现JT808 终端注册协议数据生成与解析,适用于车辆定位和监控系统。
|
||||||
|
|
||||||
|
[**Websocket**]:本demo演示使用websocket协议,实现LuatOS与Web服务器的通信,适用于实时数据传输和双向通信场景。
|
||||||
|
|
||||||
|
[**adc**]:本demo演示LuatOS的ADC功能,用于模拟信号的读取,适用于传感器数据采集等场景。
|
||||||
|
|
||||||
|
[**airlbs**]:本demo演示LuatOS的LBS功能,包括多基站定位和WIFI定位,适用于位置服务开发。
|
||||||
|
|
||||||
|
[**bit**]:本demo演示LuatOS的bit操作功能,适用于需要进行位级操作的场景。
|
||||||
|
|
||||||
|
[**bit64**]:本demo演示LuatOS的64位bit操作功能,适用于需要进行大范围位级操作的场景。
|
||||||
|
|
||||||
|
[**camera/spi_cam**]:本demo演示LuatOS的SPI摄像头功能,适用于需要集成摄像头进行图像采集的设备。
|
||||||
|
|
||||||
|
[**can**]:本demo演示LuatOS的CAN总线通信功能,适用于汽车电子和工业自动化等场景。
|
||||||
|
|
||||||
|
[**crypto**]:本demo演示LuatOS的加密功能,包括哈希、对称加密和非对称加密等,适用于需要进行数据加密和解密的场景。
|
||||||
|
|
||||||
|
[**errdump**]:本demo演示LuatOS的错误信息转储功能,适用于设备调试和错误分析。
|
||||||
|
|
||||||
|
[**fota2**]:本demo演示LuatOS的FOTA(空中下载)功能,包括固件更新等,适用于设备远程升级和维护。
|
||||||
|
|
||||||
|
[**fs**]:本demo演示LuatOS的文件系统功能,包括文件读写等,适用于需要进行文件存储和操作的场景。
|
||||||
|
|
||||||
|
[**gpio**]:本demo演示LuatOS的GPIO功能,包括数字输入输出等,适用于需要进行硬件控制的场景。
|
||||||
|
|
||||||
|
[**helloworld**]:本demo演示LuatOS的基本运行环境,通过输出“Hello, World!”来验证开发环境是否搭建成功。
|
||||||
|
|
||||||
|
[**hmeta**]:本demo演示LuatOS的硬件信息查询功能,适用于获取设备硬件相关信息。
|
||||||
|
|
||||||
|
[**http**]:本demo演示LuatOS的HTTP协议功能,包括网页请求和文件下载等,适用于需要进行网络通信的场景。
|
||||||
|
|
||||||
|
[**i2c-sht20**]:本demo演示LuatOS的I2C通信功能,通过SHT20温湿度传感器来读取温度和湿度信息。
|
||||||
|
|
||||||
|
[**iconv**]:本demo演示LuatOS的字符编码转换功能,适用于需要进行字符编码转换的场景。
|
||||||
|
|
||||||
|
[**iotcloud**]:本demo演示LuatOS与物联网云平台的通信,包括设备连接、数据上传和云服务调用等。
|
||||||
|
|
||||||
|
[**json**]:本demo演示LuatOS的JSON数据解析和生成功能,适用于需要进行JSON格式数据处理的场景。
|
||||||
|
|
||||||
|
[**lbsloc2**]:本demo演示LuatOS的LBS定位功能,适用于需要进行精准位置定位的场景。
|
||||||
|
|
||||||
|
[**lcd**]:本demo演示LuatOS的LCD显示功能,适用于需要进行图形界面显示的设备。
|
||||||
|
|
||||||
|
[**log**]:本demo演示LuatOS的日志记录功能,适用于需要进行日志记录和分析的场景。
|
||||||
|
|
||||||
|
[**lowpower**]:本demo演示LuatOS的低功耗模式功能,适用于需要进行设备功耗优化的场景。
|
||||||
|
|
||||||
|
[**lowpower_new**]:本demo演示LuatOS的低功耗模式功能,结合项目示例进行说明,适用于需要进行设备功耗优化的场景。
|
||||||
|
|
||||||
|
[**miniz**]:本demo演示LuatOS的压缩和解压缩功能,适用于需要进行数据压缩和解压缩的场景。
|
||||||
|
|
||||||
|
[**mobile**]:本demo演示LuatOS的移动网络功能,包括蜂窝网络连接、数据传输等,适用于需要进行移动网络通信的场景。
|
||||||
|
|
||||||
|
[**mqtt**]:本demo演示LuatOS的MQTT协议功能,适用于物联网场景下的消息发布和订阅。
|
||||||
|
|
||||||
|
[**netdrv/ch390**]:本demo演示LuatOS与CH390芯片的网络驱动功能,适用于USB转网口的设备。
|
||||||
|
|
||||||
|
[**ntp**]:本demo演示LuatOS的NTP网络时间同步功能,适用于需要进行时间同步的场景。
|
||||||
|
|
||||||
|
[**onewire**]:本demo演示LuatOS的1-Wire协议功能,适用于连接单总线设备如DS18B20温度传感器等。
|
||||||
|
|
||||||
|
[**openai/deepseek**]:本demo演示LuatOS如何集成OpenAI的DeepSeek服务,适用于需要进行深度学习推理的场景。
|
||||||
|
|
||||||
|
[**pack**]:本demo演示LuatOS的数据打包和解包功能,适用于需要进行数据格式转换的场景。
|
||||||
|
|
||||||
|
[**protobuf**]:本demo演示LuatOS的protobuf数据解析和生成功能,适用于需要进行protobuf格式数据处理的场景。
|
||||||
|
|
||||||
|
[**pwm**]:本demo演示LuatOS的PWM功能,适用于需要进行脉冲宽度调制的场景。
|
||||||
|
|
||||||
|
[**sms**]:本demo演示LuatOS的短信收发功能,适用于嵌入式设备需要进行短信通信的场景。
|
||||||
|
|
||||||
|
[**spi**]:本demo演示LuatOS的SPI通信功能,适用于需要进行SPI通信的场景。
|
||||||
|
|
||||||
|
[**string**]:本demo演示LuatOS的字符串操作功能,包括字符串拼接、分割、查找等,适用于需要进行字符串处理的场景。
|
||||||
|
|
||||||
|
[**tcp**]:本demo演示LuatOS的TCP协议功能,适用于需要进行TCP通信的场景。
|
||||||
|
|
||||||
|
[**timer**]:本demo演示LuatOS的定时器功能,包括单次定时器和周期定时器,适用于需要定时执行任务的场景。
|
||||||
|
|
||||||
|
[**uart**]:本demo演示LuatOS的UART串口通信功能,适用于需要进行串口通信的场景。
|
||||||
|
|
||||||
|
[**udp**]:本demo演示LuatOS的UDP协议功能,适用于需要进行UDP通信的场景。
|
||||||
|
|
||||||
|
[**wdt**]:本demo演示LuatOS的看门狗定时器功能,适用于需要进行设备监控和自动复位的场景。
|
||||||
|
|
||||||
|
[**wlan/wifiscan**]:本demo演示LuatOS的Wi-Fi扫描功能,适用于需要搜索和连接Wi-Fi网络的场景。
|
||||||
|
|
||||||
|
## 授权协议
|
||||||
|
|
||||||
|
[MIT License](LICENSE)
|
||||||
|
|
||||||
|
```lua
|
||||||
|
print("感谢您使用LuatOS ^_^")
|
||||||
|
print("Thank you for using LuatOS ^_^")
|
||||||
|
```
|
||||||
|
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
|
||||||
|
[Air780EPM固件下载地址](https://docs.openluat.com/air780epm/luatos/firmware/version/)
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
--[[
|
||||||
|
@module main
|
||||||
|
@summary LuatOS用户应用脚本文件入口,总体调度应用逻辑
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.11.09
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1040 SPI摄像头完成一次拍照上传任务
|
||||||
|
]] --
|
||||||
|
--[[
|
||||||
|
必须定义PROJECT和VERSION变量,Luatools工具会用到这两个变量,远程升级功能也会用到这两个变量
|
||||||
|
PROJECT:项目名,ascii string类型
|
||||||
|
可以随便定义,只要不使用,就行
|
||||||
|
VERSION:项目版本号,ascii string类型
|
||||||
|
如果使用合宙iot.openluat.com进行远程升级,必须按照"XXX.YYY.ZZZ"三段格式定义:
|
||||||
|
X、Y、Z各表示1位数字,三个X表示的数字可以相同,也可以不同,同理三个Y和三个Z表示的数字也是可以相同,可以不同
|
||||||
|
因为历史原因,YYY这三位数字必须存在,但是没有任何用处,可以一直写为999
|
||||||
|
如果不使用合宙iot.openluat.com进行远程升级,根据自己项目的需求,自定义格式即可
|
||||||
|
]]--
|
||||||
|
PROJECT = "AirCAMERA_1040_Demo"
|
||||||
|
VERSION = "001.999.000"
|
||||||
|
|
||||||
|
-- 在日志中打印项目名和项目版本号
|
||||||
|
log.info("main", PROJECT, VERSION)
|
||||||
|
|
||||||
|
-- 如果内核固件支持errDump功能,此处进行配置,【强烈建议打开此处的注释】
|
||||||
|
-- 因为此功能模块可以记录并且上传脚本在运行过程中出现的语法错误或者其他自定义的错误信息,可以初步分析一些设备运行异常的问题
|
||||||
|
-- 以下代码是最基本的用法,更复杂的用法可以详细阅读API说明文档
|
||||||
|
-- 启动errDump日志存储并且上传功能,600秒上传一次
|
||||||
|
-- if errDump then
|
||||||
|
-- errDump.config(true, 600)
|
||||||
|
-- end
|
||||||
|
|
||||||
|
-- 使用LuatOS开发的任何一个项目,都强烈建议使用远程升级FOTA功能
|
||||||
|
-- 可以使用合宙的iot.openluat.com平台进行远程升级
|
||||||
|
-- 也可以使用客户自己搭建的平台进行远程升级
|
||||||
|
-- 远程升级的详细用法,可以参考fota的demo进行使用
|
||||||
|
|
||||||
|
-- 启动一个循环定时器
|
||||||
|
-- 每隔3秒钟打印一次总内存,实时的已使用内存,历史最高的已使用内存情况
|
||||||
|
-- 方便分析内存使用是否有异常
|
||||||
|
-- sys.timerLoopStart(function()
|
||||||
|
-- log.info("mem.lua", rtos.meminfo())
|
||||||
|
-- log.info("mem.sys", rtos.meminfo("sys"))
|
||||||
|
-- end, 3000)
|
||||||
|
|
||||||
|
-- 导入netdrv_4g联网状态模块
|
||||||
|
require "netdrv_4g"
|
||||||
|
|
||||||
|
-- 导入gc032a配置表
|
||||||
|
require "gc032a"
|
||||||
|
|
||||||
|
-- 拍照和扫描模式需要在初始化时确认,导入对应模式的DEMO后注释另一个DEMO,拍照和扫描不可同时使用
|
||||||
|
--[[ 导入photo_to_aircloud拍照上传应用DEMO,该DEMO上传照片至aircloud平台,需要先配置photo_to_aircloud.lua中32行的 project_auth_key ,否则会报nil
|
||||||
|
project_auth_key:aircloud应用的认证密钥,用于验证上传请求的合法性
|
||||||
|
获取方式为:登录iot.openluat.com,点击”我的项目“,找到您所使用的模块对应的项目,即可复制项目KEY
|
||||||
|
当您的模块没有在您的账号下时,请参考https://docs.openluat.com/air780epm/product/attributioniot/ 处理办法,获取项目KEY]] --
|
||||||
|
require "photo_to_aircloud"
|
||||||
|
|
||||||
|
-- 导入take_photo_http_post拍照上传应用DEMO,air32.cn为虚拟服务器,仅用于演示,实际使用时请替换为自己的服务器。
|
||||||
|
-- 与photo_to_aircloud.lua二选一执行即可,不可同时导入
|
||||||
|
-- require "take_photo_http_post"
|
||||||
|
|
||||||
|
-- 导入scan_code扫描二维码应用DEMO
|
||||||
|
-- require "scan_code"
|
||||||
|
|
||||||
|
-- 用户代码已结束---------------------------------------------
|
||||||
|
-- 结尾总是这一句
|
||||||
|
sys.run()
|
||||||
|
-- sys.run()之后后面不要加任何语句!!!!!
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
--[[
|
||||||
|
@module netdrv_4g
|
||||||
|
@summary “4G网卡”驱动模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.07.01
|
||||||
|
@author 朱天华
|
||||||
|
@usage
|
||||||
|
本文件为4G网卡驱动模块,核心业务逻辑为:
|
||||||
|
1、监听"IP_READY"和"IP_LOSE",在日志中进行打印;
|
||||||
|
|
||||||
|
本文件没有对外接口,直接在其他功能模块中require "netdrv_4g"就可以加载运行;
|
||||||
|
]]
|
||||||
|
|
||||||
|
local function ip_ready_func(ip, adapter)
|
||||||
|
if adapter == socket.LWIP_GP then
|
||||||
|
log.info("netdrv_4g.ip_ready_func", "IP_READY", socket.localIP(socket.LWIP_GP))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
local function ip_lose_func(adapter)
|
||||||
|
if adapter == socket.LWIP_GP then
|
||||||
|
log.warn("netdrv_4g.ip_lose_func", "IP_LOSE")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
|
-- 此处订阅"IP_READY"和"IP_LOSE"两种消息
|
||||||
|
-- 在消息的处理函数中,仅仅打印了一些信息,便于实时观察4G网络的连接状态
|
||||||
|
-- 也可以根据自己的项目需求,在消息处理函数中增加自己的业务逻辑控制,例如可以在连网状态发生改变时更新网络图标
|
||||||
|
sys.subscribe("IP_READY", ip_ready_func)
|
||||||
|
sys.subscribe("IP_LOSE", ip_lose_func)
|
||||||
|
|
||||||
|
|
||||||
|
-- 设置默认网卡为socket.LWIP_GP
|
||||||
|
-- 在Air8000上,内核固件运行起来之后,默认网卡就是socket.LWIP_GP
|
||||||
|
-- 在单4G网卡使用场景下,下面这一行代码加不加都没有影响,为了和其他网卡驱动模块的代码风格保持一致,所以加上了
|
||||||
|
socket.dft(socket.LWIP_GP)
|
||||||
+293
@@ -0,0 +1,293 @@
|
|||||||
|
--[[
|
||||||
|
@module photo_to_aircloud
|
||||||
|
@summary AirCAMERA_1040 gc032a摄像头拍照上传应用模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2026.4.30
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1040 gc032a摄像头完成拍照上传任务
|
||||||
|
Air780EPM的sys ram内存资源只有2.3M,在使用camera功能时,需要非常谨慎,避免内存泄漏导致系统崩溃,需要注意以下情况:
|
||||||
|
1、exmcamera业务执行时,必须要确保有连续的内存空间,否则会导致excamera.open()初始化失败,需要的空间计算方式为:
|
||||||
|
( 摄像头像素高 X 摄像头像素宽 X 2 ),用“GC032A”举例,内存空间为:640 * 480 * 2 = 614400 (B) ≈ 620KB
|
||||||
|
2、当使用ZBUFF方式存储照片,或者将照片放到 /ram/ 路径下保存时,必须确保有更多的内存连续空间,需要的总空间大小计算方式为:
|
||||||
|
( 摄像头像素高 X 摄像头像素宽 X 3.5 ),用“GC032A”举例,内存空间为:640 * 480 * 3.5 = 1075200 (B) ≈ 1MB
|
||||||
|
3、本DEMO为常规模式下,摄像头稳定供电使用,DEMO逻辑为excamera.open()初始化完摄像头后,只需要重复调用excamera.photo()拍照即可,不需要反复的初始化关闭摄像头;
|
||||||
|
4、在实际应用中,务必将摄像头初始化的优先级排前,因为摄像头业务占用内存过大,尽早的初始化可以确保摄像头初始化时拿到足够的连续内存,确保后续拍照时能够正常执行;
|
||||||
|
5、Air780EPM的内存非常有限,在摄像头需求高的产品设计中,请选择Air780EHM/EGH/EHV、Air8000、Air700ECH这类 8MB + 8MB 的SOC,更大的内存才是摄像头业务稳定运行的最优解;
|
||||||
|
6、低功耗模式下使用excamera请参考lowpower DEMO,链接:https://docs.openluat.com/air780epm/luatos/app/lowpower/sleep/#_1
|
||||||
|
]] --
|
||||||
|
-- 摄像头拍照模块
|
||||||
|
-- 功能:提供摄像头初始化、拍照和资源管理功能
|
||||||
|
-- 引入excamera扩展库模块
|
||||||
|
local excamera = require "excamera"
|
||||||
|
-- 引入httpplus扩展库模块
|
||||||
|
local httpplus = require "httpplus"
|
||||||
|
-- 引入exmux扩展库模块
|
||||||
|
local exmux = require "exmux"
|
||||||
|
-- 导入excloud库
|
||||||
|
local excloud = require "excloud"
|
||||||
|
-- pm.ioVol(pm.IOVOL_ALL_GPIO, 2800)
|
||||||
|
|
||||||
|
-- 配置excloud参数
|
||||||
|
local project_auth_key = "123456"
|
||||||
|
|
||||||
|
-- 硬件I2C/SPI配置,当您使用合宙开发板时,请根据具体的开发板版本选择对应的变量,
|
||||||
|
-- exmux库将会自动处理开发板上的I2C/SPI外设,确保总线通讯正常
|
||||||
|
-- 当您使用自己的制作的板子,请参考exmux库的文档,配置对应的变量:https://docs.openluat.com/osapi/ext/exmux/
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_8000_V2.0"
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_780_V1.2"
|
||||||
|
local HARDWARE_ENV = "DEV_BOARD_780_V1.3"
|
||||||
|
|
||||||
|
-- 定义照片保存方式,有三种类型:
|
||||||
|
-- 1、ZBUFF保存,输入"ZBUFF"即可,excamera库会自动处理ZBUFF
|
||||||
|
-- 2、保存到内存文件系统中,路径名需指向/ram/文件夹
|
||||||
|
-- 3、保存到内置FLASH文件系统中
|
||||||
|
-- 选择其中一个即可,注释另两个路径变量
|
||||||
|
local save_method = "ZBUFF"
|
||||||
|
-- local save_method = "/ram/test.jpg"
|
||||||
|
-- local save_method = "/test.jpg"
|
||||||
|
|
||||||
|
--[[
|
||||||
|
excloud事件回调函数
|
||||||
|
参数:
|
||||||
|
event: 事件类型字符串
|
||||||
|
data: 事件数据,根据事件类型不同而不同
|
||||||
|
|
||||||
|
事件类型说明:
|
||||||
|
connect_result: 连接结果
|
||||||
|
auth_result: 认证结果
|
||||||
|
disconnect: 断开连接
|
||||||
|
reconnect_failed: 重连失败
|
||||||
|
]]
|
||||||
|
function on_excloud_event(event, data)
|
||||||
|
-- 打印事件信息
|
||||||
|
log.info("用户回调函数", event, json.encode(data))
|
||||||
|
-- 处理连接结果事件
|
||||||
|
if event == "connect_result" then
|
||||||
|
if data.success then
|
||||||
|
log.info("连接成功")
|
||||||
|
-- 发布连接成功消息,通知其他任务
|
||||||
|
sys.publish("aircloud_connected")
|
||||||
|
else
|
||||||
|
log.info("连接失败: " .. (data.error or "未知错误"))
|
||||||
|
end
|
||||||
|
-- 处理认证结果事件
|
||||||
|
elseif event == "auth_result" then
|
||||||
|
if data.success then
|
||||||
|
log.info("认证成功")
|
||||||
|
else
|
||||||
|
log.info("认证失败: " .. data.message)
|
||||||
|
end
|
||||||
|
-- 处理断开连接事件
|
||||||
|
elseif event == "disconnect" then
|
||||||
|
log.warn("与服务器断开连接")
|
||||||
|
-- 处理重连失败事件
|
||||||
|
elseif event == "reconnect_failed" then
|
||||||
|
log.info("重连失败,已尝试 " .. data.count .. " 次")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 注册excloud事件回调函数
|
||||||
|
excloud.on(on_excloud_event)
|
||||||
|
|
||||||
|
--[[
|
||||||
|
excloud任务函数
|
||||||
|
功能:
|
||||||
|
1. 等待网络连接就绪
|
||||||
|
2. 配置excloud参数
|
||||||
|
3. 初始化并开启excloud服务
|
||||||
|
4. 启动自动心跳
|
||||||
|
]]
|
||||||
|
local function excloud_task_func()
|
||||||
|
-- 如果当前时间点设置的默认网卡还没有连接成功,一直在这里循环等待
|
||||||
|
while not socket.adapter(socket.dft()) do
|
||||||
|
log.warn("excloud_task_func", "wait IP_READY", socket.dft())
|
||||||
|
-- 在此处阻塞等待默认网卡连接成功的消息"IP_READY"
|
||||||
|
-- 或者等待1秒超时退出阻塞等待状态;
|
||||||
|
-- 注意:此处的1000毫秒超时不要修改的更长;
|
||||||
|
-- 因为当使用exnetif.set_priority_order配置多个网卡连接外网的优先级时,会隐式的修改默认使用的网卡
|
||||||
|
-- 当exnetif.set_priority_order的调用时序和此处的socket.adapter(socket.dft())判断时序有可能不匹配
|
||||||
|
-- 此处的1秒,能够保证,即使时序不匹配,也能1秒钟退出阻塞状态,再去判断socket.adapter(socket.dft())
|
||||||
|
sys.waitUntil("IP_READY", 1000)
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 检查是否使用默认的示例key
|
||||||
|
if project_auth_key == "123" or project_auth_key == "123456" then
|
||||||
|
log.warn("photo_to_aircloud",
|
||||||
|
"请改为自己的key,如不知道对应key的可以查看main.lua 54-57行的指导进行添加key的操作")
|
||||||
|
end
|
||||||
|
|
||||||
|
local ok, err_msg = excloud.setup({
|
||||||
|
use_getip = true, -- 使用getip服务
|
||||||
|
device_type = 1, -- 4G设备
|
||||||
|
auth_key = project_auth_key, -- 认证密钥
|
||||||
|
transport = "tcp", -- 使用TCP传输
|
||||||
|
auto_reconnect = true, -- 自动重连
|
||||||
|
reconnect_interval = 10, -- 重连间隔(秒)
|
||||||
|
max_reconnect = 5, -- 最大重连次数
|
||||||
|
mtn_log_enabled = true, -- 启用运维日志
|
||||||
|
mtn_log_blocks = 2, -- 日志文件块数
|
||||||
|
mtn_log_write_way = excloud.MTN_LOG_CACHE_WRITE -- 缓存写入方式
|
||||||
|
})
|
||||||
|
|
||||||
|
-- 检查初始化是否成功
|
||||||
|
if not ok then
|
||||||
|
log.info("初始化失败: " .. err_msg)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
log.info("excloud初始化成功")
|
||||||
|
|
||||||
|
-- 开启excloud服务
|
||||||
|
local ok, err_msg = excloud.open()
|
||||||
|
if not ok then
|
||||||
|
log.info("开启excloud服务失败: " .. err_msg)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
log.info("excloud服务已开启")
|
||||||
|
|
||||||
|
-- 启动自动心跳,默认5分钟一次的心跳
|
||||||
|
excloud.start_heartbeat()
|
||||||
|
log.info("自动心跳已启动")
|
||||||
|
end
|
||||||
|
|
||||||
|
--[[
|
||||||
|
照片上传任务函数
|
||||||
|
功能:
|
||||||
|
1. 等待excloud连接建立
|
||||||
|
2. 等待图片数据
|
||||||
|
3. 上传图片到云端
|
||||||
|
4. 处理上传结果
|
||||||
|
]]
|
||||||
|
function upload_image_fun(image)
|
||||||
|
if excloud.status().is_connected then
|
||||||
|
log.info("开始上传图片")
|
||||||
|
if image then
|
||||||
|
local ok, err = excloud.upload_image(image, "test.jpg")
|
||||||
|
if ok then
|
||||||
|
log.info("图片上传成功")
|
||||||
|
return true
|
||||||
|
else
|
||||||
|
log.error("图片上传失败:", err)
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
else
|
||||||
|
log.warn("图片数据为空")
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
log.info("excloud连接已断开,等待重连")
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 拍照功能函数
|
||||||
|
-- 作用:循环监听拍照事件,执行摄像头初始化、拍照和资源释放
|
||||||
|
local function capture_func()
|
||||||
|
-- 定义变量用于存储操作结果和数据
|
||||||
|
local result, data, err
|
||||||
|
-- 增加重试次数,最多重试5次,避免日志量过大
|
||||||
|
local retry_count = 0
|
||||||
|
-- 初始化开发板
|
||||||
|
exmux.setup(HARDWARE_ENV)
|
||||||
|
-- 出现异常后重新初始化,最多重试5次
|
||||||
|
while retry_count < 5 do
|
||||||
|
-- 配置gc032a摄像头参数表
|
||||||
|
local spi_camera_param = {
|
||||||
|
id = "gc032a", -- SPI摄像头仅支持"gc032a"、"gc0310"、"bf30a2",请带引号填写
|
||||||
|
i2c_id = 1, -- 模块上使用的I2C编号
|
||||||
|
work_mode = 0, -- 工作模式,0为拍照模式,1为扫描模式
|
||||||
|
save_path = save_method, -- 拍照结果存储路径,可用"ZBUFF"交由excamera库内部管理
|
||||||
|
camera_pwr = 2, -- 摄像头使能管脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_pwdn = 5, -- 摄像头pwdn开关脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_light = nil -- 摄像头补光灯控制管脚,填写GPIO号即可,无则填nil
|
||||||
|
}
|
||||||
|
-- 打开外设分组
|
||||||
|
exmux.open("i2c1")
|
||||||
|
-- 初始化摄像头,传入配置参数
|
||||||
|
result = excamera.open(spi_camera_param)
|
||||||
|
-- 记录摄像头初始化状态
|
||||||
|
log.info("初始化状态", result)
|
||||||
|
-- 判断摄像头初始化是否成功,不成功则直接关闭,成功则启动拍照
|
||||||
|
-- 无限循环,持续等待拍照事件
|
||||||
|
while result do
|
||||||
|
-- 等待外部触发拍照事件(ONCE_CAPTURE)
|
||||||
|
sys.waitUntil("ONCE_CAPTURE")
|
||||||
|
-- 执行拍照操作
|
||||||
|
result, data = excamera.photo()
|
||||||
|
-- 拍照执行完成则上传,否则关闭摄像头
|
||||||
|
if result then
|
||||||
|
-- 通过网卡状态判断WIFI是否连接成功,WIFI连接成功后再运行照片上传任务。
|
||||||
|
while not socket.adapter(socket.dft()) do
|
||||||
|
-- 在此处阻塞等待WIFI连接成功的消息"IP_READY",避免联网过快,丢失了"IP_READY"信息而导致一直被卡住。
|
||||||
|
-- 或者等待30秒超时退出阻塞等待状态
|
||||||
|
log.warn("tcp_client_main_task_func", "wait IP_READY")
|
||||||
|
sys.waitUntil("IP_READY", 30000)
|
||||||
|
end
|
||||||
|
upload_image_fun(data)
|
||||||
|
end
|
||||||
|
-- 判断是否ZBUFF存储方式,如果是文件系统保存则删除本地文件
|
||||||
|
if save_method ~= "ZBUFF" then
|
||||||
|
os.remove(spi_camera_param.save_path)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- 关闭摄像头,释放资源
|
||||||
|
-- 使用ZBUFF存储方式时,close传入true后,excamera内部创建的ZBUFF会缩减至0字节,放出内存但是不释放ZBUFF,便于下次拍照时调用;
|
||||||
|
-- 重复申请和释放ZBUFF会导致垃圾内存堆积,影响系统内存;
|
||||||
|
excamera.close(true)
|
||||||
|
-- 关闭外设分组
|
||||||
|
exmux.close("i2c1")
|
||||||
|
-- 拍照出错,等待5秒,重试摄像头初始化
|
||||||
|
sys.wait(5000)
|
||||||
|
-- 重试次数增加
|
||||||
|
retry_count = retry_count + 1
|
||||||
|
log.info("retry_count", retry_count)
|
||||||
|
end
|
||||||
|
-- 重试5次后,提示用户检查摄像头连接或重启设备
|
||||||
|
log.info("camera init failed, please check the camera connection or reboot, retry_count:", retry_count)
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 内存检查函数
|
||||||
|
-- 作用:定期监控系统内存使用情况
|
||||||
|
local function memory_check()
|
||||||
|
-- 无限循环,定期检查内存
|
||||||
|
while true do
|
||||||
|
-- 等待3秒
|
||||||
|
sys.wait(3000)
|
||||||
|
-- 打印系统内存使用信息
|
||||||
|
log.info("sys ram", rtos.meminfo("sys"))
|
||||||
|
-- 打印Lua虚拟机内存使用信息
|
||||||
|
log.info("lua ram", rtos.meminfo("lua"))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- AirCAMERA_1040 DEMO应用触发函数,每30S触发一次拍照
|
||||||
|
local function AirCAMERA_1040_func()
|
||||||
|
while true do
|
||||||
|
sys.wait(30000)
|
||||||
|
sys.publish("ONCE_CAPTURE")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 按键触发函数,用于手动拍照拍照
|
||||||
|
local function press_key()
|
||||||
|
log.info("boot press")
|
||||||
|
sys.publish("ONCE_CAPTURE")
|
||||||
|
end
|
||||||
|
-- 配置BOOT按键引脚为输入模式,下拉电阻,上升沿触发
|
||||||
|
gpio.setup(0, press_key, gpio.PULLDOWN, gpio.RISING)
|
||||||
|
gpio.debounce(0, 100, 1)
|
||||||
|
|
||||||
|
-- 启动excloud连接任务
|
||||||
|
sys.taskInit(excloud_task_func)
|
||||||
|
|
||||||
|
-- 创建拍照功能任务
|
||||||
|
-- 作用:在单独的任务中运行拍照逻辑
|
||||||
|
sys.taskInit(capture_func)
|
||||||
|
|
||||||
|
-- 创建内存监控任务
|
||||||
|
-- 作用:在单独的任务中运行内存监控逻辑
|
||||||
|
sys.taskInit(memory_check)
|
||||||
|
|
||||||
|
-- 创建拍照触发任务
|
||||||
|
-- 作用:每30秒触发一次拍照上传业务
|
||||||
|
sys.taskInit(AirCAMERA_1040_func)
|
||||||
|
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
# AirCAMERA_1040 DEMO
|
||||||
|
|
||||||
|
## 演示功能概述
|
||||||
|
|
||||||
|
本示例主要是展示 AirCAMERA_1040 的使用,本地拍摄照片后通过 httpplus 扩展库将图片上传至 air32.com
|
||||||
|
|
||||||
|
1、main.lua:主程序入口
|
||||||
|
|
||||||
|
2、take_photo_http_post.lua:执行拍照后使用推送照片上传至air32.cn服务器,该服务器为虚拟服务器,仅用于演示,实际使用时请替换为自己的服务器。
|
||||||
|
|
||||||
|
3、scan_code.lua:扫描二维码应用DEMO模块
|
||||||
|
|
||||||
|
4、netdrv_4g.lua:联网状态检测模块
|
||||||
|
|
||||||
|
5、photo_to_aircloud.lua:执行拍照后使用推送照片上传至aircloud平台
|
||||||
|
|
||||||
|
注意事项:
|
||||||
|
|
||||||
|
- 拍照或者扫描模式需要在摄像头初始化时确定
|
||||||
|
- 如使用拍照模式就无法使用扫描模式,扫描模式同理
|
||||||
|
- 需要拍照后执行扫描的话需要重新初始化
|
||||||
|
- 所以拍照和扫描不可同时使用,如需切换模式需重新初始化
|
||||||
|
- 因为Air32.com平台已经不开放使用了,所以该DEMO仅作上传照片至服务器的演示作用,使用时请将上传URL修改为您自己的服务器地址,或者通过excloud扩展库上传到合宙IOT平台uploadtest.luatos.com
|
||||||
|
|
||||||
|
## 演示功能概述
|
||||||
|
|
||||||
|
### 1、主程序入口模块(main.lua)
|
||||||
|
|
||||||
|
- 初始化项目信息和版本号
|
||||||
|
- 初始化看门狗,并定时喂狗
|
||||||
|
- 启动一个循环定时器,每隔 3 秒钟打印一次总内存,实时的已使用内存,历史最高的已使用内存情况方便分析内存使用是否有异常
|
||||||
|
- 加载 netdrv_4g 4G联网状态检测模块
|
||||||
|
- 加载 photo_to_aircloud 拍照上传至aircloud平台模块,务必先配置auth_key,否则会报错
|
||||||
|
- 加载 take_photo_http_post 模块
|
||||||
|
|
||||||
|
### 2、4G联网状态检测模块(netdrv_4g.lua)
|
||||||
|
|
||||||
|
- 订阅"IP_READY"消息,收到消息后打印联网成功日志
|
||||||
|
- 订阅"IP_LOSE"消息,收到消息后打印联网失败日志
|
||||||
|
|
||||||
|
### 3、拍照上传服务器演示模块(take_photo_http_post.lua)
|
||||||
|
|
||||||
|
- 每 30 秒触发一次拍照:AirCAMERA_1040_func()
|
||||||
|
- 每 3 秒打印一次系统和 LUA 的内存信息:memory_check()
|
||||||
|
- 配置摄像头信息表:spi_camera_param
|
||||||
|
- 初始化摄像头:excamera.open()
|
||||||
|
- 执行拍照:excamera.photo()
|
||||||
|
- 上传照片:httpplus.request()
|
||||||
|
- 关闭摄像头:excamera.close()
|
||||||
|
|
||||||
|
### 4、扫描二维码应用DEMO(scan_code.lua)
|
||||||
|
|
||||||
|
- 每 30 秒触发一次拍照:AirCAMERA_1040_func()
|
||||||
|
- 每 3 秒打印一次系统和 LUA 的内存信息:memory_check()
|
||||||
|
- 配置摄像头信息表:spi_camera_param
|
||||||
|
- 初始化摄像头:excamera.open()
|
||||||
|
- 执行扫描:excamera.scan()
|
||||||
|
- 关闭摄像头:excamera.close()
|
||||||
|
|
||||||
|
### 5、拍照上传至aircloud平台业务模块(photo_to_aircloud.lua)
|
||||||
|
|
||||||
|
- 配置excloud链接,启动心跳包
|
||||||
|
- 开启自动重连机制,断网后自动重连
|
||||||
|
- 订阅excloud_post_image_done消息,收到消息后打印上传结果:log.info("excloud_post_image_func", err)
|
||||||
|
- 每 30 秒触发一次拍照:AirCAMERA_1040_func()
|
||||||
|
- 每 3 秒打印一次系统和 LUA 的内存信息:memory_check()
|
||||||
|
- 注册excloud回调:on_excloud_event()
|
||||||
|
- 配置excloud链接,启动心跳包:excloud_task_func()
|
||||||
|
- 照片上传任务函数:upload_image_fun()
|
||||||
|
- 配置摄像头信息表:spi_camera_param
|
||||||
|
- 初始化摄像头:excamera.open()
|
||||||
|
- 执行拍照:excamera.photo()
|
||||||
|
- 上传照片:httpplus.request()
|
||||||
|
- 关闭摄像头:excamera.close()
|
||||||
|
|
||||||
|
|
||||||
|
## 演示硬件环境
|
||||||
|
|
||||||
|
1、Air780EPM 开发板一块
|
||||||
|
|
||||||
|
2、TYPE-C USB 数据线一根
|
||||||
|
|
||||||
|
3、合宙标准配件 AirCAMERA_1040 一个
|
||||||
|
|
||||||
|
4、Air780EPM 开发板和合宙标准配件 AirCAMERA_1040 的硬件接线方式为
|
||||||
|
|
||||||
|
Air780EPM 开发板通过 TYPE-C USB 口供电;(侧面拨码拨至USB供电)
|
||||||
|
|
||||||
|
TYPE-C USB 数据线直接插到开发板的 TYPE-C USB 座子,另外一端连接电脑 USB 口;
|
||||||
|
|
||||||
|
AirCAMERA_1040 配件板插入Air780EPM 开发板的SPI摄像头座子中
|
||||||
|
|
||||||
|
## 演示软件环境
|
||||||
|
|
||||||
|
1、Luatools 下载调试工具:[https://docs.openluat.com/air780epm/common/Luatools/](https://docs.openluat.com/air780epm/common/Luatools/)
|
||||||
|
|
||||||
|
2、固件版本:LuatOS-SoC_V2018_Air780EPM_1,固件地址,如有最新固件请用最新 https://docs.openluat.com/air780epm/luatos/firmware/version/
|
||||||
|
|
||||||
|
|
||||||
|
## 演示核心步骤
|
||||||
|
|
||||||
|
1、搭建硬件环境;
|
||||||
|
|
||||||
|
2、烧录 DEMO 代码;
|
||||||
|
|
||||||
|
3、等待自动拍照完成后上传平台,LUATOOLS会有如下打印;
|
||||||
|
```lua
|
||||||
|
[2026-04-08 17:36:12.996][000000000.205] I/user.main AirCAMERA_1040_Demo 001.999.000
|
||||||
|
[2026-04-08 17:36:12.999][000000000.325] W/user.excloud_task_func wait IP_READY 1 1
|
||||||
|
[2026-04-08 17:36:13.002][000000000.326] I/user.exmux 开发板 DEV_BOARD_780_V1.2 初始化成功
|
||||||
|
[2026-04-08 17:36:13.504][000000001.326] W/user.excloud_task_func wait IP_READY 1 1
|
||||||
|
[2026-04-08 17:36:14.408][000000002.166] I/mobile sim0 sms ready
|
||||||
|
[2026-04-08 17:36:14.412][000000002.167] D/mobile cid1, state0
|
||||||
|
[2026-04-08 17:36:14.423][000000002.168] D/mobile bearer act 0, result 0
|
||||||
|
[2026-04-08 17:36:14.430][000000002.168] D/mobile NETIF_LINK_ON -> IP_READY
|
||||||
|
[2026-04-08 17:36:14.438][000000002.169] I/user.netdrv_4g.ip_ready_func IP_READY 10.122.36.125 255.255.255.255 0.0.0.0 nil
|
||||||
|
[2026-04-08 17:36:14.445][000000002.173] I/user.[excloud]4G设备 IMEI: 867920071472378 MUID: 20250604131416A755490A2989432885
|
||||||
|
[2026-04-08 17:36:14.451][000000002.189] I/user.exmtn 读取索引 1
|
||||||
|
[2026-04-08 17:36:14.457][000000002.189] I/user.exmtn 读取块数配置 2
|
||||||
|
[2026-04-08 17:36:14.464][000000002.190] I/user.exmtn 读取写入方式配置 0
|
||||||
|
[2026-04-08 17:36:14.468][000000002.190] I/user.exmtn 配置变化 false
|
||||||
|
[2026-04-08 17:36:14.473][000000002.193] I/user.exmtn 配置未变化,文件存在,继续写入
|
||||||
|
[2026-04-08 17:36:14.479][000000002.197] I/user.exmtn 初始化成功: 每个文件 8.00 KB (2 块 × 4096 字节), 总空间 32.00 KB (4 个文件)
|
||||||
|
[2026-04-08 17:36:14.484][000000002.197] I/user.[excloud]运维日志初始化成功
|
||||||
|
[2026-04-08 17:36:14.488][000000002.198] I/user.[excloud]excloud.setup 初始化成功 设备ID: 867920071472378
|
||||||
|
[2026-04-08 17:36:14.494][000000002.198] I/user.excloud初始化成功
|
||||||
|
[2026-04-08 17:36:14.499][000000002.198] I/user.[excloud]首次连接,获取服务器信息...
|
||||||
|
[2026-04-08 17:36:14.505][000000002.199] I/user.[excloud]excloud.getip 类型: 3 key: sh5g0OTP7ThOSlGKmE5jiEMbOBqQWyw9-867920071472378
|
||||||
|
[2026-04-08 17:36:14.512][000000002.205] D/socket connect to gps.openluat.com,443
|
||||||
|
[2026-04-08 17:36:14.516][000000002.209] dns_run 676:gps.openluat.com state 0 id 1 ipv6 0 use dns server2, try 0
|
||||||
|
[2026-04-08 17:36:14.520][000000002.231] D/mobile TIME_SYNC 0 tm 1775640975
|
||||||
|
[2026-04-08 17:36:14.526][000000002.273] dns_run 693:dns all done ,now stop
|
||||||
|
[2026-04-08 17:36:15.179][000000003.008] I/user.httpplus 服务器已完成响应,开始解析响应
|
||||||
|
[2026-04-08 17:36:15.211][000000003.037] I/user.[excloud]excloud.getip响应 HTTP Code: 200 Body:
|
||||||
|
[2026-04-08 17:36:15.218][000000003.037] {"msg":"ok","conninfo":{"ipv4":"124.71.128.165","port":9108},"imginfo":{"url":"https://gps.openluat.com/aircloud/air_up/image","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"audinfo":{"url":"https://gps.openluat.com/aircloud/air_up/audio","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"mtninfo":{"url":"https://gps.openluat.com/aircloud/air_up/file","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"qrinfo":{"url":"https://gps.openluat.com/#/redirect?key=_5oruyMsMk5Ny5ZajRyBqaZEqqaPjVSb93qH"}}
|
||||||
|
[2026-04-08 17:36:15.225][000000003.038] I/user.[excloud]excloud.getip响应 HTTP Code: 200 Body:
|
||||||
|
[2026-04-08 17:36:15.231][000000003.038] {"msg":"ok","conninfo":{"ipv4":"124.71.128.165","port":9108},"imginfo":{"url":"https://gps.openluat.com/aircloud/air_up/image","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"audinfo":{"url":"https://gps.openluat.com/aircloud/air_up/audio","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"mtninfo":{"url":"https://gps.openluat.com/aircloud/air_up/file","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"qrinfo":{"url":"https://gps.openluat.com/#/redirect?key=_5oruyMsMk5Ny5ZajRyBqaZEqqaPjVSb93qH"}}
|
||||||
|
[2026-04-08 17:36:15.237][000000003.039] I/user.[excloud]获取到TCP/UDP连接信息 host: 124.71.128.165 port: 9108 key: nil
|
||||||
|
[2026-04-08 17:36:15.242][000000003.039] I/user.[excloud]获取到图片上传信息
|
||||||
|
[2026-04-08 17:36:15.247][000000003.040] I/user.[excloud]获取到音频上传信息
|
||||||
|
[2026-04-08 17:36:15.255][000000003.040] I/user.[excloud]获取到运维日志上传信息
|
||||||
|
[2026-04-08 17:36:15.262][000000003.040] I/user.[excloud]获取到二维码信息
|
||||||
|
[2026-04-08 17:36:15.266][000000003.041] I/user.[excloud]excloud.getip 更新配置: 124.71.128.165 9108
|
||||||
|
[2026-04-08 17:36:15.271][000000003.041] I/user.[excloud]excloud.getip 成功: true 结果: {"ipv4":"124.71.128.165","port":9108}
|
||||||
|
[2026-04-08 17:36:15.276][000000003.042] I/user.[excloud]服务器信息获取成功 host: 124.71.128.165 port: 9108 transport: tcp
|
||||||
|
[2026-04-08 17:36:15.280][000000003.042] I/user.[excloud]创建TCP连接
|
||||||
|
[2026-04-08 17:36:15.286][000000003.043] D/socket connect to 124.71.128.165,9108
|
||||||
|
[2026-04-08 17:36:15.291][000000003.044] network_socket_connect 1610:network 1-0 local port auto select 51002
|
||||||
|
[2026-04-08 17:36:15.295][000000003.045] I/user.[excloud]TCP连接结果 true false
|
||||||
|
[2026-04-08 17:36:15.301][000000003.046] I/user.[excloud]excloud service started
|
||||||
|
[2026-04-08 17:36:15.306][000000003.046] I/user.excloud服务已开启
|
||||||
|
[2026-04-08 17:36:15.311][000000003.047] I/user.[excloud]excloud 自动心跳已启动,间隔 300 秒
|
||||||
|
[2026-04-08 17:36:15.315][000000003.047] I/user.自动心跳已启动
|
||||||
|
[2026-04-08 17:36:15.323][000000003.127] network_default_socket_callback 1123:before process socket 1,event:0xf2000009(连接成功),state:3(正在连接),wait:2(等待连接完成)
|
||||||
|
[2026-04-08 17:36:15.328][000000003.127] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:15.332][000000003.128] I/user.[excloud]socket cb userdata: 0C1843F0 33554449 0
|
||||||
|
[2026-04-08 17:36:15.337][000000003.129] I/user.[excloud]socket TCP连接成功
|
||||||
|
[2026-04-08 17:36:15.342][000000003.129] I/user.用户回调函数 connect_result {"success":true}
|
||||||
|
[2026-04-08 17:36:15.346][000000003.129] I/user.连接成功
|
||||||
|
[2026-04-08 17:36:15.352][000000003.133] I/user.[excloud]构建发送数据 16 3 sh5g0OTP7ThOSlGKmE5jiEMbOBqQWyw9-867920071472378-20250604131416A755490A2989432885
|
||||||
|
[2026-04-08 17:36:15.357][000000003.134] I/user.[excloud]tlv发送数据长度4 85
|
||||||
|
[2026-04-08 17:36:15.362][000000003.135] I/user.[excloud]构建消息头 y r7
|
||||||
|
[2026-04-08 17:36:15.371][000000003.137] I/user.用户回调函数 send_result {"sequence_num":1,"success":true,"error_msg":"Send successful"}
|
||||||
|
[2026-04-08 17:36:15.376][000000003.143] I/user.[excloud]数据发送成功 101 字节
|
||||||
|
[2026-04-08 17:36:15.385][000000003.207] network_default_socket_callback 1123:before process socket 1,event:0xf2000004(发送成功),state:5(在线),wait:3(等待发送完成)
|
||||||
|
[2026-04-08 17:36:15.390][000000003.207] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:15.395][000000003.208] I/user.[excloud]socket cb userdata: 0C1843F0 33554450 0
|
||||||
|
[2026-04-08 17:36:15.403][000000003.208] I/user.[excloud]socket 发送完成
|
||||||
|
[2026-04-08 17:36:15.491][000000003.327] I/user.sys ram 2375920 80156 121112
|
||||||
|
[2026-04-08 17:36:15.496][000000003.328] I/user.lua ram 1048568 174392 190984
|
||||||
|
[2026-04-08 17:36:18.498][000000006.328] I/user.sys ram 2375920 80156 121112
|
||||||
|
[2026-04-08 17:36:18.531][000000006.329] I/user.lua ram 1048568 174712 190984
|
||||||
|
[2026-04-08 17:36:21.500][000000009.329] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:21.518][000000009.330] I/user.lua ram 1048568 175240 190984
|
||||||
|
[2026-04-08 17:36:24.496][000000012.330] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:24.501][000000012.331] I/user.lua ram 1048568 175440 190984
|
||||||
|
[2026-04-08 17:36:27.508][000000015.331] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:27.512][000000015.332] I/user.lua ram 1048568 175632 190984
|
||||||
|
[2026-04-08 17:36:30.505][000000018.332] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:30.511][000000018.333] I/user.lua ram 1048568 175832 190984
|
||||||
|
[2026-04-08 17:36:33.503][000000021.333] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:33.510][000000021.334] I/user.lua ram 1048568 176024 190984
|
||||||
|
[2026-04-08 17:36:36.506][000000024.334] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:36.510][000000024.335] I/user.lua ram 1048568 176216 190984
|
||||||
|
[2026-04-08 17:36:39.512][000000027.335] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:39.524][000000027.336] I/user.lua ram 1048568 176416 190984
|
||||||
|
[2026-04-08 17:36:42.504][000000030.327] I/user.exmux 设置引脚 pwr2 (23) 为高电平
|
||||||
|
[2026-04-08 17:36:42.510][000000030.328] I/user.exmux 设置引脚 pwr1 (2) 为高电平
|
||||||
|
[2026-04-08 17:36:42.513][000000030.328] I/user.exmux 分组 i2c1 打开成功
|
||||||
|
[2026-04-08 17:36:42.517][000000030.329] I2C_MasterSetup 426:I2C1, Total 65 HCNT 22 LCNT 40
|
||||||
|
[2026-04-08 17:36:42.522][000000030.329] CSPI_Setup 1924:APB MP 102400000
|
||||||
|
[2026-04-08 17:36:42.551][000000030.388] I/user.初始化状态 true
|
||||||
|
[2026-04-08 17:36:42.558][000000030.388] CSPI_Rx 2022:block len 7680, total block 80
|
||||||
|
[2026-04-08 17:36:42.561][000000030.389] I/user.照片存储路径 /ram/test.jpg
|
||||||
|
[2026-04-08 17:36:42.564][000000030.389] luat_camera_capture_config 700:0,0,0,0
|
||||||
|
[2026-04-08 17:36:42.568][000000030.389] luat_camera_capture 676:save file in /ram/test.jpg
|
||||||
|
[2026-04-08 17:36:42.572][000000030.391] I/user.sys ram 2375920 696088 696224
|
||||||
|
[2026-04-08 17:36:42.575][000000030.391] I/user.lua ram 1048568 178544 190984
|
||||||
|
[2026-04-08 17:36:43.126][000000030.955] I/user.摄像头数据 58612
|
||||||
|
[2026-04-08 17:36:43.138][000000030.956] I/user.拍照完成
|
||||||
|
[2026-04-08 17:36:43.144][000000030.956] I/user.开始上传图片
|
||||||
|
[2026-04-08 17:36:43.149][000000030.957] I/user.[excloud]开始文件上传 类型: 1 文件: /ram/test.jpg 大小: 58612
|
||||||
|
[2026-04-08 17:36:43.155][000000030.957] I/user.[excloud]开始文件上传 类型: 1 文件: test.jpg 大小: 58612
|
||||||
|
[2026-04-08 17:36:43.160][000000030.958] I/user.[excloud]构建发送数据 23 0 0
|
||||||
|
[2026-04-08 17:36:43.164][000000030.959] I/user.[excloud]构建发送数据 784 0 1
|
||||||
|
[2026-04-08 17:36:43.169][000000030.960] I/user.[excloud]构建发送数据 785 3 test.jpg
|
||||||
|
[2026-04-08 17:36:43.172][000000030.961] I/user.[excloud]构建发送数据 786 0 58612
|
||||||
|
[2026-04-08 17:36:43.177][000000030.963] I/user.[excloud]tlv发送数据长度4 36
|
||||||
|
[2026-04-08 17:36:43.182][000000030.964] I/user.[excloud]构建消息头 y r7
|
||||||
|
[2026-04-08 17:36:43.185][000000030.968] I/user.用户回调函数 send_result {"sequence_num":2,"success":true,"error_msg":"Send successful"}
|
||||||
|
[2026-04-08 17:36:43.189][000000030.973] I/user.[excloud]数据发送成功 52 字节
|
||||||
|
[2026-04-08 17:36:43.195][000000030.985] I/user.[excloud]开始发送HTTP请求 URL: https://gps.openluat.com/aircloud/air_up/image
|
||||||
|
[2026-04-08 17:36:43.199][000000030.989] dns_run 676:gps.openluat.com state 0 id 2 ipv6 0 use dns server2, try 0
|
||||||
|
[2026-04-08 17:36:43.298][000000031.126] dns_run 693:dns all done ,now stop
|
||||||
|
[2026-04-08 17:36:43.304][000000031.135] network_default_socket_callback 1123:before process socket 1,event:0xf2000004(发送成功),state:5(在线),wait:3(等待发送完成)
|
||||||
|
[2026-04-08 17:36:43.308][000000031.135] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:43.312][000000031.136] I/user.[excloud]socket cb userdata: 0C1843F0 33554450 0
|
||||||
|
[2026-04-08 17:36:43.318][000000031.137] I/user.[excloud]socket 发送完成
|
||||||
|
[2026-04-08 17:36:45.565][000000033.392] I/user.sys ram 2375920 876224 1064884
|
||||||
|
[2026-04-08 17:36:45.570][000000033.393] I/user.lua ram 1048568 353216 469512
|
||||||
|
[2026-04-08 17:36:46.436][000000034.268] I/http http close c267f50
|
||||||
|
[2026-04-08 17:36:46.441][000000034.270] I/user.[excloud]excloud.getip文件上传响应 HTTP Code: 200 Body: {"info":"aircloud./aircloud/air_up/image","code":0,"trace":"code:aircloud./aircloud/air_up/image, trcace:","log":"^^^","value":{"uri":"/vsa/aircloud_image/FFZDbqsuzrLpbgPfzVd7De/2026-04/867920071472378/20260408173647_test.jpg","size":"57.00KB","thumb":"/vsa/aircloud_image/FFZDbqsuzrLpbgPfzVd7De/2026-04/867920071472378/20260408173647_testt.jpg"}}
|
||||||
|
[2026-04-08 17:36:46.446][000000034.271] I/user.[excloud]文件上传成功 URL: /vsa/aircloud_image/FFZDbqsuzrLpbgPfzVd7De/2026-04/867920071472378/20260408173647_test.jpg
|
||||||
|
[2026-04-08 17:36:46.450][000000034.271] I/user.[excloud]构建发送数据 24 0 0
|
||||||
|
[2026-04-08 17:36:46.457][000000034.274] I/user.[excloud]构建发送数据 784 0 1
|
||||||
|
[2026-04-08 17:36:46.461][000000034.276] I/user.[excloud]构建发送数据 785 3 test.jpg
|
||||||
|
[2026-04-08 17:36:46.466][000000034.277] I/user.[excloud]构建发送数据 787 0 0
|
||||||
|
[2026-04-08 17:36:46.470][000000034.278] I/user.[excloud]tlv发送数据长度4 36
|
||||||
|
[2026-04-08 17:36:46.475][000000034.279] I/user.[excloud]构建消息头 y r7
|
||||||
|
[2026-04-08 17:36:46.479][000000034.282] I/user.用户回调函数 send_result {"sequence_num":3,"success":true,"error_msg":"Send successful"}
|
||||||
|
[2026-04-08 17:36:46.486][000000034.287] I/user.[excloud]数据发送成功 52 字节
|
||||||
|
[2026-04-08 17:36:46.491][000000034.287] I/user.图片上传成功
|
||||||
|
[2026-04-08 17:36:46.498][000000034.288] I/user.exmux 设置引脚 pwr2 (23) 为低电平
|
||||||
|
[2026-04-08 17:36:46.502][000000034.289] I/user.exmux 设置引脚 pwr1 (2) 为低电平
|
||||||
|
[2026-04-08 17:36:46.507][000000034.289] I/user.exmux 分组 i2c1 关闭成功
|
||||||
|
[2026-04-08 17:36:46.512][000000034.347] network_default_socket_callback 1123:before process socket 1,event:0xf2000004(发送成功),state:5(在线),wait:3(等待发送完成)
|
||||||
|
[2026-04-08 17:36:46.519][000000034.347] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:46.524][000000034.348] I/user.[excloud]socket cb userdata: 0C1843F0 33554450 0
|
||||||
|
[2026-04-08 17:36:46.529][000000034.349] I/user.[excloud]socket 发送完成
|
||||||
|
```
|
||||||
|
4、等待自动扫描任务完成后,LUATOOLS会有如下打印;
|
||||||
|
```lua
|
||||||
|
[2025-11-21 15:19:17.310][000000000.269] I2C_MasterSetup 426:I2C1, Total 65 HCNT 22 LCNT 40
|
||||||
|
[2025-11-21 15:19:17.313][000000000.332] I/user.初始化状态 true
|
||||||
|
[2025-11-21 15:19:17.316][000000000.332] CSPI_Rx 2000:block len 7680, total block 40
|
||||||
|
[2025-11-21 15:19:17.319][000000000.541] I/user.扫码结果 Air780EPM
|
||||||
|
[2025-11-21 15:19:17.323][000000000.542] I/user.扫描完成,扫描结果为: Air780EPM
|
||||||
|
[2025-11-21 15:19:17.327][000000000.542] I/user.Scan result : Air780EPM
|
||||||
|
```
|
||||||
|
|
||||||
|
5、登录 https://iot.luatos.com/ 查看拍摄的照片;
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
--[[
|
||||||
|
@module scan_code
|
||||||
|
@summary AirCAMERA_1040 gc032a摄像头扫描二维码应用模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.11.09
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1040 gc032a摄像头完成一次扫描二维码任务
|
||||||
|
]] --
|
||||||
|
-- 摄像头扩展库模块
|
||||||
|
-- 功能:提供摄像头初始化、扫描和资源管理功能
|
||||||
|
-- 引入excamera扩展库模块
|
||||||
|
local excamera = require "excamera"
|
||||||
|
-- 引入exmux扩展库模块
|
||||||
|
local exmux = require "exmux"
|
||||||
|
|
||||||
|
-- 硬件I2C/SPI配置,当您使用合宙开发板时,请根据具体的开发板版本选择对应的变量,
|
||||||
|
-- exmux库将会自动处理开发板上的I2C/SPI外设,确保总线通讯正常
|
||||||
|
-- 当您使用自己的制作的板子,请参考exmux库的文档,配置对应的变量:https://docs.openluat.com/osapi/ext/exmux/
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_8000_V2.0"
|
||||||
|
local HARDWARE_ENV = "DEV_BOARD_780_V1.2"
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_780_V1.3"
|
||||||
|
|
||||||
|
-- 扫描功能函数
|
||||||
|
-- 作用:循环监听扫描事件,执行摄像头初始化、扫描和资源释放
|
||||||
|
local function scan_code_func()
|
||||||
|
-- 定义变量用于存储操作结果和数据
|
||||||
|
local result, data
|
||||||
|
-- 初始化外设分组开关状态
|
||||||
|
exmux.setup(HARDWARE_ENV)
|
||||||
|
-- 无限循环,持续等待扫描事件
|
||||||
|
while true do
|
||||||
|
-- 配置gc032a摄像头参数表
|
||||||
|
local spi_camera_param = {
|
||||||
|
id = "gc032a", -- SPI摄像头仅支持"gc032a"、"gc0310"、"bf30a2",请带引号填写
|
||||||
|
i2c_id = 1, -- 模块上使用的I2C编号
|
||||||
|
work_mode = 1, -- 工作模式,0为拍照模式,1为扫描模式
|
||||||
|
save_path = nil, -- 扫描结果为字符串返回,使用变量赋值既可
|
||||||
|
camera_pwr = 2, -- 摄像头使能管脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_pwdn = 5, -- 摄像头pwdn开关脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_light = nil -- 摄像头补光灯控制管脚,填写GPIO号即可,无则填nil
|
||||||
|
}
|
||||||
|
-- 等待外部触发扫描事件(SCAN_CODE)
|
||||||
|
sys.waitUntil("SCAN_CODE")
|
||||||
|
-- 打开外设分组
|
||||||
|
exmux.open("i2c1")
|
||||||
|
-- 初始化摄像头,传入配置参数
|
||||||
|
result = excamera.open(spi_camera_param)
|
||||||
|
-- 记录摄像头初始化状态
|
||||||
|
log.info("初始化状态", result)
|
||||||
|
-- 判断摄像头初始化是否成功,不成功则直接关闭,成功则启动扫描
|
||||||
|
if result then
|
||||||
|
-- 执行扫描操作,5秒超时
|
||||||
|
result, data = excamera.scan(5000)
|
||||||
|
-- 扫描执行完成则上传,否则关闭摄像头
|
||||||
|
if result then
|
||||||
|
log.info("Scan result :", data )
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- 关闭摄像头,释放资源
|
||||||
|
excamera.close()
|
||||||
|
-- 关闭外设分组
|
||||||
|
exmux.close("i2c1")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 内存检查函数
|
||||||
|
-- 作用:定期监控系统内存使用情况
|
||||||
|
local function memory_check()
|
||||||
|
-- 无限循环,定期检查内存
|
||||||
|
while true do
|
||||||
|
-- 等待3秒
|
||||||
|
sys.wait(3000)
|
||||||
|
-- 打印系统内存使用信息
|
||||||
|
log.info("sys ram", rtos.meminfo("sys"))
|
||||||
|
-- 打印Lua虚拟机内存使用信息
|
||||||
|
log.info("lua ram", rtos.meminfo("lua"))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- AirCAMERA_1040 DEMO应用触发函数,每30S触发一次扫描
|
||||||
|
local function AirCAMERA_1040_func()
|
||||||
|
while true do
|
||||||
|
sys.publish("SCAN_CODE")
|
||||||
|
sys.wait(30000)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 创建扫描功能任务
|
||||||
|
-- 作用:在单独的任务中运行扫描逻辑
|
||||||
|
sys.taskInit(scan_code_func)
|
||||||
|
|
||||||
|
-- 创建内存监控任务
|
||||||
|
-- 作用:在单独的任务中运行内存监控逻辑
|
||||||
|
sys.taskInit(memory_check)
|
||||||
|
|
||||||
|
-- 创建扫描触发任务
|
||||||
|
-- 作用:每30秒触发一次扫描二维码业务
|
||||||
|
sys.taskInit(AirCAMERA_1040_func)
|
||||||
+142
@@ -0,0 +1,142 @@
|
|||||||
|
--[[
|
||||||
|
@module take_photo_http_post
|
||||||
|
@summary AirCAMERA_1040 gc032a摄像头拍照上传应用模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.11.09
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1040 gc032a摄像头完成一次拍照上传任务
|
||||||
|
]] -- 摄像头拍照模块
|
||||||
|
-- 功能:提供摄像头初始化、拍照和资源管理功能
|
||||||
|
-- 引入excamera扩展库模块
|
||||||
|
local excamera = require "excamera"
|
||||||
|
-- 引入httpplus扩展库模块
|
||||||
|
local httpplus = require "httpplus"
|
||||||
|
-- 引入exmux扩展库模块
|
||||||
|
local exmux = require "exmux"
|
||||||
|
|
||||||
|
-- 硬件I2C/SPI配置,当您使用合宙开发板时,请根据具体的开发板版本选择对应的变量,
|
||||||
|
-- exmux库将会自动处理开发板上的I2C/SPI外设,确保总线通讯正常
|
||||||
|
-- 当您使用自己的制作的板子,请参考exmux库的文档,配置对应的变量:https://docs.openluat.com/osapi/ext/exmux/
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_8000_V2.0"
|
||||||
|
local HARDWARE_ENV = "DEV_BOARD_780_V1.2"
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_780_V1.3"
|
||||||
|
|
||||||
|
-- 定义照片保存方式,有三种类型:
|
||||||
|
-- 1、ZBUFF保存,输入"ZBUFF"即可,excamera库会自动处理ZBUFF
|
||||||
|
-- 2、保存到内存文件系统中,路径名需指向/ram/文件夹
|
||||||
|
-- 3、保存到内置FLASH文件系统中
|
||||||
|
-- 选择其中一个即可,注释另两个路径变量
|
||||||
|
local save_method = "ZBUFF"
|
||||||
|
-- local save_method = "/ram/test.jpg"
|
||||||
|
-- local save_method = "/test.jpg"
|
||||||
|
|
||||||
|
-- 拍照功能函数
|
||||||
|
-- 作用:循环监听拍照事件,执行摄像头初始化、拍照和资源释放
|
||||||
|
local function capture_func()
|
||||||
|
-- 定义变量用于存储操作结果和数据
|
||||||
|
local result, data
|
||||||
|
-- 初始化外设分组开关状态
|
||||||
|
exmux.setup(HARDWARE_ENV)
|
||||||
|
-- 无限循环,持续等待拍照事件
|
||||||
|
while true do
|
||||||
|
-- 配置gc032a摄像头参数表
|
||||||
|
local spi_camera_param = {
|
||||||
|
id = "gc032a", -- SPI摄像头仅支持"gc032a"、"gc0310"、"bf30a2",请带引号填写
|
||||||
|
i2c_id = 1, -- 模块上使用的I2C编号
|
||||||
|
work_mode = 0, -- 工作模式,0为拍照模式,1为扫描模式
|
||||||
|
save_path = save_method, -- 拍照结果存储路径,可用"ZBUFF"交由excamera库内部管理
|
||||||
|
camera_pwr = 2, -- 摄像头使能管脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_pwdn = 5, -- 摄像头pwdn开关脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_light = nil -- 摄像头补光灯控制管脚,填写GPIO号即可,无则填nil
|
||||||
|
}
|
||||||
|
-- 等待外部触发拍照事件(ONCE_CAPTURE)
|
||||||
|
sys.waitUntil("ONCE_CAPTURE")
|
||||||
|
-- 打开外设分组
|
||||||
|
exmux.open("i2c1")
|
||||||
|
-- 初始化摄像头,传入配置参数
|
||||||
|
result = excamera.open(spi_camera_param)
|
||||||
|
-- 记录摄像头初始化状态
|
||||||
|
log.info("初始化状态", result)
|
||||||
|
-- 判断摄像头初始化是否成功,不成功则直接关闭,成功则启动拍照
|
||||||
|
if result then
|
||||||
|
-- 执行拍照操作
|
||||||
|
result, data = excamera.photo()
|
||||||
|
-- 拍照执行完成则上传,否则关闭摄像头
|
||||||
|
if result then
|
||||||
|
-- 通过网卡状态判断WIFI是否连接成功,WIFI连接成功后再运行照片上传任务。
|
||||||
|
while not socket.adapter(socket.dft()) do
|
||||||
|
-- 在此处阻塞等待WIFI连接成功的消息"IP_READY",避免联网过快,丢失了"IP_READY"信息而导致一直被卡住。
|
||||||
|
-- 或者等待30秒超时退出阻塞等待状态
|
||||||
|
log.warn("tcp_client_main_task_func", "wait IP_READY")
|
||||||
|
sys.waitUntil("IP_READY", 30000)
|
||||||
|
end
|
||||||
|
if type(data) == "userdata" then
|
||||||
|
data = data:query()
|
||||||
|
else
|
||||||
|
data = io.readFile(data)
|
||||||
|
end
|
||||||
|
-- 通过网卡(本demo使用的是socket.LWIP_STA网卡)将拍摄到的照片数据result上传到服务器air32.cn
|
||||||
|
-- 如果上传成功,电脑上浏览器打开https://uploadtest.luatos.com/upload/jpg/,打开对应的测试日期目录,点击具体的测试时间照片,可以查看摄像头拍照上传的照片
|
||||||
|
-- 执行httpplus.request后,等待服务器的http应答,此处会阻塞当前task,等待整个过程成功结束或者出现错误异常结束
|
||||||
|
-- code表示结果,number类型,详细说明参考API手册,一般来说:
|
||||||
|
-- 200表示成功
|
||||||
|
-- 小于0的值表示出错,例如-8表示超时错误
|
||||||
|
-- 其余结果值参考API手册
|
||||||
|
-- 因为Air32.com平台已经不开放使用了,所以该DEMO仅作上传照片至服务器的演示作用,使用时请将上传URL修改为您自己的服务器地址
|
||||||
|
-- 或者通过excloud扩展库上传到合宙IOT平台uploadtest.luatos.com,详见:photo_to_aircloud.lua,详见:photo_to_aircloud.lua
|
||||||
|
local code = httpplus.request({
|
||||||
|
url = "http://uploadtest.luatos.com/api/upload/jpg",
|
||||||
|
method = "POST",
|
||||||
|
body = data
|
||||||
|
})
|
||||||
|
-- 打印http传输状态
|
||||||
|
log.info("http_upload_photo_task_func", "httpplus.request", code)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- 判断是否ZBUFF存储方式,如果是文件系统保存则删除本地文件
|
||||||
|
if save_method ~= "ZBUFF" then
|
||||||
|
os.remove(spi_camera_param.save_path)
|
||||||
|
end
|
||||||
|
-- 关闭摄像头,释放资源
|
||||||
|
-- 使用ZBUFF存储方式时,close传入true后,excamera内部创建的ZBUFF会缩减至0字节,放出内存但是不释放ZBUFF,便于下次拍照时调用;
|
||||||
|
-- 重复申请和释放ZBUFF会导致垃圾内存堆积,影响系统内存;
|
||||||
|
excamera.close(true)
|
||||||
|
-- 关闭外设分组
|
||||||
|
exmux.close("i2c1")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 内存检查函数
|
||||||
|
-- 作用:定期监控系统内存使用情况
|
||||||
|
local function memory_check()
|
||||||
|
-- 无限循环,定期检查内存
|
||||||
|
while true do
|
||||||
|
-- 等待3秒
|
||||||
|
sys.wait(3000)
|
||||||
|
-- 打印系统内存使用信息
|
||||||
|
log.info("sys ram", rtos.meminfo("sys"))
|
||||||
|
-- 打印Lua虚拟机内存使用信息
|
||||||
|
log.info("lua ram", rtos.meminfo("lua"))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- AirCAMERA_1040 DEMO应用触发函数,每30S触发一次拍照
|
||||||
|
local function AirCAMERA_1040_func()
|
||||||
|
while true do
|
||||||
|
sys.publish("ONCE_CAPTURE")
|
||||||
|
sys.wait(30000)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 创建拍照功能任务
|
||||||
|
-- 作用:在单独的任务中运行拍照逻辑
|
||||||
|
sys.taskInit(capture_func)
|
||||||
|
|
||||||
|
-- 创建内存监控任务
|
||||||
|
-- 作用:在单独的任务中运行内存监控逻辑
|
||||||
|
sys.taskInit(memory_check)
|
||||||
|
|
||||||
|
-- 创建拍照触发任务
|
||||||
|
-- 作用:每30秒触发一次拍照上传业务
|
||||||
|
sys.taskInit(AirCAMERA_1040_func)
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
--[[
|
||||||
|
@module main
|
||||||
|
@summary LuatOS用户应用脚本文件入口,总体调度应用逻辑
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.11.09
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1050 SPI摄像头完成一次拍照上传任务
|
||||||
|
]]
|
||||||
|
--[[
|
||||||
|
必须定义PROJECT和VERSION变量,Luatools工具会用到这两个变量,远程升级功能也会用到这两个变量
|
||||||
|
PROJECT:项目名,ascii string类型
|
||||||
|
可以随便定义,只要不使用,就行
|
||||||
|
VERSION:项目版本号,ascii string类型
|
||||||
|
如果使用合宙iot.openluat.com进行远程升级,必须按照"XXX.YYY.ZZZ"三段格式定义:
|
||||||
|
X、Y、Z各表示1位数字,三个X表示的数字可以相同,也可以不同,同理三个Y和三个Z表示的数字也是可以相同,可以不同
|
||||||
|
因为历史原因,YYY这三位数字必须存在,但是没有任何用处,可以一直写为999
|
||||||
|
如果不使用合宙iot.openluat.com进行远程升级,根据自己项目的需求,自定义格式即可
|
||||||
|
]]
|
||||||
|
PROJECT = "AirCAMERA_1050_Demo"
|
||||||
|
VERSION = "001.999.000"
|
||||||
|
|
||||||
|
-- 在日志中打印项目名和项目版本号
|
||||||
|
log.info("main", PROJECT, VERSION)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-- 如果内核固件支持errDump功能,此处进行配置,【强烈建议打开此处的注释】
|
||||||
|
-- 因为此功能模块可以记录并且上传脚本在运行过程中出现的语法错误或者其他自定义的错误信息,可以初步分析一些设备运行异常的问题
|
||||||
|
-- 以下代码是最基本的用法,更复杂的用法可以详细阅读API说明文档
|
||||||
|
-- 启动errDump日志存储并且上传功能,600秒上传一次
|
||||||
|
-- if errDump then
|
||||||
|
-- errDump.config(true, 600)
|
||||||
|
-- end
|
||||||
|
|
||||||
|
|
||||||
|
-- 使用LuatOS开发的任何一个项目,都强烈建议使用远程升级FOTA功能
|
||||||
|
-- 可以使用合宙的iot.openluat.com平台进行远程升级
|
||||||
|
-- 也可以使用客户自己搭建的平台进行远程升级
|
||||||
|
-- 远程升级的详细用法,可以参考fota的demo进行使用
|
||||||
|
|
||||||
|
|
||||||
|
-- 启动一个循环定时器
|
||||||
|
-- 每隔3秒钟打印一次总内存,实时的已使用内存,历史最高的已使用内存情况
|
||||||
|
-- 方便分析内存使用是否有异常
|
||||||
|
-- sys.timerLoopStart(function()
|
||||||
|
-- log.info("mem.lua", rtos.meminfo())
|
||||||
|
-- log.info("mem.sys", rtos.meminfo("sys"))
|
||||||
|
-- end, 3000)
|
||||||
|
|
||||||
|
-- 导入netdrv_4g联网状态模块
|
||||||
|
require "netdrv_4g"
|
||||||
|
|
||||||
|
-- 导入gc0310配置表
|
||||||
|
require "gc0310"
|
||||||
|
|
||||||
|
-- 拍照和扫描模式需要在初始化时确认,导入对应模式的DEMO后注释另一个DEMO,拍照和扫描不可同时使用
|
||||||
|
--[[ 导入photo_to_aircloud拍照上传应用DEMO,该DEMO上传照片至aircloud平台,需要先配置photo_to_aircloud.lua中105行的 auth_key ,否则会报错
|
||||||
|
auth_key:aircloud应用的认证密钥,用于验证上传请求的合法性
|
||||||
|
获取方式为:登录iot.openluat.com,点击”我的项目“,找到您所使用的模块对应的项目,即可复制项目KEY
|
||||||
|
当您的模块没有在您的账号下时,请参考https://docs.openluat.com/air780epm/product/attributioniot/ 处理办法,获取项目KEY]] --
|
||||||
|
require "photo_to_aircloud"
|
||||||
|
|
||||||
|
-- 导入take_photo_http_post拍照上传应用DEMO,air32.cn为虚拟服务器,仅用于演示,实际使用时请替换为自己的服务器。
|
||||||
|
-- 与photo_to_aircloud.lua二选一执行即可,不可同时导入
|
||||||
|
-- require "take_photo_http_post"
|
||||||
|
|
||||||
|
-- 导入scan_code扫描二维码应用DEMO
|
||||||
|
-- require "scan_code"
|
||||||
|
|
||||||
|
|
||||||
|
-- 用户代码已结束---------------------------------------------
|
||||||
|
-- 结尾总是这一句
|
||||||
|
sys.run()
|
||||||
|
-- sys.run()之后后面不要加任何语句!!!!!
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
--[[
|
||||||
|
@module netdrv_4g
|
||||||
|
@summary “4G网卡”驱动模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.07.01
|
||||||
|
@author 朱天华
|
||||||
|
@usage
|
||||||
|
本文件为4G网卡驱动模块,核心业务逻辑为:
|
||||||
|
1、监听"IP_READY"和"IP_LOSE",在日志中进行打印;
|
||||||
|
|
||||||
|
本文件没有对外接口,直接在其他功能模块中require "netdrv_4g"就可以加载运行;
|
||||||
|
]]
|
||||||
|
|
||||||
|
local function ip_ready_func(ip, adapter)
|
||||||
|
if adapter == socket.LWIP_GP then
|
||||||
|
log.info("netdrv_4g.ip_ready_func", "IP_READY", socket.localIP(socket.LWIP_GP))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
local function ip_lose_func(adapter)
|
||||||
|
if adapter == socket.LWIP_GP then
|
||||||
|
log.warn("netdrv_4g.ip_lose_func", "IP_LOSE")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
|
-- 此处订阅"IP_READY"和"IP_LOSE"两种消息
|
||||||
|
-- 在消息的处理函数中,仅仅打印了一些信息,便于实时观察4G网络的连接状态
|
||||||
|
-- 也可以根据自己的项目需求,在消息处理函数中增加自己的业务逻辑控制,例如可以在连网状态发生改变时更新网络图标
|
||||||
|
sys.subscribe("IP_READY", ip_ready_func)
|
||||||
|
sys.subscribe("IP_LOSE", ip_lose_func)
|
||||||
|
|
||||||
|
|
||||||
|
-- 设置默认网卡为socket.LWIP_GP
|
||||||
|
-- 在Air8000上,内核固件运行起来之后,默认网卡就是socket.LWIP_GP
|
||||||
|
-- 在单4G网卡使用场景下,下面这一行代码加不加都没有影响,为了和其他网卡驱动模块的代码风格保持一致,所以加上了
|
||||||
|
socket.dft(socket.LWIP_GP)
|
||||||
+287
@@ -0,0 +1,287 @@
|
|||||||
|
--[[
|
||||||
|
@module photo_to_aircloud
|
||||||
|
@summary AirCAMERA_1050 gc0310摄像头拍照上传应用模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2026.4.30
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1050 gc0310摄像头完成一次拍照上传任务
|
||||||
|
Air780EPM的sys ram内存资源只有2.3M,在使用camera功能时,需要非常谨慎,避免内存泄漏导致系统崩溃,需要注意以下情况:
|
||||||
|
1、exmcamera业务执行时,必须要确保有连续的内存空间,否则会导致excamera.open()初始化失败,需要的空间计算方式为:
|
||||||
|
( 摄像头像素高 X 摄像头像素宽 X 2 ),用“GC032A”举例,内存空间为:640 * 480 * 2 = 614400 (B) ≈ 620KB
|
||||||
|
2、当使用ZBUFF方式存储照片,或者将照片放到 /ram/ 路径下保存时,必须确保有更多的内存连续空间,需要的总空间大小计算方式为:
|
||||||
|
( 摄像头像素高 X 摄像头像素宽 X 3.5 ),用“GC032A”举例,内存空间为:640 * 480 * 3.5 = 1075200 (B) ≈ 1MB
|
||||||
|
3、本DEMO为常规模式下,摄像头稳定供电使用,DEMO逻辑为excamera.open()初始化完摄像头后,只需要重复调用excamera.photo()拍照即可,不需要反复的初始化关闭摄像头;
|
||||||
|
4、在实际应用中,务必将摄像头初始化的优先级排前,因为摄像头业务占用内存过大,尽早的初始化可以确保摄像头初始化时拿到足够的连续内存,确保后续拍照时能够正常执行;
|
||||||
|
5、Air780EPM的内存非常有限,在摄像头需求高的产品设计中,请选择Air780EHM/EGH/EHV、Air8000、Air700ECH这类 8MB + 8MB 的SOC,更大的内存才是摄像头业务稳定运行的最优解;
|
||||||
|
6、低功耗模式下使用excamera请参考lowpower DEMO,链接:https://docs.openluat.com/air780epm/luatos/app/lowpower/sleep/#_1
|
||||||
|
]] --
|
||||||
|
-- 摄像头拍照模块
|
||||||
|
-- 功能:提供摄像头初始化、拍照和资源管理功能
|
||||||
|
-- 引入excamera扩展库模块
|
||||||
|
local excamera = require "excamera"
|
||||||
|
-- 引入httpplus扩展库模块
|
||||||
|
local httpplus = require "httpplus"
|
||||||
|
-- 引入exmux扩展库模块
|
||||||
|
local exmux = require "exmux"
|
||||||
|
-- 导入excloud库
|
||||||
|
local excloud = require "excloud"
|
||||||
|
-- pm.ioVol(pm.IOVOL_ALL_GPIO, 2800)
|
||||||
|
|
||||||
|
-- 硬件I2C/SPI配置,当您使用合宙开发板时,请根据具体的开发板版本选择对应的变量,
|
||||||
|
-- exmux库将会自动处理开发板上的I2C/SPI外设,确保总线通讯正常
|
||||||
|
-- 当您使用自己的制作的板子,请参考exmux库的文档,配置对应的变量:https://docs.openluat.com/osapi/ext/exmux/
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_8000_V2.0"
|
||||||
|
local HARDWARE_ENV = "DEV_BOARD_780_V1.2"
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_780_V1.3"
|
||||||
|
|
||||||
|
-- 定义照片保存方式,有三种类型:
|
||||||
|
-- 1、ZBUFF保存,输入"ZBUFF"即可,excamera库会自动处理ZBUFF
|
||||||
|
-- 2、保存到内存文件系统中,路径名需指向/ram/文件夹
|
||||||
|
-- 3、保存到内置FLASH文件系统中
|
||||||
|
-- 选择其中一个即可,注释另两个路径变量
|
||||||
|
-- local save_method = "ZBUFF"
|
||||||
|
local save_method = "/ram/test.jpg"
|
||||||
|
-- local save_method = "/test.jpg"
|
||||||
|
|
||||||
|
--[[
|
||||||
|
excloud事件回调函数
|
||||||
|
参数:
|
||||||
|
event: 事件类型字符串
|
||||||
|
data: 事件数据,根据事件类型不同而不同
|
||||||
|
|
||||||
|
事件类型说明:
|
||||||
|
connect_result: 连接结果
|
||||||
|
auth_result: 认证结果
|
||||||
|
disconnect: 断开连接
|
||||||
|
reconnect_failed: 重连失败
|
||||||
|
]]
|
||||||
|
function on_excloud_event(event, data)
|
||||||
|
-- 打印事件信息
|
||||||
|
log.info("用户回调函数", event, json.encode(data))
|
||||||
|
-- 处理连接结果事件
|
||||||
|
if event == "connect_result" then
|
||||||
|
if data.success then
|
||||||
|
log.info("连接成功")
|
||||||
|
-- 发布连接成功消息,通知其他任务
|
||||||
|
sys.publish("aircloud_connected")
|
||||||
|
else
|
||||||
|
log.info("连接失败: " .. (data.error or "未知错误"))
|
||||||
|
end
|
||||||
|
-- 处理认证结果事件
|
||||||
|
elseif event == "auth_result" then
|
||||||
|
if data.success then
|
||||||
|
log.info("认证成功")
|
||||||
|
else
|
||||||
|
log.info("认证失败: " .. data.message)
|
||||||
|
end
|
||||||
|
-- 处理断开连接事件
|
||||||
|
elseif event == "disconnect" then
|
||||||
|
log.warn("与服务器断开连接")
|
||||||
|
-- 处理重连失败事件
|
||||||
|
elseif event == "reconnect_failed" then
|
||||||
|
log.info("重连失败,已尝试 " .. data.count .. " 次")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 注册excloud事件回调函数
|
||||||
|
excloud.on(on_excloud_event)
|
||||||
|
|
||||||
|
--[[
|
||||||
|
excloud任务函数
|
||||||
|
功能:
|
||||||
|
1. 等待网络连接就绪
|
||||||
|
2. 配置excloud参数
|
||||||
|
3. 初始化并开启excloud服务
|
||||||
|
4. 启动自动心跳
|
||||||
|
]]
|
||||||
|
local function excloud_task_func()
|
||||||
|
-- 如果当前时间点设置的默认网卡还没有连接成功,一直在这里循环等待
|
||||||
|
while not socket.adapter(socket.dft()) do
|
||||||
|
log.warn("excloud_task_func", "wait IP_READY", socket.dft())
|
||||||
|
-- 在此处阻塞等待默认网卡连接成功的消息"IP_READY"
|
||||||
|
-- 或者等待1秒超时退出阻塞等待状态;
|
||||||
|
-- 注意:此处的1000毫秒超时不要修改的更长;
|
||||||
|
-- 因为当使用exnetif.set_priority_order配置多个网卡连接外网的优先级时,会隐式的修改默认使用的网卡
|
||||||
|
-- 当exnetif.set_priority_order的调用时序和此处的socket.adapter(socket.dft())判断时序有可能不匹配
|
||||||
|
-- 此处的1秒,能够保证,即使时序不匹配,也能1秒钟退出阻塞状态,再去判断socket.adapter(socket.dft())
|
||||||
|
sys.waitUntil("IP_READY", 1000)
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 配置excloud参数
|
||||||
|
local ok, err_msg = excloud.setup({
|
||||||
|
use_getip = true, -- 使用getip服务
|
||||||
|
device_type = 1, -- 4G设备
|
||||||
|
auth_key = "sh5g0OTP7ThOSlGKmE5jiEMbOBqQWyw9", -- 认证密钥
|
||||||
|
transport = "tcp", -- 使用TCP传输
|
||||||
|
auto_reconnect = true, -- 自动重连
|
||||||
|
reconnect_interval = 10, -- 重连间隔(秒)
|
||||||
|
max_reconnect = 5, -- 最大重连次数
|
||||||
|
mtn_log_enabled = true, -- 启用运维日志
|
||||||
|
mtn_log_blocks = 2, -- 日志文件块数
|
||||||
|
mtn_log_write_way = excloud.MTN_LOG_CACHE_WRITE -- 缓存写入方式
|
||||||
|
})
|
||||||
|
|
||||||
|
-- 检查初始化是否成功
|
||||||
|
if not ok then
|
||||||
|
log.info("初始化失败: " .. err_msg)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
log.info("excloud初始化成功")
|
||||||
|
|
||||||
|
-- 开启excloud服务
|
||||||
|
local ok, err_msg = excloud.open()
|
||||||
|
if not ok then
|
||||||
|
log.info("开启excloud服务失败: " .. err_msg)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
log.info("excloud服务已开启")
|
||||||
|
|
||||||
|
-- 启动自动心跳,默认5分钟一次的心跳
|
||||||
|
excloud.start_heartbeat()
|
||||||
|
log.info("自动心跳已启动")
|
||||||
|
end
|
||||||
|
|
||||||
|
--[[
|
||||||
|
照片上传任务函数
|
||||||
|
功能:
|
||||||
|
1. 等待excloud连接建立
|
||||||
|
2. 等待图片数据
|
||||||
|
3. 上传图片到云端
|
||||||
|
4. 处理上传结果
|
||||||
|
]]
|
||||||
|
function upload_image_fun(image)
|
||||||
|
|
||||||
|
-- 连接成功,等待图片数据
|
||||||
|
if excloud.status().is_connected then
|
||||||
|
log.info("开始上传图片")
|
||||||
|
if image then
|
||||||
|
local ok, err = excloud.upload_image(image, "test.jpg")
|
||||||
|
if ok then
|
||||||
|
log.info("图片上传成功")
|
||||||
|
return true
|
||||||
|
else
|
||||||
|
log.error("图片上传失败:", err)
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
else
|
||||||
|
log.warn("测试图片文件不存在")
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- 连接断开,等待重连
|
||||||
|
log.info("excloud连接已断开,等待重连")
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 拍照功能函数
|
||||||
|
-- 作用:循环监听拍照事件,执行摄像头初始化、拍照和资源释放
|
||||||
|
local function capture_func()
|
||||||
|
-- 定义变量用于存储操作结果和数据
|
||||||
|
local result, data, err
|
||||||
|
-- 增加重试次数,最多重试5次,避免日志量过大
|
||||||
|
local retry_count = 0
|
||||||
|
-- 初始化开发板
|
||||||
|
exmux.setup(HARDWARE_ENV)
|
||||||
|
-- 出现异常后重新初始化,最多重试5次
|
||||||
|
while retry_count < 5 do
|
||||||
|
-- 配置gc0310摄像头参数表
|
||||||
|
local spi_camera_param = {
|
||||||
|
id = "gc0310", -- SPI摄像头仅支持"gc032a"、"gc0310"、"bf30a2",请带引号填写
|
||||||
|
i2c_id = 1, -- 模块上使用的I2C编号
|
||||||
|
work_mode = 0, -- 工作模式,0为拍照模式,1为扫描模式
|
||||||
|
save_path = save_method, -- 拍照结果存储路径,可用"ZBUFF"交由excamera库内部管理
|
||||||
|
camera_pwr = 2, -- 摄像头使能管脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_pwdn = 5, -- 摄像头pwdn开关脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_light = nil -- 摄像头补光灯控制管脚,填写GPIO号即可,无则填nil
|
||||||
|
}
|
||||||
|
-- 打开外设分组
|
||||||
|
exmux.open("i2c1")
|
||||||
|
-- 初始化摄像头,传入配置参数
|
||||||
|
result = excamera.open(spi_camera_param)
|
||||||
|
-- 记录摄像头初始化状态
|
||||||
|
log.info("初始化状态", result)
|
||||||
|
-- 判断摄像头初始化是否成功,不成功则直接关闭,成功则启动拍照
|
||||||
|
-- 无限循环,持续等待拍照事件
|
||||||
|
while result do
|
||||||
|
-- 等待外部触发拍照事件(ONCE_CAPTURE)
|
||||||
|
sys.waitUntil("ONCE_CAPTURE")
|
||||||
|
-- 执行拍照操作
|
||||||
|
result, data = excamera.photo()
|
||||||
|
-- 拍照执行完成则上传,否则关闭摄像头
|
||||||
|
if result then
|
||||||
|
-- 通过网卡状态判断WIFI是否连接成功,WIFI连接成功后再运行照片上传任务。
|
||||||
|
while not socket.adapter(socket.dft()) do
|
||||||
|
-- 在此处阻塞等待WIFI连接成功的消息"IP_READY",避免联网过快,丢失了"IP_READY"信息而导致一直被卡住。
|
||||||
|
-- 或者等待30秒超时退出阻塞等待状态
|
||||||
|
log.warn("tcp_client_main_task_func", "wait IP_READY")
|
||||||
|
sys.waitUntil("IP_READY", 30000)
|
||||||
|
end
|
||||||
|
upload_image_fun(data)
|
||||||
|
end
|
||||||
|
-- 判断是否ZBUFF存储方式,如果是文件系统保存则删除本地文件
|
||||||
|
if save_method ~= "ZBUFF" then
|
||||||
|
os.remove(spi_camera_param.save_path)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- 关闭摄像头,释放资源
|
||||||
|
-- 使用ZBUFF存储方式时,close传入true后,excamera内部创建的ZBUFF会缩减至0字节,放出内存但是不释放ZBUFF,便于下次拍照时调用;
|
||||||
|
-- 重复申请和释放ZBUFF会导致垃圾内存堆积,影响系统内存;
|
||||||
|
excamera.close(true)
|
||||||
|
-- 关闭外设分组
|
||||||
|
exmux.close("i2c1")
|
||||||
|
-- 拍照出错,等待5秒,重试摄像头初始化
|
||||||
|
sys.wait(5000)
|
||||||
|
-- 重试次数增加
|
||||||
|
retry_count = retry_count + 1
|
||||||
|
log.info("retry_count", retry_count)
|
||||||
|
end
|
||||||
|
-- 重试5次后,提示用户检查摄像头连接或重启设备
|
||||||
|
log.info("camera init failed, please check the camera connection or reboot, retry_count:", retry_count)
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 内存检查函数
|
||||||
|
-- 作用:定期监控系统内存使用情况
|
||||||
|
local function memory_check()
|
||||||
|
-- 无限循环,定期检查内存
|
||||||
|
while true do
|
||||||
|
-- 等待3秒
|
||||||
|
sys.wait(3000)
|
||||||
|
-- 打印系统内存使用信息
|
||||||
|
log.info("sys ram", rtos.meminfo("sys"))
|
||||||
|
-- 打印Lua虚拟机内存使用信息
|
||||||
|
log.info("lua ram", rtos.meminfo("lua"))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- AirCAMERA_1050 DEMO应用触发函数,每30S触发一次拍照
|
||||||
|
local function AirCAMERA_1050_func()
|
||||||
|
while true do
|
||||||
|
sys.wait(30000)
|
||||||
|
sys.publish("ONCE_CAPTURE")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 按键触发函数,用于手动拍照拍照
|
||||||
|
local function press_key()
|
||||||
|
log.info("boot press")
|
||||||
|
sys.publish("ONCE_CAPTURE")
|
||||||
|
end
|
||||||
|
-- 配置BOOT按键引脚为输入模式,下拉电阻,上升沿触发
|
||||||
|
gpio.setup(0, press_key, gpio.PULLDOWN, gpio.RISING)
|
||||||
|
gpio.debounce(0, 100, 1)
|
||||||
|
|
||||||
|
-- 启动excloud连接任务
|
||||||
|
sys.taskInit(excloud_task_func)
|
||||||
|
|
||||||
|
-- 创建拍照功能任务
|
||||||
|
-- 作用:在单独的任务中运行拍照逻辑
|
||||||
|
sys.taskInit(capture_func)
|
||||||
|
|
||||||
|
-- 创建内存监控任务
|
||||||
|
-- 作用:在单独的任务中运行内存监控逻辑
|
||||||
|
sys.taskInit(memory_check)
|
||||||
|
|
||||||
|
-- 创建拍照触发任务
|
||||||
|
-- 作用:每30秒触发一次拍照上传业务
|
||||||
|
sys.taskInit(AirCAMERA_1050_func)
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
# AirCAMERA_1050 DEMO
|
||||||
|
|
||||||
|
## 演示功能概述
|
||||||
|
|
||||||
|
本示例主要是展示 AirCAMERA_1050 的使用,本地拍摄照片后通过 httpplus 扩展库将图片上传至 air32.com
|
||||||
|
|
||||||
|
1、main.lua:主程序入口
|
||||||
|
|
||||||
|
2、take_photo_http_post.lua:执行拍照后使用推送照片上传至air32.cn服务器,该服务器为虚拟服务器,仅用于演示,实际使用时请替换为自己的服务器。
|
||||||
|
|
||||||
|
3、scan_code.lua:扫描二维码应用DEMO模块
|
||||||
|
|
||||||
|
4、netdrv_4g.lua:联网状态检测模块
|
||||||
|
|
||||||
|
5、photo_to_aircloud.lua:执行拍照后使用推送照片上传至aircloud平台
|
||||||
|
|
||||||
|
注意事项:
|
||||||
|
|
||||||
|
- 拍照或者扫描模式需要在摄像头初始化时确定
|
||||||
|
- 如使用拍照模式就无法使用扫描模式,扫描模式同理
|
||||||
|
- 需要拍照后执行扫描的话需要重新初始化
|
||||||
|
- 所以拍照和扫描不可同时使用,如需切换模式需重新初始化
|
||||||
|
- 因为Air32.com平台已经不开放使用了,所以该DEMO仅作上传照片至服务器的演示作用,使用时请将上传URL修改为您自己的服务器地址,或者通过excloud扩展库上传到合宙IOT平台uploadtest.luatos.com
|
||||||
|
|
||||||
|
## 演示功能概述
|
||||||
|
|
||||||
|
### 1、主程序入口模块(main.lua)
|
||||||
|
|
||||||
|
- 初始化项目信息和版本号
|
||||||
|
- 初始化看门狗,并定时喂狗
|
||||||
|
- 启动一个循环定时器,每隔 3 秒钟打印一次总内存,实时的已使用内存,历史最高的已使用内存情况方便分析内存使用是否有异常
|
||||||
|
- 加载 netdrv_4g 4G联网状态检测模块
|
||||||
|
- 加载 photo_to_aircloud 拍照上传至aircloud平台模块,务必先配置auth_key,否则会报错
|
||||||
|
- 加载 take_photo_http_post 模块
|
||||||
|
|
||||||
|
### 2、4G联网状态检测模块(netdrv_4g.lua)
|
||||||
|
|
||||||
|
- 订阅"IP_READY"消息,收到消息后打印联网成功日志
|
||||||
|
- 订阅"IP_LOSE"消息,收到消息后打印联网失败日志
|
||||||
|
|
||||||
|
### 3、拍照上传服务器演示模块(take_photo_http_post.lua)
|
||||||
|
|
||||||
|
- 每 30 秒触发一次拍照:AirCAMERA_1050_func()
|
||||||
|
- 每 3 秒打印一次系统和 LUA 的内存信息:memory_check()
|
||||||
|
- 配置摄像头信息表:spi_camera_param
|
||||||
|
- 初始化摄像头:excamera.open()
|
||||||
|
- 执行拍照:excamera.photo()
|
||||||
|
- 上传照片:httpplus.request()
|
||||||
|
- 关闭摄像头:excamera.close()
|
||||||
|
|
||||||
|
### 4、扫描二维码应用DEMO(scan_code.lua)
|
||||||
|
|
||||||
|
- 每 30 秒触发一次拍照:AirCAMERA_1050_func()
|
||||||
|
- 每 3 秒打印一次系统和 LUA 的内存信息:memory_check()
|
||||||
|
- 配置摄像头信息表:spi_camera_param
|
||||||
|
- 初始化摄像头:excamera.open()
|
||||||
|
- 执行扫描:excamera.scan()
|
||||||
|
- 关闭摄像头:excamera.close()
|
||||||
|
|
||||||
|
### 5、拍照上传至aircloud平台业务模块(photo_to_aircloud.lua)
|
||||||
|
|
||||||
|
- 配置excloud链接,启动心跳包
|
||||||
|
- 开启自动重连机制,断网后自动重连
|
||||||
|
- 订阅excloud_post_image_done消息,收到消息后打印上传结果:log.info("excloud_post_image_func", err)
|
||||||
|
- 每 30 秒触发一次拍照:AirCAMERA_1050_func()
|
||||||
|
- 每 3 秒打印一次系统和 LUA 的内存信息:memory_check()
|
||||||
|
- 注册excloud回调:on_excloud_event()
|
||||||
|
- 配置excloud链接,启动心跳包:excloud_task_func()
|
||||||
|
- 照片上传任务函数:upload_image_fun()
|
||||||
|
- 配置摄像头信息表:spi_camera_param
|
||||||
|
- 初始化摄像头:excamera.open()
|
||||||
|
- 执行拍照:excamera.photo()
|
||||||
|
- 上传照片:httpplus.request()
|
||||||
|
- 关闭摄像头:excamera.close()
|
||||||
|
|
||||||
|
|
||||||
|
## 演示硬件环境
|
||||||
|
|
||||||
|
1、Air780EPM 开发板一块
|
||||||
|
|
||||||
|
2、TYPE-C USB 数据线一根
|
||||||
|
|
||||||
|
3、合宙标准配件 AirCAMERA_1050 一个
|
||||||
|
|
||||||
|
4、Air780EPM 开发板和合宙标准配件 AirCAMERA_1050 的硬件接线方式为
|
||||||
|
|
||||||
|
Air780EPM 开发板通过 TYPE-C USB 口供电;(侧面拨码拨至USB供电)
|
||||||
|
|
||||||
|
TYPE-C USB 数据线直接插到开发板的 TYPE-C USB 座子,另外一端连接电脑 USB 口;
|
||||||
|
|
||||||
|
AirCAMERA_1050 配件板插入Air780EPM 开发板的SPI摄像头座子中
|
||||||
|
|
||||||
|
## 演示软件环境
|
||||||
|
|
||||||
|
1、Luatools 下载调试工具:[https://docs.openluat.com/air780epm/common/Luatools/](https://docs.openluat.com/air780epm/common/Luatools/)
|
||||||
|
|
||||||
|
2、固件版本:LuatOS-SoC_V2018_Air780EPM_1,固件地址,如有最新固件请用最新 https://docs.openluat.com/air780epm/luatos/firmware/version/
|
||||||
|
|
||||||
|
|
||||||
|
## 演示核心步骤
|
||||||
|
|
||||||
|
1、搭建硬件环境;
|
||||||
|
|
||||||
|
2、烧录 DEMO 代码;
|
||||||
|
|
||||||
|
3、等待自动拍照完成后上传平台,LUATOOLS会有如下打印;
|
||||||
|
```lua
|
||||||
|
[2026-04-08 17:36:12.996][000000000.205] I/user.main AirCAMERA_1040_Demo 001.999.000
|
||||||
|
[2026-04-08 17:36:12.999][000000000.325] W/user.excloud_task_func wait IP_READY 1 1
|
||||||
|
[2026-04-08 17:36:13.002][000000000.326] I/user.exmux 开发板 DEV_BOARD_780_V1.2 初始化成功
|
||||||
|
[2026-04-08 17:36:13.504][000000001.326] W/user.excloud_task_func wait IP_READY 1 1
|
||||||
|
[2026-04-08 17:36:14.408][000000002.166] I/mobile sim0 sms ready
|
||||||
|
[2026-04-08 17:36:14.412][000000002.167] D/mobile cid1, state0
|
||||||
|
[2026-04-08 17:36:14.423][000000002.168] D/mobile bearer act 0, result 0
|
||||||
|
[2026-04-08 17:36:14.430][000000002.168] D/mobile NETIF_LINK_ON -> IP_READY
|
||||||
|
[2026-04-08 17:36:14.438][000000002.169] I/user.netdrv_4g.ip_ready_func IP_READY 10.122.36.125 255.255.255.255 0.0.0.0 nil
|
||||||
|
[2026-04-08 17:36:14.445][000000002.173] I/user.[excloud]4G设备 IMEI: 867920071472378 MUID: 20250604131416A755490A2989432885
|
||||||
|
[2026-04-08 17:36:14.451][000000002.189] I/user.exmtn 读取索引 1
|
||||||
|
[2026-04-08 17:36:14.457][000000002.189] I/user.exmtn 读取块数配置 2
|
||||||
|
[2026-04-08 17:36:14.464][000000002.190] I/user.exmtn 读取写入方式配置 0
|
||||||
|
[2026-04-08 17:36:14.468][000000002.190] I/user.exmtn 配置变化 false
|
||||||
|
[2026-04-08 17:36:14.473][000000002.193] I/user.exmtn 配置未变化,文件存在,继续写入
|
||||||
|
[2026-04-08 17:36:14.479][000000002.197] I/user.exmtn 初始化成功: 每个文件 8.00 KB (2 块 × 4096 字节), 总空间 32.00 KB (4 个文件)
|
||||||
|
[2026-04-08 17:36:14.484][000000002.197] I/user.[excloud]运维日志初始化成功
|
||||||
|
[2026-04-08 17:36:14.488][000000002.198] I/user.[excloud]excloud.setup 初始化成功 设备ID: 867920071472378
|
||||||
|
[2026-04-08 17:36:14.494][000000002.198] I/user.excloud初始化成功
|
||||||
|
[2026-04-08 17:36:14.499][000000002.198] I/user.[excloud]首次连接,获取服务器信息...
|
||||||
|
[2026-04-08 17:36:14.505][000000002.199] I/user.[excloud]excloud.getip 类型: 3 key: sh5g0OTP7ThOSlGKmE5jiEMbOBqQWyw9-867920071472378
|
||||||
|
[2026-04-08 17:36:14.512][000000002.205] D/socket connect to gps.openluat.com,443
|
||||||
|
[2026-04-08 17:36:14.516][000000002.209] dns_run 676:gps.openluat.com state 0 id 1 ipv6 0 use dns server2, try 0
|
||||||
|
[2026-04-08 17:36:14.520][000000002.231] D/mobile TIME_SYNC 0 tm 1775640975
|
||||||
|
[2026-04-08 17:36:14.526][000000002.273] dns_run 693:dns all done ,now stop
|
||||||
|
[2026-04-08 17:36:15.179][000000003.008] I/user.httpplus 服务器已完成响应,开始解析响应
|
||||||
|
[2026-04-08 17:36:15.211][000000003.037] I/user.[excloud]excloud.getip响应 HTTP Code: 200 Body:
|
||||||
|
[2026-04-08 17:36:15.218][000000003.037] {"msg":"ok","conninfo":{"ipv4":"124.71.128.165","port":9108},"imginfo":{"url":"https://gps.openluat.com/aircloud/air_up/image","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"audinfo":{"url":"https://gps.openluat.com/aircloud/air_up/audio","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"mtninfo":{"url":"https://gps.openluat.com/aircloud/air_up/file","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"qrinfo":{"url":"https://gps.openluat.com/#/redirect?key=_5oruyMsMk5Ny5ZajRyBqaZEqqaPjVSb93qH"}}
|
||||||
|
[2026-04-08 17:36:15.225][000000003.038] I/user.[excloud]excloud.getip响应 HTTP Code: 200 Body:
|
||||||
|
[2026-04-08 17:36:15.231][000000003.038] {"msg":"ok","conninfo":{"ipv4":"124.71.128.165","port":9108},"imginfo":{"url":"https://gps.openluat.com/aircloud/air_up/image","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"audinfo":{"url":"https://gps.openluat.com/aircloud/air_up/audio","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"mtninfo":{"url":"https://gps.openluat.com/aircloud/air_up/file","data_key":"f","data_param":{"key":"8bcWhwHK4pZR7gTbvPUdxL1TAbW5H3C65MFcC","tip":""}},"qrinfo":{"url":"https://gps.openluat.com/#/redirect?key=_5oruyMsMk5Ny5ZajRyBqaZEqqaPjVSb93qH"}}
|
||||||
|
[2026-04-08 17:36:15.237][000000003.039] I/user.[excloud]获取到TCP/UDP连接信息 host: 124.71.128.165 port: 9108 key: nil
|
||||||
|
[2026-04-08 17:36:15.242][000000003.039] I/user.[excloud]获取到图片上传信息
|
||||||
|
[2026-04-08 17:36:15.247][000000003.040] I/user.[excloud]获取到音频上传信息
|
||||||
|
[2026-04-08 17:36:15.255][000000003.040] I/user.[excloud]获取到运维日志上传信息
|
||||||
|
[2026-04-08 17:36:15.262][000000003.040] I/user.[excloud]获取到二维码信息
|
||||||
|
[2026-04-08 17:36:15.266][000000003.041] I/user.[excloud]excloud.getip 更新配置: 124.71.128.165 9108
|
||||||
|
[2026-04-08 17:36:15.271][000000003.041] I/user.[excloud]excloud.getip 成功: true 结果: {"ipv4":"124.71.128.165","port":9108}
|
||||||
|
[2026-04-08 17:36:15.276][000000003.042] I/user.[excloud]服务器信息获取成功 host: 124.71.128.165 port: 9108 transport: tcp
|
||||||
|
[2026-04-08 17:36:15.280][000000003.042] I/user.[excloud]创建TCP连接
|
||||||
|
[2026-04-08 17:36:15.286][000000003.043] D/socket connect to 124.71.128.165,9108
|
||||||
|
[2026-04-08 17:36:15.291][000000003.044] network_socket_connect 1610:network 1-0 local port auto select 51002
|
||||||
|
[2026-04-08 17:36:15.295][000000003.045] I/user.[excloud]TCP连接结果 true false
|
||||||
|
[2026-04-08 17:36:15.301][000000003.046] I/user.[excloud]excloud service started
|
||||||
|
[2026-04-08 17:36:15.306][000000003.046] I/user.excloud服务已开启
|
||||||
|
[2026-04-08 17:36:15.311][000000003.047] I/user.[excloud]excloud 自动心跳已启动,间隔 300 秒
|
||||||
|
[2026-04-08 17:36:15.315][000000003.047] I/user.自动心跳已启动
|
||||||
|
[2026-04-08 17:36:15.323][000000003.127] network_default_socket_callback 1123:before process socket 1,event:0xf2000009(连接成功),state:3(正在连接),wait:2(等待连接完成)
|
||||||
|
[2026-04-08 17:36:15.328][000000003.127] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:15.332][000000003.128] I/user.[excloud]socket cb userdata: 0C1843F0 33554449 0
|
||||||
|
[2026-04-08 17:36:15.337][000000003.129] I/user.[excloud]socket TCP连接成功
|
||||||
|
[2026-04-08 17:36:15.342][000000003.129] I/user.用户回调函数 connect_result {"success":true}
|
||||||
|
[2026-04-08 17:36:15.346][000000003.129] I/user.连接成功
|
||||||
|
[2026-04-08 17:36:15.352][000000003.133] I/user.[excloud]构建发送数据 16 3 sh5g0OTP7ThOSlGKmE5jiEMbOBqQWyw9-867920071472378-20250604131416A755490A2989432885
|
||||||
|
[2026-04-08 17:36:15.357][000000003.134] I/user.[excloud]tlv发送数据长度4 85
|
||||||
|
[2026-04-08 17:36:15.362][000000003.135] I/user.[excloud]构建消息头 y r7
|
||||||
|
[2026-04-08 17:36:15.371][000000003.137] I/user.用户回调函数 send_result {"sequence_num":1,"success":true,"error_msg":"Send successful"}
|
||||||
|
[2026-04-08 17:36:15.376][000000003.143] I/user.[excloud]数据发送成功 101 字节
|
||||||
|
[2026-04-08 17:36:15.385][000000003.207] network_default_socket_callback 1123:before process socket 1,event:0xf2000004(发送成功),state:5(在线),wait:3(等待发送完成)
|
||||||
|
[2026-04-08 17:36:15.390][000000003.207] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:15.395][000000003.208] I/user.[excloud]socket cb userdata: 0C1843F0 33554450 0
|
||||||
|
[2026-04-08 17:36:15.403][000000003.208] I/user.[excloud]socket 发送完成
|
||||||
|
[2026-04-08 17:36:15.491][000000003.327] I/user.sys ram 2375920 80156 121112
|
||||||
|
[2026-04-08 17:36:15.496][000000003.328] I/user.lua ram 1048568 174392 190984
|
||||||
|
[2026-04-08 17:36:18.498][000000006.328] I/user.sys ram 2375920 80156 121112
|
||||||
|
[2026-04-08 17:36:18.531][000000006.329] I/user.lua ram 1048568 174712 190984
|
||||||
|
[2026-04-08 17:36:21.500][000000009.329] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:21.518][000000009.330] I/user.lua ram 1048568 175240 190984
|
||||||
|
[2026-04-08 17:36:24.496][000000012.330] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:24.501][000000012.331] I/user.lua ram 1048568 175440 190984
|
||||||
|
[2026-04-08 17:36:27.508][000000015.331] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:27.512][000000015.332] I/user.lua ram 1048568 175632 190984
|
||||||
|
[2026-04-08 17:36:30.505][000000018.332] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:30.511][000000018.333] I/user.lua ram 1048568 175832 190984
|
||||||
|
[2026-04-08 17:36:33.503][000000021.333] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:33.510][000000021.334] I/user.lua ram 1048568 176024 190984
|
||||||
|
[2026-04-08 17:36:36.506][000000024.334] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:36.510][000000024.335] I/user.lua ram 1048568 176216 190984
|
||||||
|
[2026-04-08 17:36:39.512][000000027.335] I/user.sys ram 2375920 71760 121112
|
||||||
|
[2026-04-08 17:36:39.524][000000027.336] I/user.lua ram 1048568 176416 190984
|
||||||
|
[2026-04-08 17:36:42.504][000000030.327] I/user.exmux 设置引脚 pwr2 (23) 为高电平
|
||||||
|
[2026-04-08 17:36:42.510][000000030.328] I/user.exmux 设置引脚 pwr1 (2) 为高电平
|
||||||
|
[2026-04-08 17:36:42.513][000000030.328] I/user.exmux 分组 i2c1 打开成功
|
||||||
|
[2026-04-08 17:36:42.517][000000030.329] I2C_MasterSetup 426:I2C1, Total 65 HCNT 22 LCNT 40
|
||||||
|
[2026-04-08 17:36:42.522][000000030.329] CSPI_Setup 1924:APB MP 102400000
|
||||||
|
[2026-04-08 17:36:42.551][000000030.388] I/user.初始化状态 true
|
||||||
|
[2026-04-08 17:36:42.558][000000030.388] CSPI_Rx 2022:block len 7680, total block 80
|
||||||
|
[2026-04-08 17:36:42.561][000000030.389] I/user.照片存储路径 /ram/test.jpg
|
||||||
|
[2026-04-08 17:36:42.564][000000030.389] luat_camera_capture_config 700:0,0,0,0
|
||||||
|
[2026-04-08 17:36:42.568][000000030.389] luat_camera_capture 676:save file in /ram/test.jpg
|
||||||
|
[2026-04-08 17:36:42.572][000000030.391] I/user.sys ram 2375920 696088 696224
|
||||||
|
[2026-04-08 17:36:42.575][000000030.391] I/user.lua ram 1048568 178544 190984
|
||||||
|
[2026-04-08 17:36:43.126][000000030.955] I/user.摄像头数据 58612
|
||||||
|
[2026-04-08 17:36:43.138][000000030.956] I/user.拍照完成
|
||||||
|
[2026-04-08 17:36:43.144][000000030.956] I/user.开始上传图片
|
||||||
|
[2026-04-08 17:36:43.149][000000030.957] I/user.[excloud]开始文件上传 类型: 1 文件: /ram/test.jpg 大小: 58612
|
||||||
|
[2026-04-08 17:36:43.155][000000030.957] I/user.[excloud]开始文件上传 类型: 1 文件: test.jpg 大小: 58612
|
||||||
|
[2026-04-08 17:36:43.160][000000030.958] I/user.[excloud]构建发送数据 23 0 0
|
||||||
|
[2026-04-08 17:36:43.164][000000030.959] I/user.[excloud]构建发送数据 784 0 1
|
||||||
|
[2026-04-08 17:36:43.169][000000030.960] I/user.[excloud]构建发送数据 785 3 test.jpg
|
||||||
|
[2026-04-08 17:36:43.172][000000030.961] I/user.[excloud]构建发送数据 786 0 58612
|
||||||
|
[2026-04-08 17:36:43.177][000000030.963] I/user.[excloud]tlv发送数据长度4 36
|
||||||
|
[2026-04-08 17:36:43.182][000000030.964] I/user.[excloud]构建消息头 y r7
|
||||||
|
[2026-04-08 17:36:43.185][000000030.968] I/user.用户回调函数 send_result {"sequence_num":2,"success":true,"error_msg":"Send successful"}
|
||||||
|
[2026-04-08 17:36:43.189][000000030.973] I/user.[excloud]数据发送成功 52 字节
|
||||||
|
[2026-04-08 17:36:43.195][000000030.985] I/user.[excloud]开始发送HTTP请求 URL: https://gps.openluat.com/aircloud/air_up/image
|
||||||
|
[2026-04-08 17:36:43.199][000000030.989] dns_run 676:gps.openluat.com state 0 id 2 ipv6 0 use dns server2, try 0
|
||||||
|
[2026-04-08 17:36:43.298][000000031.126] dns_run 693:dns all done ,now stop
|
||||||
|
[2026-04-08 17:36:43.304][000000031.135] network_default_socket_callback 1123:before process socket 1,event:0xf2000004(发送成功),state:5(在线),wait:3(等待发送完成)
|
||||||
|
[2026-04-08 17:36:43.308][000000031.135] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:43.312][000000031.136] I/user.[excloud]socket cb userdata: 0C1843F0 33554450 0
|
||||||
|
[2026-04-08 17:36:43.318][000000031.137] I/user.[excloud]socket 发送完成
|
||||||
|
[2026-04-08 17:36:45.565][000000033.392] I/user.sys ram 2375920 876224 1064884
|
||||||
|
[2026-04-08 17:36:45.570][000000033.393] I/user.lua ram 1048568 353216 469512
|
||||||
|
[2026-04-08 17:36:46.436][000000034.268] I/http http close c267f50
|
||||||
|
[2026-04-08 17:36:46.441][000000034.270] I/user.[excloud]excloud.getip文件上传响应 HTTP Code: 200 Body: {"info":"aircloud./aircloud/air_up/image","code":0,"trace":"code:aircloud./aircloud/air_up/image, trcace:","log":"^^^","value":{"uri":"/vsa/aircloud_image/FFZDbqsuzrLpbgPfzVd7De/2026-04/867920071472378/20260408173647_test.jpg","size":"57.00KB","thumb":"/vsa/aircloud_image/FFZDbqsuzrLpbgPfzVd7De/2026-04/867920071472378/20260408173647_testt.jpg"}}
|
||||||
|
[2026-04-08 17:36:46.446][000000034.271] I/user.[excloud]文件上传成功 URL: /vsa/aircloud_image/FFZDbqsuzrLpbgPfzVd7De/2026-04/867920071472378/20260408173647_test.jpg
|
||||||
|
[2026-04-08 17:36:46.450][000000034.271] I/user.[excloud]构建发送数据 24 0 0
|
||||||
|
[2026-04-08 17:36:46.457][000000034.274] I/user.[excloud]构建发送数据 784 0 1
|
||||||
|
[2026-04-08 17:36:46.461][000000034.276] I/user.[excloud]构建发送数据 785 3 test.jpg
|
||||||
|
[2026-04-08 17:36:46.466][000000034.277] I/user.[excloud]构建发送数据 787 0 0
|
||||||
|
[2026-04-08 17:36:46.470][000000034.278] I/user.[excloud]tlv发送数据长度4 36
|
||||||
|
[2026-04-08 17:36:46.475][000000034.279] I/user.[excloud]构建消息头 y r7
|
||||||
|
[2026-04-08 17:36:46.479][000000034.282] I/user.用户回调函数 send_result {"sequence_num":3,"success":true,"error_msg":"Send successful"}
|
||||||
|
[2026-04-08 17:36:46.486][000000034.287] I/user.[excloud]数据发送成功 52 字节
|
||||||
|
[2026-04-08 17:36:46.491][000000034.287] I/user.图片上传成功
|
||||||
|
[2026-04-08 17:36:46.498][000000034.288] I/user.exmux 设置引脚 pwr2 (23) 为低电平
|
||||||
|
[2026-04-08 17:36:46.502][000000034.289] I/user.exmux 设置引脚 pwr1 (2) 为低电平
|
||||||
|
[2026-04-08 17:36:46.507][000000034.289] I/user.exmux 分组 i2c1 关闭成功
|
||||||
|
[2026-04-08 17:36:46.512][000000034.347] network_default_socket_callback 1123:before process socket 1,event:0xf2000004(发送成功),state:5(在线),wait:3(等待发送完成)
|
||||||
|
[2026-04-08 17:36:46.519][000000034.347] network_default_socket_callback 1127:after process socket 1,state:5(在线),wait:0(无等待)
|
||||||
|
[2026-04-08 17:36:46.524][000000034.348] I/user.[excloud]socket cb userdata: 0C1843F0 33554450 0
|
||||||
|
[2026-04-08 17:36:46.529][000000034.349] I/user.[excloud]socket 发送完成
|
||||||
|
```
|
||||||
|
4、等待自动扫描任务完成后,LUATOOLS会有如下打印;
|
||||||
|
```lua
|
||||||
|
[2025-11-21 15:19:17.310][000000000.269] I2C_MasterSetup 426:I2C1, Total 65 HCNT 22 LCNT 40
|
||||||
|
[2025-11-21 15:19:17.313][000000000.332] I/user.初始化状态 true
|
||||||
|
[2025-11-21 15:19:17.316][000000000.332] CSPI_Rx 2000:block len 7680, total block 40
|
||||||
|
[2025-11-21 15:19:17.319][000000000.541] I/user.扫码结果 Air780EPM
|
||||||
|
[2025-11-21 15:19:17.323][000000000.542] I/user.扫描完成,扫描结果为: Air780EPM
|
||||||
|
[2025-11-21 15:19:17.327][000000000.542] I/user.Scan result : Air780EPM
|
||||||
|
```
|
||||||
|
|
||||||
|
5、登录 https://iot.luatos.com/ 查看拍摄的照片;
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
--[[
|
||||||
|
@module scan_code
|
||||||
|
@summary AirCAMERA_1050 gc0310摄像头扫描二维码应用模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.11.09
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1050 gc0310摄像头完成一次扫描二维码任务
|
||||||
|
]] --
|
||||||
|
-- 摄像头扩展库模块
|
||||||
|
-- 功能:提供摄像头初始化、扫描和资源管理功能
|
||||||
|
-- 引入excamera扩展库模块
|
||||||
|
local excamera = require "excamera"
|
||||||
|
-- 引入exmux扩展库模块
|
||||||
|
local exmux = require "exmux"
|
||||||
|
|
||||||
|
-- 硬件I2C/SPI配置,当您使用合宙开发板时,请根据具体的开发板版本选择对应的变量,
|
||||||
|
-- exmux库将会自动处理开发板上的I2C/SPI外设,确保总线通讯正常
|
||||||
|
-- 当您使用自己的制作的板子,请参考exmux库的文档,配置对应的变量:https://docs.openluat.com/osapi/ext/exmux/
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_8000_V2.0"
|
||||||
|
local HARDWARE_ENV = "DEV_BOARD_780_V1.2"
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_780_V1.3"
|
||||||
|
|
||||||
|
-- 扫描功能函数
|
||||||
|
-- 作用:循环监听扫描事件,执行摄像头初始化、扫描和资源释放
|
||||||
|
local function scan_code_func()
|
||||||
|
-- 定义变量用于存储操作结果和数据
|
||||||
|
local result, data
|
||||||
|
-- 初始化外设分组开关状态
|
||||||
|
exmux.setup(HARDWARE_ENV)
|
||||||
|
-- 无限循环,持续等待扫描事件
|
||||||
|
while true do
|
||||||
|
-- 配置gc0310摄像头参数表
|
||||||
|
local spi_camera_param = {
|
||||||
|
id = "gc0310", -- SPI摄像头仅支持"gc032a"、"gc0310"、"bf30a2",请带引号填写
|
||||||
|
i2c_id = 1, -- 模块上使用的I2C编号
|
||||||
|
work_mode = 1, -- 工作模式,0为拍照模式,1为扫描模式
|
||||||
|
save_path = nil, -- 扫描结果为字符串返回,使用变量赋值既可
|
||||||
|
camera_pwr = 2, -- 摄像头使能管脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_pwdn = 5, -- 摄像头pwdn开关脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_light = nil -- 摄像头补光灯控制管脚,填写GPIO号即可,无则填nil
|
||||||
|
}
|
||||||
|
-- 等待外部触发扫描事件(SCAN_CODE)
|
||||||
|
sys.waitUntil("SCAN_CODE")
|
||||||
|
-- 打开外设分组
|
||||||
|
exmux.open("i2c1")
|
||||||
|
-- 初始化摄像头,传入配置参数
|
||||||
|
result = excamera.open(spi_camera_param)
|
||||||
|
-- 记录摄像头初始化状态
|
||||||
|
log.info("初始化状态", result)
|
||||||
|
-- 判断摄像头初始化是否成功,不成功则直接关闭,成功则启动扫描
|
||||||
|
if result then
|
||||||
|
-- 执行扫描操作,5秒超时
|
||||||
|
result, data = excamera.scan(5000)
|
||||||
|
-- 扫描执行完成则上传,否则关闭摄像头
|
||||||
|
if result then
|
||||||
|
log.info("Scan result :", data )
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- 关闭摄像头,释放资源
|
||||||
|
excamera.close()
|
||||||
|
-- 关闭外设分组
|
||||||
|
exmux.close("i2c1")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 内存检查函数
|
||||||
|
-- 作用:定期监控系统内存使用情况
|
||||||
|
local function memory_check()
|
||||||
|
-- 无限循环,定期检查内存
|
||||||
|
while true do
|
||||||
|
-- 等待3秒
|
||||||
|
sys.wait(3000)
|
||||||
|
-- 打印系统内存使用信息
|
||||||
|
log.info("sys ram", rtos.meminfo("sys"))
|
||||||
|
-- 打印Lua虚拟机内存使用信息
|
||||||
|
log.info("lua ram", rtos.meminfo("lua"))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- AirCAMERA_1050 DEMO应用触发函数,每30S触发一次扫描
|
||||||
|
local function AirCAMERA_1050_func()
|
||||||
|
while true do
|
||||||
|
sys.publish("SCAN_CODE")
|
||||||
|
sys.wait(30000)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 创建扫描功能任务
|
||||||
|
-- 作用:在单独的任务中运行扫描逻辑
|
||||||
|
sys.taskInit(scan_code_func)
|
||||||
|
|
||||||
|
-- 创建内存监控任务
|
||||||
|
-- 作用:在单独的任务中运行内存监控逻辑
|
||||||
|
sys.taskInit(memory_check)
|
||||||
|
|
||||||
|
-- 创建扫描触发任务
|
||||||
|
-- 作用:每30秒触发一次扫描二维码业务
|
||||||
|
sys.taskInit(AirCAMERA_1050_func)
|
||||||
+142
@@ -0,0 +1,142 @@
|
|||||||
|
--[[
|
||||||
|
@module take_photo_http_post
|
||||||
|
@summary AirCAMERA_1050 gc0310摄像头拍照上传应用模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.11.09
|
||||||
|
@author 陈取德
|
||||||
|
@usage
|
||||||
|
本demo主要使用AirCAMERA_1050 gc0310摄像头完成一次拍照上传任务
|
||||||
|
]] -- 摄像头拍照模块
|
||||||
|
-- 功能:提供摄像头初始化、拍照和资源管理功能
|
||||||
|
-- 引入excamera扩展库模块
|
||||||
|
local excamera = require "excamera"
|
||||||
|
-- 引入httpplus扩展库模块
|
||||||
|
local httpplus = require "httpplus"
|
||||||
|
-- 引入exmux扩展库模块
|
||||||
|
local exmux = require "exmux"
|
||||||
|
|
||||||
|
-- 硬件I2C/SPI配置,当您使用合宙开发板时,请根据具体的开发板版本选择对应的变量,
|
||||||
|
-- exmux库将会自动处理开发板上的I2C/SPI外设,确保总线通讯正常
|
||||||
|
-- 当您使用自己的制作的板子,请参考exmux库的文档,配置对应的变量:https://docs.openluat.com/osapi/ext/exmux/
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_8000_V2.0"
|
||||||
|
local HARDWARE_ENV = "DEV_BOARD_780_V1.2"
|
||||||
|
-- local HARDWARE_ENV = "DEV_BOARD_780_V1.3"
|
||||||
|
|
||||||
|
-- 定义照片保存方式,有三种类型:
|
||||||
|
-- 1、ZBUFF保存,输入"ZBUFF"即可,excamera库会自动处理ZBUFF
|
||||||
|
-- 2、保存到内存文件系统中,路径名需指向/ram/文件夹
|
||||||
|
-- 3、保存到内置FLASH文件系统中
|
||||||
|
-- 选择其中一个即可,注释另两个路径变量
|
||||||
|
local save_method = "ZBUFF"
|
||||||
|
-- local save_method = "/ram/test.jpg"
|
||||||
|
-- local save_method = "/test.jpg"
|
||||||
|
|
||||||
|
-- 拍照功能函数
|
||||||
|
-- 作用:循环监听拍照事件,执行摄像头初始化、拍照和资源释放
|
||||||
|
local function capture_func()
|
||||||
|
-- 定义变量用于存储操作结果和数据
|
||||||
|
local result, data
|
||||||
|
-- 初始化外设分组开关状态
|
||||||
|
exmux.setup(HARDWARE_ENV)
|
||||||
|
-- 无限循环,持续等待拍照事件
|
||||||
|
while true do
|
||||||
|
-- 配置gc0310摄像头参数表
|
||||||
|
local spi_camera_param = {
|
||||||
|
id = "gc0310", -- SPI摄像头仅支持"gc032a"、"gc0310"、"bf30a2",请带引号填写
|
||||||
|
i2c_id = 1, -- 模块上使用的I2C编号
|
||||||
|
work_mode = 0, -- 工作模式,0为拍照模式,1为扫描模式
|
||||||
|
save_path = save_method, -- 拍照结果存储路径,可用"ZBUFF"交由excamera库内部管理
|
||||||
|
camera_pwr = 2, -- 摄像头使能管脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_pwdn = 5, -- 摄像头pwdn开关脚,填写GPIO号即可,无则填nil
|
||||||
|
camera_light = nil -- 摄像头补光灯控制管脚,填写GPIO号即可,无则填nil
|
||||||
|
}
|
||||||
|
-- 等待外部触发拍照事件(ONCE_CAPTURE)
|
||||||
|
sys.waitUntil("ONCE_CAPTURE")
|
||||||
|
-- 打开外设分组
|
||||||
|
exmux.open("i2c1")
|
||||||
|
-- 初始化摄像头,传入配置参数
|
||||||
|
result = excamera.open(spi_camera_param)
|
||||||
|
-- 记录摄像头初始化状态
|
||||||
|
log.info("初始化状态", result)
|
||||||
|
-- 判断摄像头初始化是否成功,不成功则直接关闭,成功则启动拍照
|
||||||
|
if result then
|
||||||
|
-- 执行拍照操作
|
||||||
|
result, data = excamera.photo()
|
||||||
|
-- 拍照执行完成则上传,否则关闭摄像头
|
||||||
|
if result then
|
||||||
|
-- 通过网卡状态判断WIFI是否连接成功,WIFI连接成功后再运行照片上传任务。
|
||||||
|
while not socket.adapter(socket.dft()) do
|
||||||
|
-- 在此处阻塞等待WIFI连接成功的消息"IP_READY",避免联网过快,丢失了"IP_READY"信息而导致一直被卡住。
|
||||||
|
-- 或者等待30秒超时退出阻塞等待状态
|
||||||
|
log.warn("tcp_client_main_task_func", "wait IP_READY")
|
||||||
|
sys.waitUntil("IP_READY", 30000)
|
||||||
|
end
|
||||||
|
if type(data) == "userdata" then
|
||||||
|
data = data:query()
|
||||||
|
else
|
||||||
|
data = io.readFile(data)
|
||||||
|
end
|
||||||
|
-- 通过网卡(本demo使用的是socket.LWIP_STA网卡)将拍摄到的照片数据result上传到服务器air32.cn
|
||||||
|
-- 如果上传成功,电脑上浏览器打开https://uploadtest.luatos.com/upload/jpg/,打开对应的测试日期目录,点击具体的测试时间照片,可以查看摄像头拍照上传的照片
|
||||||
|
-- 执行httpplus.request后,等待服务器的http应答,此处会阻塞当前task,等待整个过程成功结束或者出现错误异常结束
|
||||||
|
-- code表示结果,number类型,详细说明参考API手册,一般来说:
|
||||||
|
-- 200表示成功
|
||||||
|
-- 小于0的值表示出错,例如-8表示超时错误
|
||||||
|
-- 其余结果值参考API手册
|
||||||
|
-- 因为Air32.com平台已经不开放使用了,所以该DEMO仅作上传照片至服务器的演示作用,使用时请将上传URL修改为您自己的服务器地址
|
||||||
|
-- 或者通过excloud扩展库上传到合宙IOT平台uploadtest.luatos.com,详见:photo_to_aircloud.lua
|
||||||
|
local code = httpplus.request({
|
||||||
|
url = "http://uploadtest.luatos.com/api/upload/jpg",
|
||||||
|
method = "POST",
|
||||||
|
body = data
|
||||||
|
})
|
||||||
|
-- 打印http传输状态
|
||||||
|
log.info("http_upload_photo_task_func", "httpplus.request", code)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
-- 判断是否ZBUFF存储方式,如果是文件系统保存则删除本地文件
|
||||||
|
if save_method ~= "ZBUFF" then
|
||||||
|
os.remove(spi_camera_param.save_path)
|
||||||
|
end
|
||||||
|
-- 关闭摄像头,释放资源
|
||||||
|
-- 使用ZBUFF存储方式时,close传入true后,excamera内部创建的ZBUFF会缩减至0字节,放出内存但是不释放ZBUFF,便于下次拍照时调用;
|
||||||
|
-- 重复申请和释放ZBUFF会导致垃圾内存堆积,影响系统内存;
|
||||||
|
excamera.close(true)
|
||||||
|
-- 关闭外设分组
|
||||||
|
exmux.close("i2c1")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 内存检查函数
|
||||||
|
-- 作用:定期监控系统内存使用情况
|
||||||
|
local function memory_check()
|
||||||
|
-- 无限循环,定期检查内存
|
||||||
|
while true do
|
||||||
|
-- 等待3秒
|
||||||
|
sys.wait(3000)
|
||||||
|
-- 打印系统内存使用信息
|
||||||
|
log.info("sys ram", rtos.meminfo("sys"))
|
||||||
|
-- 打印Lua虚拟机内存使用信息
|
||||||
|
log.info("lua ram", rtos.meminfo("lua"))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- AirCAMERA_1050 DEMO应用触发函数,每30S触发一次拍照
|
||||||
|
local function AirCAMERA_1050_func()
|
||||||
|
while true do
|
||||||
|
sys.publish("ONCE_CAPTURE")
|
||||||
|
sys.wait(30000)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 创建拍照功能任务
|
||||||
|
-- 作用:在单独的任务中运行拍照逻辑
|
||||||
|
sys.taskInit(capture_func)
|
||||||
|
|
||||||
|
-- 创建内存监控任务
|
||||||
|
-- 作用:在单独的任务中运行内存监控逻辑
|
||||||
|
sys.taskInit(memory_check)
|
||||||
|
|
||||||
|
-- 创建拍照触发任务
|
||||||
|
-- 作用:每30秒触发一次拍照上传业务
|
||||||
|
sys.taskInit(AirCAMERA_1050_func)
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
--[[
|
||||||
|
@module http_app
|
||||||
|
@summary http应用功能模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.09.17
|
||||||
|
@author 王城钧
|
||||||
|
@usage
|
||||||
|
本文件为http应用功能模块,核心业务逻辑为:基于不同的应用场景,演示http核心库的使用方式;
|
||||||
|
本文件没有对外接口,直接在main.lua中require "http_app"就可以加载运行;
|
||||||
|
]]
|
||||||
|
|
||||||
|
-- 普通的http get请求功能演示
|
||||||
|
-- 请求的body数据保存到内存变量中,在内存够用的情况下,最大支持32KB的数据存储到内存中
|
||||||
|
-- timeout可以设置超时时间
|
||||||
|
-- callback可以设置回调函数,可用于实时检测body数据的下载进度
|
||||||
|
local function http_app_get()
|
||||||
|
-- https get请求https://httpbin.luatos.com/get网页内容
|
||||||
|
-- 如果请求成功,请求的数据保存到body中
|
||||||
|
local code, headers, body = http.request("GET", "https://httpbin.luatos.com/get").wait()
|
||||||
|
log.info("http_app_get1",
|
||||||
|
code == 200 and "success" or "error",
|
||||||
|
code,
|
||||||
|
json.encode(headers or {}),
|
||||||
|
body and (body:len() > 512 and body:len() or body) or "nil")
|
||||||
|
|
||||||
|
-- https get请求https://www.luatos.com/网页内容,超时时间为10秒
|
||||||
|
-- 请求超时时间为10秒,用户自己写代码时,不要照抄10秒,根据自己业务逻辑的需要设置合适的超时时间
|
||||||
|
-- 回调函数为http_cbfunc,回调函数使用的第三个回调参数为"http_app_get2"
|
||||||
|
-- 如果请求成功,请求的数据保存到body中
|
||||||
|
code, headers, body = http.request("GET", "https://www.luatos.com/", nil, nil,
|
||||||
|
{ timeout = 10000, userdata = "http_app_get2", callback = http_cbfunc }).wait()
|
||||||
|
log.info("http_app_get2",
|
||||||
|
code == 200 and "success" or "error",
|
||||||
|
code,
|
||||||
|
json.encode(headers or {}),
|
||||||
|
body and (body:len() > 512 and body:len() or body) or "nil")
|
||||||
|
|
||||||
|
-- http get请求http://httpbin.luatos.com/get网页内容,超时时间为3秒
|
||||||
|
-- 请求超时时间为3秒,用户自己写代码时,不要照抄3秒,根据自己业务逻辑的需要设置合适的超时时间
|
||||||
|
-- 回调函数为http_cbfunc,回调函数使用的第三个回调参数为"http_app_get3"
|
||||||
|
-- 如果请求成功,请求的数据保存到body中
|
||||||
|
code, headers, body = http.request("GET", "http://httpbin.luatos.com/get", nil, nil,
|
||||||
|
{ timeout = 3000, userdata = "http_app_get3", callback = http_cbfunc }).wait()
|
||||||
|
log.info("http_app_get3",
|
||||||
|
code == 200 and "success" or "error",
|
||||||
|
code,
|
||||||
|
json.encode(headers or {}),
|
||||||
|
body and (body:len() > 512 and body:len() or body) or "nil")
|
||||||
|
end
|
||||||
|
|
||||||
|
-- http app task 的任务处理函数
|
||||||
|
local function http_app_task_func()
|
||||||
|
while true do
|
||||||
|
-- 如果当前时间点设置的默认网卡还没有连接成功,一直在这里循环等待
|
||||||
|
while not socket.adapter(socket.dft()) do
|
||||||
|
log.warn("http_app_task_func", "wait IP_READY", socket.dft())
|
||||||
|
-- 在此处阻塞等待默认网卡连接成功的消息"IP_READY"
|
||||||
|
-- 或者等待1秒超时退出阻塞等待状态;
|
||||||
|
-- 注意:此处的1000毫秒超时不要修改的更长;
|
||||||
|
-- 因为当使用exnetif.set_priority_order配置多个网卡连接外网的优先级时,会隐式的修改默认使用的网卡
|
||||||
|
-- 当exnetif.set_priority_order的调用时序和此处的socket.adapter(socket.dft())判断时序有可能不匹配
|
||||||
|
-- 此处的1秒,能够保证,即使时序不匹配,也能1秒钟退出阻塞状态,再去判断socket.adapter(socket.dft())
|
||||||
|
sys.waitUntil("IP_READY", 1000)
|
||||||
|
end
|
||||||
|
|
||||||
|
-- 检测到了IP_READY消息
|
||||||
|
log.info("http_app_task_func", "recv IP_READY", socket.dft())
|
||||||
|
|
||||||
|
-- 普通的http get请求功能演示
|
||||||
|
http_app_get()
|
||||||
|
|
||||||
|
-- 50秒之后,循环测试
|
||||||
|
sys.wait(50000)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
--创建并且启动一个task
|
||||||
|
--运行这个task的处理函数http_app_task_func
|
||||||
|
sys.taskInit(http_app_task_func)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
--[[
|
||||||
|
@module main
|
||||||
|
@summary LuatOS用户应用脚本文件入口,总体调度应用逻辑
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.09.17
|
||||||
|
@author 王城钧
|
||||||
|
@usage
|
||||||
|
本demo演示的核心功能为:
|
||||||
|
1、http_app: 普通的http get请求功能演示;
|
||||||
|
2、netdrv_device:配置连接外网使用的网卡,目前支持以下四种选择(四选一)
|
||||||
|
(1) netdrv_eth_spi:通过SPI外挂CH390H芯片的以太网卡
|
||||||
|
(2)netdrv_4g:socket.LWIP_GP,4G网卡;
|
||||||
|
(3)netdrv_multiple:可以配置多种网卡的优先级,按照优先级配置,使用其中一种网卡连接外网;
|
||||||
|
(4)netdrv_pc:socket.LWIP_PC,PC模拟器网卡;
|
||||||
|
更多说明参考本目录下的readme.md文件
|
||||||
|
]]
|
||||||
|
|
||||||
|
--[[
|
||||||
|
必须定义PROJECT和VERSION变量,Luatools工具会用到这两个变量,远程升级功能也会用到这两个变量
|
||||||
|
PROJECT:项目名,ascii string类型
|
||||||
|
可以随便定义,只要不使用,就行
|
||||||
|
VERSION:项目版本号,ascii string类型
|
||||||
|
如果使用合宙iot.openluat.com进行远程升级,必须按照"XXX.YYY.ZZZ"三段格式定义:
|
||||||
|
X、Y、Z各表示1位数字,三个X表示的数字可以相同,也可以不同,同理三个Y和三个Z表示的数字也是可以相同,可以不同
|
||||||
|
因为历史原因,YYY这三位数字必须存在,但是没有任何用处,可以一直写为999
|
||||||
|
如果不使用合宙iot.openluat.com进行远程升级,根据自己项目的需求,自定义格式即可
|
||||||
|
]]
|
||||||
|
|
||||||
|
PROJECT = "HTTP"
|
||||||
|
VERSION = "001.999.000"
|
||||||
|
|
||||||
|
|
||||||
|
-- 在日志中打印项目名和项目版本号
|
||||||
|
log.info("main", PROJECT, VERSION)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
-- 如果内核固件支持errDump功能,此处进行配置,【强烈建议打开此处的注释】
|
||||||
|
-- 因为此功能模块可以记录并且上传脚本在运行过程中出现的语法错误或者其他自定义的错误信息,可以初步分析一些设备运行异常的问题
|
||||||
|
-- 以下代码是最基本的用法,更复杂的用法可以详细阅读API说明文档
|
||||||
|
-- 启动errDump日志存储并且上传功能,600秒上传一次
|
||||||
|
-- if errDump then
|
||||||
|
-- errDump.config(true, 600)
|
||||||
|
-- end
|
||||||
|
|
||||||
|
|
||||||
|
-- 使用LuatOS开发的任何一个项目,都强烈建议使用远程升级FOTA功能
|
||||||
|
-- 可以使用合宙的iot.openluat.com平台进行远程升级
|
||||||
|
-- 也可以使用客户自己搭建的平台进行远程升级
|
||||||
|
-- 远程升级的详细用法,可以参考fota的demo进行使用
|
||||||
|
|
||||||
|
|
||||||
|
-- 启动一个循环定时器
|
||||||
|
-- 每隔3秒钟打印一次总内存,实时的已使用内存,历史最高的已使用内存情况
|
||||||
|
-- 方便分析内存使用是否有异常
|
||||||
|
-- sys.timerLoopStart(function()
|
||||||
|
-- log.info("mem.lua", rtos.meminfo())
|
||||||
|
-- log.info("mem.sys", rtos.meminfo("sys"))
|
||||||
|
-- end, 3000)
|
||||||
|
|
||||||
|
-- 加载网络驱动设备功能模块
|
||||||
|
require "netdrv_device"
|
||||||
|
|
||||||
|
-- 加载http应用功能模块
|
||||||
|
require "http_app"
|
||||||
|
|
||||||
|
|
||||||
|
-- 用户代码已结束---------------------------------------------
|
||||||
|
-- 结尾总是这一句
|
||||||
|
sys.run()
|
||||||
|
-- sys.run()之后不要加任何语句!!!!!因为添加的任何语句都不会被执行
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
--[[
|
||||||
|
@module netdrv_4g
|
||||||
|
@summary “4G网卡”驱动模块
|
||||||
|
@version 1.0
|
||||||
|
@date 2025.07.01
|
||||||
|
@author 马梦阳
|
||||||
|
@usage
|
||||||
|
本文件为4G网卡驱动模块,核心业务逻辑为:
|
||||||
|
1、监听"IP_READY"和"IP_LOSE",在日志中进行打印;
|
||||||
|
|
||||||
|
本文件没有对外接口,直接在其他功能模块中require "netdrv_4g"就可以加载运行;
|
||||||
|
]]
|
||||||
|
|
||||||
|
local function ip_ready_func(ip, adapter)
|
||||||
|
if adapter == socket.LWIP_GP then
|
||||||
|
-- 在位置1和2设置自定义的DNS服务器ip地址:
|
||||||
|
-- "223.5.5.5",这个DNS服务器IP地址是阿里云提供的DNS服务器IP地址;
|
||||||
|
-- "114.114.114.114",这个DNS服务器IP地址是国内通用的DNS服务器IP地址;
|
||||||
|
-- 可以加上以下两行代码,在自动获取的DNS服务器工作不稳定的情况下,这两个新增的DNS服务器会使DNS服务更加稳定可靠;
|
||||||
|
-- 如果使用专网卡,不要使用这两行代码;
|
||||||
|
-- 如果使用国外的网络,不要使用这两行代码;
|
||||||
|
socket.setDNS(adapter, 1, "223.5.5.5")
|
||||||
|
socket.setDNS(adapter, 2, "114.114.114.114")
|
||||||
|
|
||||||
|
log.info("netdrv_4g.ip_ready_func", "IP_READY", socket.localIP(socket.LWIP_GP))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
local function ip_lose_func(adapter)
|
||||||
|
if adapter == socket.LWIP_GP then
|
||||||
|
log.warn("netdrv_4g.ip_lose_func", "IP_LOSE")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
|
-- 此处订阅"IP_READY"和"IP_LOSE"两种消息
|
||||||
|
-- 在消息的处理函数中,仅仅打印了一些信息,便于实时观察4G网络的连接状态
|
||||||
|
-- 也可以根据自己的项目需求,在消息处理函数中增加自己的业务逻辑控制,例如可以在连网状态发生改变时更新网络图标
|
||||||
|
sys.subscribe("IP_READY", ip_ready_func)
|
||||||
|
sys.subscribe("IP_LOSE", ip_lose_func)
|
||||||
|
|
||||||
|
-- 在Air780EPM上,内核固件运行起来之后,默认网卡就是socket.LWIP_GP
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user