Skip to content

Commit 45f4dd0

Browse files
CopilotGordonSmith
authored andcommitted
chore: Enhance WAMR Component Model Sample with improved build and run scripts, comprehensive README, and error handling
Signed-off-by: Gordon Smith <GordonJSmith@gmail.com>
1 parent 557b20b commit 45f4dd0

21 files changed

Lines changed: 1635 additions & 248 deletions
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
---
2+
applyTo: '**'
3+
---
4+
# Component Model Instructions
5+
6+
## Repository Goal
7+
8+
This repository implements a C++ ABI (Application Binary Interface) for the WebAssembly Component Model, providing host bindings that allow C++ applications to interact with WebAssembly components.
9+
10+
### WebAssembly Component Model Overview
11+
The [WebAssembly Component Model](https://github.com/WebAssembly/component-model) is a specification that extends WebAssembly with:
12+
- **Interface Types**: Rich type system beyond basic WebAssembly types
13+
- **Component Linking**: Composable components with well-defined interfaces
14+
- **World Definitions**: Complete application interface descriptions
15+
- **WIT (WebAssembly Interface Types)**: IDL for describing component interfaces
16+
17+
### This Repository's Implementation
18+
19+
#### Core Features Implemented
20+
- **Host Data Types**: Complete mapping of Component Model types to C++ types
21+
- Primitive types: bool, integers (s8-s64, u8-u64), floats (f32, f64), char
22+
- String types: UTF-8, UTF-16, Latin-1+UTF-16 encoding support
23+
- Composite types: lists, records, tuples, variants, enums, options, results, flags
24+
- Resource types: own, borrow (planned)
25+
26+
- **ABI Functions**: Core Component Model operations
27+
- `lower_flat_values`: Convert C++ values to WebAssembly flat representation
28+
- `lift_flat_values`: Convert WebAssembly flat values to C++ types
29+
- Memory management with proper encoding handling
30+
31+
#### Architecture
32+
- **Header-only Library**: Pure template-based implementation in `include/cmcpp/`
33+
- **Type Safety**: Strong typing ensures correct Component Model ABI compliance
34+
- **Runtime Integration**: Support for multiple WebAssembly runtimes
35+
- [WAMR (WebAssembly Micro Runtime)](https://github.com/bytecodealliance/wasm-micro-runtime) - implemented
36+
- [WasmTime](https://github.com/bytecodealliance/wasmtime) - planned
37+
- [WasmEdge](https://github.com/WasmEdge/WasmEdge) - planned
38+
- [Wasmer](https://github.com/wasmerio/wasmer) - planned
39+
40+
#### Component Model Compliance
41+
- **Canonical ABI**: Implements the official Component Model Canonical ABI
42+
- **Interface Types**: Full support for Interface Types specification
43+
- **Memory Layout**: Proper handling of WebAssembly linear memory layout
44+
- **Encoding**: Support for UTF-8, UTF-16, and Latin-1+UTF-16 string encodings
45+
- **Alignment**: Correct alignment handling for different data types
46+
47+
### Usage Patterns
48+
When working with this library:
49+
1. **Define Interfaces**: Use C++ types that map to Component Model interface types
50+
2. **Host Functions**: Implement host functions using the provided type wrappers
51+
3. **Guest Interaction**: Use lift/lower functions to marshal data between host and guest
52+
4. **Memory Management**: Use the provided realloc functions for guest memory allocation
53+
54+
### References
55+
- [WebAssembly Component Model Specification](https://github.com/WebAssembly/component-model)
56+
- [Component Model Canonical ABI](https://github.com/WebAssembly/component-model/blob/main/design/mvp/CanonicalABI.md)
57+
- [WIT (WebAssembly Interface Types)](https://github.com/WebAssembly/component-model/blob/main/design/mvp/WIT.md)

.github/instructions/general.instructions.md

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,45 @@ applyTo: '**'
33
---
44
# General Instructions
55

6-
- This repository is a modern c++ project.
7-
- It uses CMake to build and test the project
8-
- The goal of the project is to create host bindings for the [WebAssembly Component Model](ref/component-model/README.md)
6+
## Modern C++ Project Guidelines
7+
8+
This repository is a modern C++20 header-only library implementing WebAssembly Component Model host bindings.
9+
10+
### C++ Standards and Features
11+
- **C++20 Standard**: Use modern C++20 features throughout the codebase
12+
- **Header-only Library**: All implementation is in the `include/` directory
13+
- **Template-heavy Design**: Extensive use of templates for type safety and compile-time optimizations
14+
- **Concepts**: Use C++20 concepts where appropriate for template constraints
15+
- **constexpr**: Prefer constexpr for compile-time computations
16+
- **RAII**: Follow RAII principles for resource management
17+
- **Smart Pointers**: Use std::unique_ptr, std::shared_ptr instead of raw pointers
18+
- **Standard Library**: Prefer STL containers and algorithms over custom implementations
19+
20+
### Code Organization (Reference: `include/` directory)
21+
- **Namespace**: All code is in the `cmcpp` namespace
22+
- **Modular Headers**: Each data type has its own header (integer.hpp, float.hpp, string.hpp, etc.)
23+
- **Core Types**: Located in `include/cmcpp/` subdirectory
24+
- **Integration Headers**: Top-level headers like `wamr.hpp` for runtime integration
25+
- **Template Specializations**: Use template specialization for different WebAssembly types
26+
27+
### Build System
28+
- **CMake**: Uses CMake 3.5+ with modern CMake practices
29+
- **Interface Library**: Configured as an interface library target
30+
- **Cross-platform**: Supports Ubuntu, macOS, and Windows
31+
- **Compiler Requirements**: Requires C++20 support
32+
- **Dependencies**: Uses vcpkg for third-party library management
33+
- Package definitions in `vcpkg.json` and `vcpkg-configuration.json`
34+
- Key dependencies: doctest (testing), ICU (Unicode), wasm-micro-runtime, wasi-sdk
35+
36+
### Type Safety and WebAssembly ABI
37+
- **Strong Typing**: Use distinct types for WebAssembly values (bool_t, char_t, etc.)
38+
- **ABI Compliance**: Implement proper lifting and lowering functions for WebAssembly Component Model
39+
- **Memory Safety**: Handle WebAssembly linear memory access safely
40+
- **Error Handling**: Use proper exception handling and validation
41+
42+
### Code Style Guidelines
43+
- **Template Programming**: Follow modern template metaprogramming practices
44+
- **Function Templates**: Use function templates for type-generic operations
45+
- **SFINAE/Concepts**: Use concepts or SFINAE for template constraints
46+
- **Const Correctness**: Maintain const correctness throughout
47+
- **Naming**: Use snake_case for variables, PascalCase for types
Lines changed: 88 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,92 @@
11
---
2-
applyTo: '**'
2+
applyTo: 'samples/wamr/**'
33
---
4-
54
# WAMR Instructions
65

7-
- This code uses the [wasm-micro-runtime](https://github.com/bytecodealliance/wasm-micro-runtime) to host a wasm guest.
6+
## WebAssembly Micro Runtime Integration
7+
8+
This code demonstrates how to use the [WebAssembly Micro Runtime (WAMR)](https://github.com/bytecodealliance/wasm-micro-runtime) to host WebAssembly components with Component Model bindings.
9+
10+
### WAMR Overview
11+
WAMR is a lightweight, high-performance WebAssembly runtime designed for:
12+
- **Embedded Systems**: Optimized for resource-constrained environments
13+
- **Edge Computing**: Fast startup and low memory footprint
14+
- **Cross-platform**: Supports multiple architectures and operating systems
15+
- **Multiple Execution Modes**: Interpreter, AOT, and JIT compilation
16+
17+
### Integration Architecture
18+
19+
#### Host Function Registration
20+
```cpp
21+
// Register native functions that the WebAssembly guest can call
22+
bool success = wasm_runtime_register_natives_raw("module_name", symbols, count);
23+
```
24+
25+
#### Component Model Host Functions
26+
The `samples/wamr/main.cpp` demonstrates:
27+
- **Type Mapping**: C++ types to Component Model types using `cmcpp` namespace
28+
- **Function Wrappers**: Using `host_function()` to create WAMR-compatible function pointers
29+
- **Module Organization**: Grouping functions by interface/module names
30+
31+
#### Memory Management
32+
- **Linear Memory**: Access WebAssembly linear memory through `wasm_memory_get_base_address()`
33+
- **Reallocation**: Use `cabi_realloc` for guest memory management
34+
- **Memory Safety**: Proper bounds checking and address validation
35+
36+
### WAMR-Specific Implementation Details
37+
38+
#### Execution Environment
39+
```cpp
40+
wasm_exec_env_t exec_env = wasm_runtime_create_exec_env(module_inst, stack_size);
41+
```
42+
- **Stack Size**: Configure stack size for WebAssembly execution
43+
- **Heap Size**: Set heap size for guest memory allocation
44+
- **Module Instance**: Each module gets its own instance with isolated memory
45+
46+
#### Function Calling Convention
47+
- **Native Symbols**: Use `NativeSymbol` arrays to define exported functions
48+
- **Argument Passing**: Arguments passed via `uint64_t *args` array
49+
- **Return Values**: Return values set through the same args array
50+
- **Type Conversion**: Automatic conversion between C++ and WebAssembly types
51+
52+
#### Integration with Component Model
53+
The `wamr.hpp` header provides:
54+
- **Template Functions**: `export_func<F>()` for automatic type marshaling
55+
- **Host Function Creation**: `host_function()` helper for creating native symbols
56+
- **Memory Access**: Safe linear memory access with bounds checking
57+
- **Encoding Support**: UTF-8, UTF-16 string encoding handling
58+
59+
### Sample Structure (`samples/wamr/`)
60+
61+
#### Files
62+
- **main.cpp**: Complete example showing WAMR integration
63+
- **CMakeLists.txt**: Build configuration for WAMR sample
64+
- **main.c**: Alternative C implementation (if needed)
65+
66+
#### Example Functions Demonstrated
67+
- **Void Functions**: Simple function calls without parameters
68+
- **Boolean Operations**: Logical operations with Component Model bool_t
69+
- **Numeric Operations**: Float and integer arithmetic
70+
- **String Manipulation**: UTF-8 string processing and transformation
71+
- **Logging**: Host-side logging from guest functions
72+
73+
### Build Requirements
74+
- **WAMR Library**: Requires libiwasm and libvmlib
75+
- **vcpkg Integration**: Uses vcpkg for dependency management
76+
- **CMake Configuration**: Proper CMake setup for finding WAMR libraries
77+
78+
### Error Handling
79+
- **Runtime Errors**: Check return values from WAMR API calls
80+
- **Memory Errors**: Validate memory access and allocation
81+
- **Type Errors**: Ensure proper type conversion between host and guest
82+
- **Module Loading**: Handle WebAssembly module loading failures
83+
84+
### Performance Considerations
85+
- **Function Call Overhead**: Minimize marshaling overhead for hot paths
86+
- **Memory Allocation**: Efficient guest memory management
87+
- **Type Conversions**: Optimize type lifting/lowering operations
88+
89+
### References
90+
- [WAMR GitHub Repository](https://github.com/bytecodealliance/wasm-micro-runtime)
91+
- [WAMR Documentation](https://github.com/bytecodealliance/wasm-micro-runtime/blob/main/doc/README.md)
92+
- [WAMR Host API](https://github.com/bytecodealliance/wasm-micro-runtime/blob/main/core/iwasm/include/wasm_export.h)

.github/workflows/macos.yml

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ on:
99
branches:
1010
- trunk
1111
- main
12+
workflow_dispatch:
1213

1314
env:
1415
CTEST_OUTPUT_ON_FAILURE: 1
@@ -24,12 +25,6 @@ jobs:
2425

2526
runs-on: ${{ matrix.os }}
2627
steps:
27-
- name: Set up C++20
28-
uses: aminya/setup-cpp@v1
29-
with:
30-
compiler: gcc-13
31-
cmake: true
32-
ninja: true
3328

3429
- uses: actions/checkout@v3
3530
with:

.github/workflows/ubuntu.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ on:
99
branches:
1010
- trunk
1111
- main
12+
workflow_dispatch:
1213

1314
env:
1415
CTEST_OUTPUT_ON_FAILURE: 1

.github/workflows/windows.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ on:
99
branches:
1010
- trunk
1111
- main
12+
workflow_dispatch:
1213

1314
env:
1415
CTEST_OUTPUT_ON_FAILURE: 1

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,7 @@
99
# Added by cargo
1010

1111
/target
12+
13+
# Python cache files
14+
__pycache__/
15+
*.pyc

.vscode/launch.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,18 @@
2020
"program": "${workspaceFolder}/build/samples/wamr/wamr",
2121
"args": [],
2222
"stopAtEntry": false,
23+
"cwd": "${workspaceFolder}/build/samples/wamr",
24+
"environment": [],
25+
"externalConsole": false,
26+
"preLaunchTask": "CMake: build"
27+
},
28+
{
29+
"name": "(gdb) wasmtime-sample",
30+
"type": "cppdbg",
31+
"request": "launch",
32+
"program": "${workspaceFolder}/build/samples/wasmtime/wasmtime",
33+
"args": [],
34+
"stopAtEntry": false,
2335
"cwd": "${workspaceFolder}",
2436
"environment": [],
2537
"externalConsole": false,

README.md

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,112 @@ This repository contains a C++ ABI implementation of the WebAssembly Component M
5959
- [x] Wamr
6060
- [ ] WasmEdge
6161

62+
## Build Instructions
63+
64+
### Prerequisites
65+
66+
- **CMake** 3.5 or higher (3.22+ recommended for presets)
67+
- **C++20 compatible compiler**
68+
- **vcpkg** for dependency management
69+
- **Rust toolchain** with `cargo` (for additional tools)
70+
71+
#### Platform-specific requirements
72+
73+
**Ubuntu/Linux:**
74+
```bash
75+
sudo apt-get install -y autoconf autoconf-archive automake build-essential ninja-build
76+
```
77+
78+
**macOS:**
79+
```bash
80+
brew install pkg-config autoconf autoconf-archive automake coreutils libtool cmake ninja
81+
```
82+
83+
**Windows:**
84+
- Visual Studio 2019 or 2022 with C++ support
85+
86+
#### Rust tools (required for samples and tests)
87+
```bash
88+
cargo install wasm-tools wit-bindgen-cli
89+
```
90+
91+
### Basic Build (Header-only)
92+
93+
For header-only usage without tests or samples:
94+
95+
```bash
96+
git clone https://github.com/LexisNexis-GHCPE/component-model-cpp.git
97+
cd component-model-cpp
98+
git submodule update --init --recursive
99+
100+
mkdir build && cd build
101+
cmake .. -DBUILD_TESTING=OFF -DBUILD_SAMPLES=OFF
102+
cmake --build .
103+
```
104+
105+
### Build with Dependencies (Tests & Samples)
106+
107+
Using CMake presets with vcpkg:
108+
109+
#### Linux
110+
```bash
111+
git clone https://github.com/LexisNexis-GHCPE/component-model-cpp.git
112+
cd component-model-cpp
113+
git submodule update --init --recursive
114+
115+
# Configure and build
116+
cmake --preset linux-ninja-Debug
117+
cmake --build --preset linux-ninja-Debug
118+
119+
# Run tests
120+
cd build && ctest -VV
121+
```
122+
123+
#### Windows
124+
```bash
125+
git clone https://github.com/LexisNexis-GHCPE/component-model-cpp.git
126+
cd component-model-cpp
127+
git submodule update --init --recursive
128+
129+
# Configure and build
130+
cmake --preset vcpkg-VS-17
131+
cmake --build --preset VS-17-Debug
132+
133+
# Run tests
134+
cd build && ctest -C Debug -VV
135+
```
136+
137+
#### macOS
138+
```bash
139+
git clone https://github.com/LexisNexis-GHCPE/component-model-cpp.git
140+
cd component-model-cpp
141+
git submodule update --init --recursive
142+
143+
# Configure and build
144+
cmake --preset linux-ninja-Debug
145+
cmake --build --preset linux-ninja-Debug
146+
147+
# Run tests
148+
cd build && ctest -VV
149+
```
150+
151+
### Manual Build without Presets
152+
153+
If you prefer not to use CMake presets:
154+
155+
```bash
156+
mkdir build && cd build
157+
cmake .. -DCMAKE_TOOLCHAIN_FILE=../vcpkg/scripts/buildsystems/vcpkg.cmake
158+
cmake --build .
159+
ctest -VV # Run tests
160+
```
161+
162+
### Build Options
163+
164+
- `-DBUILD_TESTING=ON/OFF` - Enable/disable building tests (requires doctest, ICU)
165+
- `-DBUILD_SAMPLES=ON/OFF` - Enable/disable building samples (requires wasi-sdk)
166+
- `-DCMAKE_BUILD_TYPE=Debug/Release/RelWithDebInfo/MinSizeRel` - Build configuration
167+
62168
## Usage
63169

64170
This library is a header only library. To use it in your project, you can:

include/cmcpp.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@
88
#include <cmcpp/list.hpp>
99
#include <cmcpp/tuple.hpp>
1010
#include <cmcpp/variant.hpp>
11+
#include <cmcpp/func.hpp>
1112
#include <cmcpp/lower.hpp>
1213
#include <cmcpp/lift.hpp>
13-
#include <cmcpp/func.hpp>
1414

1515
#endif // CMCPP_HPP

0 commit comments

Comments
 (0)