[Golang][Cgo] It is possible to build go source file with c-archive with less runtime libraries?

Viewed 132

I have one question about export golang source file as c-archive file when building. For example, we have 2 files for both c and golang.

// The Entry defined in golang, and build with cgo.
extern void Entry();

int main() {
    // Entry();

    return 0;
}
package main

import "C"

//export Entry
func Entry(magic int) {
}

//#cgo CFLAGS: -nostdlib -nostdinc -fno-builtin -fno-stack-protector -m32 -Wall -Wextra -Werror

func main() {
}

For c source files, it may be compiled like below.

gcc -nostdlib -nostdinc -fno-builtin -fno-stack-protector -m32 -Wall -Wextra -Werror -c entry/main.c -o entry/main.o

For golang source files, it will be compiled like below.

go build -o entry/entry.a -buildmode=c-archive entry/entry.go

After that, we would like to link it together as below. Unfortunately, it may depend on some more symbols from libc or even more libs from cgo.

ld -T./config/link.ld -m elf_i386 entry/main.o entry/entry.a -o unicorn/kernel
ld: entry/entry.a(000010.o): in function `x_cgo_thread_start':
/_/runtime/cgo/gcc_util.c:15: undefined reference to `malloc'
ld: /_/runtime/cgo/gcc_util.c:18: undefined reference to `stderr'
ld: entry/entry.a(000010.o): in function `fprintf':
/usr/include/bits/stdio2.h:105: undefined reference to `fwrite'
ld: entry/entry.a(000010.o): in function `x_cgo_thread_start':
/_/runtime/cgo/gcc_util.c:19: undefined reference to `abort'
ld: entry/entry.a(000005.o): in function `fatalf':
/_/runtime/cgo/gcc_fatalf.c:17: undefined reference to `stderr'
ld: entry/entry.a(000005.o): in function `fprintf':
/usr/include/bits/stdio2.h:105: undefined reference to `fwrite'
ld: entry/entry.a(000005.o): in function `vfprintf':
/usr/include/bits/stdio2.h:135: undefined reference to `__vfprintf_chk'
ld: entry/entry.a(000005.o): in function `fprintf':
/usr/include/bits/stdio2.h:105: undefined reference to `fputc'
ld: entry/entry.a(000005.o): in function `fatalf':
/_/runtime/cgo/gcc_fatalf.c:22: undefined reference to `abort'
ld: unicorn/kernel: hidden symbol `__stack_chk_fail_local' isn't defined
ld: final link failed: bad value

I am not sure for now if it is possible to compile the golang source files with fewer links to libc or cgo libraries. Here is the link.ld for reference. Thank you very much.

ENTRY(start)
OUTPUT_FORMAT("elf32-i386")
SECTIONS
{
    .text 0x100000 :
    {
        code = .; _code = .; __code = .;
        *(.text)
        . = ALIGN(4096);
    }

    .data :
    {
        data = .; _data = .; __data = .;
        *(.data)
        *(.rodata)
        . = ALIGN(4096);
    }

    .bss :
    {
        bss = .; _bss = .; __bss = .;
        *(.bss)
        . = ALIGN(4096);
    }

    end = .; _end = .; __end = .;
}
0 Answers
Related