Skip to content

Commit

Permalink
Add -fpic and -fPIC options
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed Dec 7, 2020
1 parent c3edffb commit 86785fc
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions chibicc.h
Original file line number Diff line number Diff line change
Expand Up @@ -440,5 +440,6 @@ void hashmap_test(void);
bool file_exists(char *path);

extern StringArray include_paths;
extern bool opt_fpic;
extern bool opt_fcommon;
extern char *base_file;
15 changes: 15 additions & 0 deletions codegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,21 @@ static void gen_addr(Node *node) {
return;
}

if (opt_fpic) {
// Thread-local variable
if (node->var->is_tls) {
println(" data16 lea %s@tlsgd(%%rip), %%rdi", node->var->name);
println(" .value 0x6666");
println(" rex64");
println(" call __tls_get_addr@PLT");
return;
}

// Function or global variable
println(" mov %s@GOTPCREL(%%rip), %%rax", node->var->name);
return;
}

// Thread-local variable
if (node->var->is_tls) {
println(" mov %%fs:0, %%rax");
Expand Down
6 changes: 6 additions & 0 deletions main.c
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ typedef enum {

StringArray include_paths;
bool opt_fcommon = true;
bool opt_fpic;

static FileType opt_x;
static StringArray opt_include;
Expand Down Expand Up @@ -256,6 +257,11 @@ static void parse_args(int argc, char **argv) {
continue;
}

if (!strcmp(argv[i], "-fpic") || !strcmp(argv[i], "-fPIC")) {
opt_fpic = true;
continue;
}

if (!strcmp(argv[i], "-cc1-input")) {
base_file = argv[++i];
continue;
Expand Down
6 changes: 6 additions & 0 deletions test/driver.sh
Original file line number Diff line number Diff line change
Expand Up @@ -259,4 +259,10 @@ $chibicc -c -MD -MF $tmp/md-mf.d -I. $tmp/md2.c
grep -q -z '^md2.o:.*md2\.c .*/out2\.h' $tmp/md-mf.d
check -MD

echo 'extern int bar; int foo() { return bar; }' | $chibicc -fPIC -xc -c -o $tmp/foo.o -
cc -shared -o $tmp/foo.so $tmp/foo.o
echo 'int foo(); int bar=3; int main() { foo(); }' > $tmp/main.c
$chibicc -o $tmp/foo $tmp/main.c $tmp/foo.so
check -fPIC

echo OK

0 comments on commit 86785fc

Please sign in to comment.