immunant / c2rust

Migrate C code to Rust
https://c2rust.com/
Other
3.79k stars 219 forks source link

Aggregate libc functions into one file. #1050

Open ahaoboy opened 7 months ago

ahaoboy commented 7 months ago

Currently, libc functions are individually imported in each file. If there is a need to replace a particular function, modifications are required in all files using it. Consolidating all libc functions into one file would require modifications only in that file for any changes.

// a.c
#include <stdio.h>

int funA(int n){
  puts("funA");
  printf("funA");
  return n;
}

// b.c
#include <stdio.h>

int funB(int n){
  printf("funB");
  return n;
}
// b.c
use ::libc;
extern "C" {
    fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
}
#[no_mangle]
pub unsafe extern "C" fn funB(mut n: libc::c_int) -> libc::c_int {
    printf(b"funB\0" as *const u8 as *const libc::c_char);
    return n;
}

// a.rs
use ::libc;
extern "C" {
    fn printf(_: *const libc::c_char, _: ...) -> libc::c_int;
    fn puts(__s: *const libc::c_char) -> libc::c_int;
}
#[no_mangle]
pub unsafe extern "C" fn funA(mut n: libc::c_int) -> libc::c_int {
    puts(b"funA\0" as *const u8 as *const libc::c_char);
    printf(b"funA\0" as *const u8 as *const libc::c_char);
    return n;
}
pitaj commented 4 months ago

Ideally these would just import from libc directly:

// b.c
use ::libc::printf;

#[no_mangle]
pub unsafe extern "C" fn funB(mut n: libc::c_int) -> libc::c_int {
    printf(b"funB\0" as *const u8 as *const libc::c_char);
    return n;
}

// a.rs
use ::libc::{printf, puts};

#[no_mangle]
pub unsafe extern "C" fn funA(mut n: libc::c_int) -> libc::c_int {
    puts(b"funA\0" as *const u8 as *const libc::c_char);
    printf(b"funA\0" as *const u8 as *const libc::c_char);
    return n;
}