Created
February 13, 2019 15:52
-
-
Save nyinyithann/4db3d74b14244974ae9829a1b22061c7 to your computer and use it in GitHub Desktop.
A simple freestanding program using libc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(start)] | |
#![no_std] | |
extern crate libc; | |
use core::panic::PanicInfo; | |
use libc::{c_char, c_int, c_void, size_t}; | |
extern "C" { | |
fn malloc(size: size_t) -> *mut c_void; | |
fn free(p: *mut c_void); | |
fn exit(status: c_int) -> !; | |
fn printf(fmt: *const c_char, ...) -> c_int; | |
} | |
#[start] | |
fn main(argc: isize, _argv: *const *const u8) -> isize { | |
unsafe { | |
let ptr1 = malloc(32 as size_t) as *mut i32; | |
if ptr1 as usize == 0 { | |
printf("Memory not allocated.\0".as_ptr() as *const i8); | |
exit(0); | |
} | |
*ptr1 = 2; | |
let ptr2 = malloc(32 as size_t) as *mut i32; | |
if ptr2 as usize == 0 { | |
printf("Memory not allocated.\0".as_ptr() as *const i8); | |
exit(0); | |
} | |
*ptr2 = 5; | |
printf( | |
"%d + %d = %d\0".as_ptr() as *const i8, | |
*ptr1, | |
*ptr2, | |
*ptr1 + *ptr2, | |
); | |
free(ptr1 as *mut c_void); | |
free(ptr2 as *mut c_void); | |
} | |
0 | |
} | |
#[panic_handler] | |
fn panic(_info: &PanicInfo) -> ! { | |
loop {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cargo.toml
[package]
name = "libc"
version = "0.1.0"
authors = ["nyinyithann [email protected]"]
edition = "2018"
[profile.dev]
panic = "abort"
[profile.release]
panic = "abort"
[dependencies]
libc = { version = "0.2.48", default-features = false }