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
#![deny(missing_docs)]

//! A crate wrapping [tcc](https://bellard.org/tcc/) in Rust.

mod bindings;

use crate::bindings::*;
use std::ffi::{CStr, CString};
use std::fmt;
use std::mem;
use std::os::raw::c_void;
use std::path::Path;
use std::ptr::null_mut;
use std::rc::Rc;

#[derive(Debug, Clone, Copy)]
#[repr(u32)]
/// Output type of the compilation.
pub enum OutputType {
    /// output will be run in memory (default)
    Memory = TCC_OUTPUT_MEMORY,

    /// executable file
    Exe = TCC_OUTPUT_EXE,

    /// dynamic library
    Dll = TCC_OUTPUT_DLL,

    /// object file
    Obj = TCC_OUTPUT_OBJ,

    /// only preprocess (used internally)
    Preprocess = TCC_OUTPUT_PREPROCESS,
}

extern "C" fn callback(user_data: *mut c_void, string: *const i8) {
    let tcc = unsafe { &mut *(user_data as *mut Tcc) };
    if let Some(ref func) = tcc.error_func {
        let string = unsafe { CStr::from_ptr(string) }.to_str().unwrap();
        func(string);
    }
}

/// Main struct of this crate, can be used to compile C code into machine code.
pub struct Tcc {
    inner: *mut TCCState,
    error_func: Option<Box<dyn Fn(&str)>>,
}

impl fmt::Debug for Tcc {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "Tcc")
    }
}

impl Default for Tcc {
    fn default() -> Tcc {
        Tcc::new()
    }
}

impl Tcc {
    /// create a new TCC compilation context
    pub fn new() -> Self {
        Tcc {
            inner: unsafe { tcc_new() },
            error_func: None,
        }
    }

    /// set CONFIG_TCCDIR at runtime
    pub fn set_lib_path<P: AsRef<Path>>(&mut self, path: P) {
        let path = path.as_ref().to_str().unwrap();
        unsafe { tcc_set_lib_path(self.inner, path.as_ptr() as *const i8) }
    }

    /// set error/warning display callback
    pub fn set_error_func(&mut self, error_func: Option<Box<dyn Fn(&str)>>) {
        unsafe {
            tcc_set_error_func(
                self.inner,
                self as *mut Tcc as *mut c_void,
                if error_func.is_some() {
                    Some(callback)
                } else {
                    None
                },
            )
        };
        self.error_func = error_func;
    }

    /// set options as from command line (multiple supported)
    pub fn set_options(&mut self, options: &str) {
        let options = CString::new(options).unwrap();
        unsafe { tcc_set_options(self.inner, options.as_ptr()) };
    }

    /// add include path
    pub fn add_include_path<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        let path = path.as_ref().to_str().unwrap();
        let ret = unsafe { tcc_add_include_path(self.inner, path.as_ptr() as *const i8) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// add in system include path
    pub fn add_sysinclude_path<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        let path = path.as_ref().to_str().unwrap();
        let ret = unsafe { tcc_add_sysinclude_path(self.inner, path.as_ptr() as *const i8) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// define preprocessor symbol 'sym'. Can put optional value
    pub fn define_symbol(&mut self, sym: &str, value: &str) {
        let sym = CString::new(sym).unwrap();
        let value = CString::new(value).unwrap();
        unsafe { tcc_define_symbol(self.inner, sym.as_ptr(), value.as_ptr()) }
    }

    /// undefine preprocess symbol 'sym'
    pub fn undefine_symbol(&mut self, sym: &str) {
        let sym = CString::new(sym).unwrap();
        unsafe { tcc_undefine_symbol(self.inner, sym.as_ptr()) }
    }

    /// add a file (C file, dll, object, library, ld script)
    pub fn add_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        let path = path.as_ref().to_str().unwrap();
        let ret = unsafe { tcc_add_file(self.inner, path.as_ptr() as *const i8) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// compile a string containing a C source
    pub fn compile_string(&mut self, buf: &str) -> Result<(), ()> {
        let buf = CString::new(buf).unwrap();
        let ret = unsafe { tcc_compile_string(self.inner, buf.as_ptr()) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// set output type. MUST BE CALLED before any compilation
    pub fn set_output_type(&mut self, output_type: OutputType) -> Result<(), ()> {
        let ret = unsafe { tcc_set_output_type(self.inner, output_type as i32) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// equivalent to -Lpath option
    pub fn add_library_path<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        let path = path.as_ref().to_str().unwrap();
        let ret = unsafe { tcc_add_library_path(self.inner, path.as_ptr() as *const i8) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// the library name is the same as the argument of the '-l' option
    pub fn add_library(&mut self, name: &str) -> Result<(), ()> {
        let name = CString::new(name).unwrap();
        let ret = unsafe { tcc_add_library(self.inner, name.as_ptr()) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// add a symbol to the compiled program
    pub fn add_symbol<S: Symbol>(&mut self, name: &str, symbol: &S) -> Result<(), ()> {
        let name = CString::new(name).unwrap();
        let ret = unsafe { tcc_add_symbol(self.inner, name.as_ptr(), symbol.as_ptr()) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// output an executable, library or object file
    pub fn output_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        let path = path.as_ref().to_str().unwrap();
        let ret = unsafe { tcc_output_file(self.inner, path.as_ptr() as *const i8) };
        if ret == -1 {
            return Err(());
        }
        Ok(())
    }

    /// link and run main() function and return its value
    pub fn run(&mut self, args: &[&str]) -> Result<(), ()> {
        let argc = args.len();
        let mut argv: Vec<*mut i8> = args
            .iter()
            .map(|string| CString::new(*string).unwrap().into_raw())
            .collect();
        let ret = unsafe { tcc_run(self.inner, argc as i32, argv.as_mut_ptr()) };
        if ret == -1 {
            return Err(());
        }
        let _: Vec<CString> = argv
            .into_iter()
            .map(|ptr| unsafe { CString::from_raw(ptr) })
            .collect();
        Ok(())
    }

    /// do all relocations
    pub fn relocate(self) -> Result<RelocatedTcc, Tcc> {
        let len = unsafe { tcc_relocate(self.inner, null_mut()) };
        if len == -1 {
            return Err(self);
        }
        let mut memory = Vec::with_capacity(len as usize);
        let ret = unsafe { tcc_relocate(self.inner, memory.as_mut_ptr() as *mut c_void) };
        if ret == -1 {
            return Err(self);
        }
        unsafe { memory.set_len(len as usize) }
        let relocated = RelocatedTcc {
            inner: self.inner,
            memory: Rc::new(memory),
        };
        // We need this in order to not deallocate self.inner in the Drop impl.
        mem::forget(self);
        Ok(relocated)
    }
}

impl Drop for Tcc {
    fn drop(&mut self) {
        unsafe { tcc_delete(self.inner) }
    }
}

/// Once `Tcc::relocate()` is done successfully, this struct is returned to let you fetch the
/// symbols from the generated machine code.
pub struct RelocatedTcc {
    inner: *mut TCCState,
    memory: Rc<Vec<u8>>,
}

impl RelocatedTcc {
    /// return symbol value or NULL if not found
    pub fn get_symbol(&mut self, name: &str) -> Result<CSymbol, ()> {
        let name = CString::new(name).unwrap();
        let ptr = unsafe { tcc_get_symbol(self.inner, name.as_ptr()) };
        if ptr.is_null() {
            return Err(());
        }
        Ok(CSymbol {
            ptr: ptr,
            name: name.into_string().map_err(|_| ())?,
            memory: self.memory.clone(),
        })
    }
}

impl fmt::Debug for RelocatedTcc {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "RelocatedTcc")
    }
}

impl Drop for RelocatedTcc {
    fn drop(&mut self) {
        unsafe { tcc_delete(self.inner) }
        // self.memory will only be dropped once the last CSymbol is dropped.
    }
}

/// Symbol trait, implemented by either a `CSymbol` returned by `TccRelocated::get_symbol()`, or
/// by any `*const c_void` (for instance an `extern "C"` function).
pub trait Symbol {
    /// How to obtain a pointer to pass to `Tcc::add_symbol()`.
    fn as_ptr(&self) -> *const c_void;
}

/// A C symbol returned by `TccRelocated::get_symbol()`.
pub struct CSymbol {
    ptr: *const c_void,

    name: String,

    #[allow(dead_code)]
    memory: Rc<Vec<u8>>,
}

impl fmt::Debug for CSymbol {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(fmt, "CSymbol({:?} at {:p})", self.name, self.ptr)
    }
}

impl Symbol for CSymbol {
    fn as_ptr(&self) -> *const c_void {
        self.ptr
    }
}

impl Symbol for *const c_void {
    fn as_ptr(&self) -> *const c_void {
        *self
    }
}