Skip to content
This repository has been archived by the owner on Aug 22, 2019. It is now read-only.

Add support for __attribute__((destructor)) #214

Closed
mrigger opened this issue Apr 29, 2016 · 0 comments
Closed

Add support for __attribute__((destructor)) #214

mrigger opened this issue Apr 29, 2016 · 0 comments

Comments

@mrigger
Copy link
Collaborator

mrigger commented Apr 29, 2016

The GNU C extensions support attributes, with which one can implement constructors and destructors for C:

#include <stdio.h>

int main() {
    puts("hello world!");
}

__attribute__((constructor))
void constr() {
    puts("constr");
}

__attribute__((destructor))
void destr() {
    puts("constr");
}

Using mx su-clang -S -emit-llvm -o test.ll test.c to compile, one gets the following bitcode:

@.str = private unnamed_addr constant [13 x i8] c"hello world!\00", align 1
@.str1 = private unnamed_addr constant [7 x i8] c"constr\00", align 1
@llvm.global_ctors = appending global [1 x { i32, void ()* }] [{ i32, void ()* } { i32 65535, void ()* @constr }]
@llvm.global_dtors = appending global [1 x { i32, void ()* }] [{ i32, void ()* } { i32 65535, void ()* @destr }]

define i32 @main() nounwind uwtable {
  %1 = call i32 @puts(i8* getelementptr inbounds ([13 x i8]* @.str, i32 0, i32 0))
  ret i32 0
}

declare i32 @puts(i8*)

define void @constr() nounwind uwtable {
  %1 = call i32 @puts(i8* getelementptr inbounds ([7 x i8]* @.str1, i32 0, i32 0))
  ret void
}

define void @destr() nounwind uwtable {
  %1 = call i32 @puts(i8* getelementptr inbounds ([7 x i8]* @.str1, i32 0, i32 0))
  ret void
}

The constructors and destructors functions are stored in variables @llvm.global_ctors and @llvm.global_dtors.

Currently, we only support constructors. A suitable beginner task would be to also add destructors based on the current constructor implementation. Also see #174 for implementation hints.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant