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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//! Defines WasmEdge ahead-of-time compiler.

use crate::{error::WasmEdgeError, ffi, utils, utils::check, Config, WasmEdgeResult};
use std::path::Path;

/// Defines WasmEdge ahead-of-time(AOT) compiler and the relevant APIs.
#[derive(Debug)]
pub struct Compiler {
    pub(crate) inner: InnerCompiler,
}
impl Drop for Compiler {
    fn drop(&mut self) {
        if !self.inner.0.is_null() {
            unsafe { ffi::WasmEdge_CompilerDelete(self.inner.0) }
        }
    }
}
impl Compiler {
    /// Creates a new AOT [compiler](crate::Compiler).
    ///
    /// # Error
    ///
    /// If fail to create a AOT [compiler](crate::Compiler), then an error is returned.
    pub fn create(config: Option<&Config>) -> WasmEdgeResult<Self> {
        let ctx = match config {
            Some(config) => unsafe { ffi::WasmEdge_CompilerCreate(config.inner.0) },
            None => unsafe { ffi::WasmEdge_CompilerCreate(std::ptr::null_mut()) },
        };

        match ctx.is_null() {
            true => Err(Box::new(WasmEdgeError::CompilerCreate)),
            false => Ok(Self {
                inner: InnerCompiler(ctx),
            }),
        }
    }

    /// Compiles the input WASM from the given file path for the AOT mode and stores the result to the output file path.
    ///
    /// # Arguments
    ///
    /// * `wasm_file` - The input wasm file, of which the file extension should be one of `wasm` or`wat`.
    ///
    /// * `aot_file` - The generated AOT wasm file, of which the file extension should be `dylib` on macOS, `so` on Linux or `dll` on Windows.
    ///
    /// # Error
    ///
    /// If fail to compile, then an error is returned.
    pub fn compile_from_file(
        &self,
        wasm_file: impl AsRef<Path>,
        aot_file: impl AsRef<Path>,
    ) -> WasmEdgeResult<()> {
        match wasm_file.as_ref().extension() {
            Some(extension) => match extension.to_str() {
                Some("wasm") => self.compile_from_wasm_file(wasm_file, aot_file),
                Some("wat") => {
                    let bytes = wat::parse_file(wasm_file.as_ref())
                        .map_err(|_| WasmEdgeError::Operation("Failed to parse wat file".into()))?;
                    self.compile_from_bytes(bytes, aot_file)
                }
                _ => Err(Box::new(WasmEdgeError::Operation(
                    "The wasm file's extension should be `wasm` or `wat`".into(),
                ))),
            },
            None => Err(Box::new(WasmEdgeError::Operation(
                "The wasm file's extension should be `wasm` or `wat`".into(),
            ))),
        }
    }

    fn compile_from_wasm_file(
        &self,
        wasm_file: impl AsRef<Path>,
        aot_file: impl AsRef<Path>,
    ) -> WasmEdgeResult<()> {
        let in_path = utils::path_to_cstring(wasm_file.as_ref())?;
        let out_path = utils::path_to_cstring(aot_file.as_ref())?;
        unsafe {
            check(ffi::WasmEdge_CompilerCompile(
                self.inner.0,
                in_path.as_ptr(),
                out_path.as_ptr(),
            ))
        }
    }

    /// Compiles the input WASM from the given bytes for the AOT mode and stores the result to the output file path.
    ///
    /// # Argument
    ///
    /// * `wasm_bytes` - The in-memory WASM bytes.
    ///
    /// * `aot_file` - The generated AOT wasm file, of which the file extension should be `dylib` on macOS, `so` on Linux or `dll` on Windows.
    ///
    /// # Error
    ///
    /// If fail to compile, then an error is returned.
    pub fn compile_from_bytes(
        &self,
        wasm_bytes: impl AsRef<[u8]>,
        aot_file: impl AsRef<Path>,
    ) -> WasmEdgeResult<()> {
        let out_path = utils::path_to_cstring(aot_file.as_ref())?;
        unsafe {
            let ptr = libc::malloc(wasm_bytes.as_ref().len());
            let dst = ::core::slice::from_raw_parts_mut(
                ptr.cast::<std::mem::MaybeUninit<u8>>(),
                wasm_bytes.as_ref().len(),
            );
            let src = ::core::slice::from_raw_parts(
                wasm_bytes
                    .as_ref()
                    .as_ptr()
                    .cast::<std::mem::MaybeUninit<u8>>(),
                wasm_bytes.as_ref().len(),
            );
            dst.copy_from_slice(src);

            check(ffi::WasmEdge_CompilerCompileFromBuffer(
                self.inner.0,
                ptr as *const u8,
                wasm_bytes.as_ref().len() as u64,
                out_path.as_ptr(),
            ))?;

            libc::free(ptr as *mut libc::c_void);
        }

        Ok(())
    }

    /// Provides a raw pointer to the inner Compiler context.
    #[cfg(feature = "ffi")]
    pub fn as_ptr(&self) -> *const ffi::WasmEdge_CompilerContext {
        self.inner.0 as *const _
    }
}

#[derive(Debug)]
pub(crate) struct InnerCompiler(pub(crate) *mut ffi::WasmEdge_CompilerContext);
unsafe impl Send for InnerCompiler {}
unsafe impl Sync for InnerCompiler {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        error::{CoreError, CoreLoadError},
        Config,
    };
    use std::{
        io::Read,
        sync::{Arc, Mutex},
        thread,
    };
    use wasmedge_types::{wat2wasm, CompilerOptimizationLevel, CompilerOutputFormat};

    #[test]
    #[allow(clippy::assertions_on_result_states)]
    fn test_compiler() {
        {
            let result = Config::create();
            assert!(result.is_ok());
            let config = result.unwrap();

            // create a AOT Compiler without configuration
            let result = Compiler::create(None);
            assert!(result.is_ok());

            // create a AOT Compiler with a given configuration
            let result = Compiler::create(Some(&config));
            assert!(result.is_ok());
            let compiler = result.unwrap();

            // compile a file for universal WASM output format
            let in_path = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
                .join("bindings/rust/wasmedge-sys/examples/data/test.wat");
            #[cfg(target_os = "linux")]
            let out_path = std::path::PathBuf::from("test_aot.so");
            #[cfg(target_os = "macos")]
            let out_path = std::path::PathBuf::from("test_aot.dylib");
            #[cfg(target_os = "windows")]
            let out_path = std::path::PathBuf::from("test_aot.dll");
            assert!(!out_path.exists());
            let result = compiler.compile_from_file(in_path, &out_path);
            assert!(result.is_ok());
            assert!(out_path.exists());
            assert!(std::fs::remove_file(out_path).is_ok());

            // compile a virtual file
            let result = compiler.compile_from_file("not_exist.wasm", "not_exist_ast.wasm");
            assert!(result.is_err());
            assert_eq!(
                result.unwrap_err(),
                Box::new(WasmEdgeError::Core(CoreError::Load(
                    CoreLoadError::IllegalPath
                )))
            );
        }

        {
            let result = Config::create();
            assert!(result.is_ok());
            let mut config = result.unwrap();
            // compile file for shared library output format
            config.set_aot_compiler_output_format(CompilerOutputFormat::Native);

            let result = Compiler::create(Some(&config));
            assert!(result.is_ok());
            let compiler = result.unwrap();
            let in_path = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
                .join("bindings/rust/wasmedge-sys/examples/data/test.wat");
            #[cfg(target_os = "linux")]
            let out_path = std::path::PathBuf::from("test_aot_from_file.so");
            #[cfg(target_os = "macos")]
            let out_path = std::path::PathBuf::from("test_aot_from_file.dylib");
            #[cfg(target_os = "windows")]
            let out_path = std::path::PathBuf::from("test_aot_from_file.dll");
            assert!(!out_path.exists());
            let result = compiler.compile_from_file(in_path, &out_path);
            assert!(result.is_ok());
            assert!(out_path.exists());

            // read buffer
            let result = std::fs::File::open(&out_path);
            assert!(result.is_ok());
            let mut f = result.unwrap();
            let mut buffer = [0u8; 4];
            let result = f.read(&mut buffer);
            assert!(result.is_ok());
            let wasm_magic: [u8; 4] = [0x00, 0x61, 0x73, 0x6D];
            assert_ne!(buffer, wasm_magic);

            // cleanup
            assert!(std::fs::remove_file(out_path).is_ok());
        }

        {
            let result = wat2wasm(
                br#"(module
                    (export "fib" (func $fib))
                    (func $fib (param $n i32) (result i32)
                     (if
                      (i32.lt_s
                       (get_local $n)
                       (i32.const 2)
                      )
                      (return
                       (i32.const 1)
                      )
                     )
                     (return
                      (i32.add
                       (call $fib
                        (i32.sub
                         (get_local $n)
                         (i32.const 2)
                        )
                       )
                       (call $fib
                        (i32.sub
                         (get_local $n)
                         (i32.const 1)
                        )
                       )
                      )
                     )
                    )
                   )
              "#,
            );
            assert!(result.is_ok());
            let wasm_bytes = result.unwrap();

            let result = Config::create();
            assert!(result.is_ok());
            let mut config = result.unwrap();
            config.set_aot_optimization_level(CompilerOptimizationLevel::O0);
            config.set_aot_compiler_output_format(CompilerOutputFormat::Native);

            let result = Compiler::create(Some(&config));
            assert!(result.is_ok());
            let compiler = result.unwrap();
            #[cfg(target_os = "linux")]
            let out_path = std::path::PathBuf::from("test_aot_from_bytes.so");
            #[cfg(target_os = "macos")]
            let out_path = std::path::PathBuf::from("test_aot_from_bytes.dylib");
            #[cfg(target_os = "windows")]
            let out_path = std::path::PathBuf::from("test_aot_from_bytes.dll");
            assert!(!out_path.exists());
            let result = compiler.compile_from_bytes(wasm_bytes, &out_path);
            assert!(result.is_ok());
            assert!(out_path.exists());

            // cleanup
            assert!(std::fs::remove_file(out_path).is_ok());
        }
    }

    #[test]
    #[ignore]
    #[allow(clippy::assertions_on_result_states)]
    fn test_compiler_send() {
        let result = Config::create();
        assert!(result.is_ok());
        let config = result.unwrap();

        // create a AOT Compiler without configuration
        let result = Compiler::create(None);
        assert!(result.is_ok());

        // create a AOT Compiler with a given configuration
        let result = Compiler::create(Some(&config));
        assert!(result.is_ok());
        let compiler = result.unwrap();

        let handle = thread::spawn(move || {
            // compile a file for universal WASM output format
            let in_path = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
                .join("bindings/rust/wasmedge-sys/examples/data/fibonacci.wasm");
            #[cfg(target_os = "linux")]
            let out_path = std::path::PathBuf::from("test_aot_fib_send.so");
            #[cfg(target_os = "macos")]
            let out_path = std::path::PathBuf::from("test_aot_fib_send.dylib");
            #[cfg(target_os = "windows")]
            let out_path = std::path::PathBuf::from("test_aot_fib_send.dll");
            assert!(!out_path.exists());
            let result = compiler.compile_from_file(in_path, &out_path);
            assert!(result.is_ok());
            assert!(out_path.exists());
            assert!(std::fs::remove_file(out_path).is_ok());
        });

        handle.join().unwrap();
    }

    #[test]
    #[ignore]
    #[allow(clippy::assertions_on_result_states)]
    fn test_compiler_sync() {
        let result = Config::create();
        assert!(result.is_ok());
        let config = result.unwrap();

        // create a AOT Compiler without configuration
        let result = Compiler::create(None);
        assert!(result.is_ok());

        // create a AOT Compiler with a given configuration
        let result = Compiler::create(Some(&config));
        assert!(result.is_ok());
        let compiler = Arc::new(Mutex::new(result.unwrap()));

        let compiler_cloned = Arc::clone(&compiler);
        let handle = thread::spawn(move || {
            let result = compiler_cloned.lock();
            assert!(result.is_ok());
            let compiler = result.unwrap();

            // compile a file for universal WASM output format
            let in_path = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
                .join("bindings/rust/wasmedge-sys/examples/data/fibonacci.wasm");
            let out_path = std::path::PathBuf::from("fibonacci_sync_thread_aot.wasm");
            assert!(!out_path.exists());
            let result = compiler.compile_from_file(in_path, &out_path);
            assert!(result.is_ok());
            assert!(out_path.exists());
            assert!(std::fs::remove_file(out_path).is_ok());
        });

        {
            let result = compiler.lock();
            assert!(result.is_ok());
            let compiler_main = result.unwrap();
            // compile a file for universal WASM output format
            let in_path = std::path::PathBuf::from(env!("WASMEDGE_DIR"))
                .join("bindings/rust/wasmedge-sys/examples/data/fibonacci.wasm");
            #[cfg(target_os = "linux")]
            let out_path = std::path::PathBuf::from("test_aot_fib_sync.so");
            #[cfg(target_os = "macos")]
            let out_path = std::path::PathBuf::from("test_aot_fib_sync.dylib");
            #[cfg(target_os = "windows")]
            let out_path = std::path::PathBuf::from("test_aot_fib_sync.dll");
            assert!(!out_path.exists());
            let result = compiler_main.compile_from_file(in_path, &out_path);
            assert!(result.is_ok());
            assert!(out_path.exists());
            assert!(std::fs::remove_file(out_path).is_ok());
        }

        handle.join().unwrap();
    }
}