go icon indicating copy to clipboard operation
go copied to clipboard

cmd/link: MSVC support (MSVC object + linking with MSVC)

Open ghost opened this issue 8 years ago • 226 comments

I understand that the go linker cannot currently link msvc object files and also recognize that this issue is likely to be a low priority. However, it would be nice to support this because it would somewhat simplify windows workflow. This issue is mainly to understand how much effort this would be and/or what would be required.

ghost avatar Jul 11 '17 17:07 ghost

/cc @alexbrainman

bradfitz avatar Jul 11 '17 18:07 bradfitz

@xoviat what is the problem that you are having? I need to be able to reproduce it here. So, please, provide all steps I will need to follow to reproduce this.

Thank you

Alex

PS: I won't have computer until end of July. I will have a look at this then.

alexbrainman avatar Jul 12 '17 00:07 alexbrainman

what is the problem that you are having?

I haven't tried it yet, but I would like to specifically call c functions in msvc object files by linking them as .syso with the go linker. Everything that I have read indicates that this is not possible but I will create a procedure to reproduce the specific error that occurs.

ghost avatar Jul 12 '17 00:07 ghost

specifically call c functions in msvc object files by linking them as .syso with the go linker

Have you tried building these into a DLL, and use them from inside of DLL?

I will create a procedure to reproduce the specific error that occurs.

Please, do. Thank you.

Alex

alexbrainman avatar Jul 12 '17 00:07 alexbrainman

Have you tried building these into a DLL, and use them from inside of DLL?

That was actually my original plan. I am using swig so it is not so convenient to compile the generated c code separately and then rewrite the functions as DLL exports. It's not difficult, but it is annoying when the workflow with gcc is just go generate; go build.

ghost avatar Jul 12 '17 01:07 ghost

Alright, I have a procedure. Start with these files:

hello.go:

package main

/*
	extern void hello();
*/
import "C"

func main() {
	C.hello()
}

hello.c:

#include <stdio.h>

extern void hello()
{
    printf("Hello World from C");
}

then run these commands (with msvc on path):

cl /c hello.c
mv hello.obj hello.syso
mv hello.c hello.c.bak
go build

Result: Warning: corrupt .drectve at end of def file

When running the produced file:

Exception 0xc0000005 0x8 0x13 0x13
PC=0x13
signal arrived during external code execution

main._Cfunc_hello()
        _//_obj/_cgo_gotypes.go:41 +
main.main()
        C://hello.go:9 +0x27

goroutine 17 [syscall, locked to thread]:
runtime.goexit()
        C:/Program Files/Go/src/runtime/asm_amd64.s:2197 +0x1
rax     0x4a5960
rbx     0xc042045f78
rcx     0x4a9a20
rdi     0xc042045f78
rsi     0x4adc60
rbp     0xc042045f38
rsp     0x6dfd68
r8      0xc042016340
r9      0x0
r10     0xc04204faa0
r11     0x4783c2
r12     0x0
r13     0x6
r14     0x0
r15     0xf1
rip     0x13
rflags  0x10216
cs      0x33
fs      0x53
gs      0x2b

ghost avatar Jul 13 '17 01:07 ghost

I do not have cl command installed on my pc. How do I install msvc?

Thank you.

Alex

alexbrainman avatar Jul 13 '17 03:07 alexbrainman

You need the "build tools 2017" here. Microsoft actually now allows anyone to use visual studio for free as long as it's not for commercial development. If it's too much trouble, I can just give you the object file if you want.

ghost avatar Jul 13 '17 04:07 ghost

If only c++ was not a thing, I wouldn't have to worry about this. But it is, so the pain continues...

ghost avatar Jul 13 '17 04:07 ghost

You need the "build tools 2017" here.

Got it. Thank you.

If it's too much trouble, I can just give you the object file if you want.

Yes, please, post hello.obj somewhere.

Thinking about this some more. You are actually using gcc to link object file compiled with msvc compiler. Can you try and do your exercise, but replacing "go build" step with gcc linking hello.obj to a C program? Perhaps it has been done before. I suspect, if we know how to do that, we might be able to do similar with Go.

Alex

alexbrainman avatar Jul 13 '17 05:07 alexbrainman

AFAIK lld https://github.com/llvm-mirror/lld supports msvc object files.

Object file is here: https://github.com/xoviat/msvcgo/blob/master/hello.syso

ghost avatar Jul 13 '17 05:07 ghost

lld https://github.com/llvm-mirror/lld supports msvc object files

Go uses gcc linker (not lld) on Windows.

Object file is here: https://github.com/xoviat/msvcgo/blob/master/hello.syso

I will try it when I get home in August. thank you.

Alex

alexbrainman avatar Jul 13 '17 05:07 alexbrainman

Go uses gcc linker (not lld) on Windows.

I know. But lld is the best open source documentation of msvc object format.

ghost avatar Jul 13 '17 05:07 ghost

I actually get same error from ld so the error is definitely coming from ld.

ghost avatar Jul 13 '17 05:07 ghost

I actually get same error from ld so the error is definitely coming from ld.

Yes. We need to work out how to build C program by compiling part with msvc, and linking with gcc.

Alex

alexbrainman avatar Jul 13 '17 06:07 alexbrainman

Forgive my ignorance, but what exactly gcc linking? Is it linking output of the go linker?

ghost avatar Jul 13 '17 15:07 ghost

Running objconv on the object files to convert to elf:

objconv -felf hello.obj hello.syso

We now have these errors:

hello.syso: In function `__local_stdio_printf_options':
(.text$mn+0x3): undefined reference to `?_OptionsStorage@?1??__local_stdio_printf_options@@9@9'
hello.syso: In function `_vfprintf_l':
(.text$mn+0x3a): undefined reference to `__stdio_common_vfprintf'
hello.syso: In function `printf':
(.text$mn+0x28): undefined reference to `__acrt_iob_func'
collect2.exe: error: ld returned 1 exit status

ghost avatar Jul 13 '17 18:07 ghost

Possibly stdio is off limits?

ghost avatar Jul 13 '17 18:07 ghost

Forgive my ignorance, but what exactly gcc linking? Is it linking output of the go linker?

You use 2 programs to build your Go program:

  • compiler converts your .go files (1 package at the time) into an object file stored under %GOPATH%/pkg directory;
  • linker that builds final .exe file from object files from under %GOPATH%/pkg.

Sometimes (when one of your packages uses Cgo), the Go linker calls external linker to find all bits that are implemented in C. Imagine you call printf from your C code. The C printf compiled code needs to be part of Go executable, but Go linker does not know where to get it. So Go linker calls external linker to include that code.

Current Go uses gcc compiler/linker to compile and link C code (we use mingw gcc). If you are going to compile your C code with different compiler (by Microsoft), you would have to use correspondent linker (by Microsoft) to find all external C code that the compiler created.

So, I guess, I was wrong about suggesting to use gcc linker. For general scenario, you would have to use both Microsoft compiler and linker. We would have to figure out what Microsoft linker requires as input and match that.

You might get away without MC linker, if your C code does not have any external code. Please try some really simple C program (like the one that adds 2 integers or something). That might just work as you have described above.

Alex

alexbrainman avatar Jul 26 '17 07:07 alexbrainman

Possibly stdio is off limits?

I suspect you need to call Microsoft linker to find that code.

Alex

alexbrainman avatar Jul 26 '17 07:07 alexbrainman

I don't make sure but

objconv -felf hello.obj hello.syso

Maybe, you should try to do coff or omf instead of elf?

mattn avatar Jul 26 '17 07:07 mattn

Maybe, you should try to do coff or omf instead of elf?

@xoviat yes, you should not convert .obj files to elf, Windows version of gcc generates pe/coff files just like any other Windows compiler.

Alex

alexbrainman avatar Jul 26 '17 10:07 alexbrainman

the Go linker calls external linker to find all bits that are implemented in C.

What is the specific command used? If I know the mingw command, then perhaps I can proceed down a file comparison path to try to get msvc to match what mingw is putting out.

ghost avatar Jul 26 '17 15:07 ghost

You can see the exact comment by running go build -ldflags=-v.

ianlancetaylor avatar Jul 26 '17 17:07 ianlancetaylor

Okay, so from what I can tell:

ld (link -> go.obj) + (gcc -> obj files) ==> a.out.exe

Go appears to create a temporary directory with these files. Is there any way to preserve the temporary directory so that I can inspect its contents?

ghost avatar Aug 05 '17 15:08 ghost

Try go build -work

WORK=C:\Users\mattn\AppData\Local\Temp\go-build566171254

Object files are remaining in this directory.

mattn avatar Aug 05 '17 16:08 mattn

The -work option actually won't preserve the temporary files that the linker creates. At the moment you just have to edit the linker sources to not remove the directory. We should probably add an option for that, one way or another.

ianlancetaylor avatar Aug 05 '17 17:08 ianlancetaylor

At the moment you just have to edit the linker sources to not remove the directory.

If you don't mind, I'm going to wait until this is implemented in HEAD so that I don't have to do repetitive work.

ghost avatar Aug 05 '17 22:08 ghost

Is there any way to preserve the temporary directory so that I can inspect its contents?

cmd/link program has -tmpdir flag for that. You can use it like this:

c:\Users\Alex\dev\src\a>dir
 Volume in drive C has no label.
 Volume Serial Number is 9012-A870

 Directory of c:\Users\Alex\dev\src\a

06/08/2017  02:02 PM    <DIR>          .
06/08/2017  02:02 PM    <DIR>          ..
06/08/2017  02:02 PM                77 main.go
               1 File(s)             77 bytes
               2 Dir(s)  430,809,088,000 bytes free

c:\Users\Alex\dev\src\a>type main.go
package main

import "fmt"
import "C"

func main() {
        fmt.Println("Hello")
}

c:\Users\Alex\dev\src\a>go build -o a.exe -ldflags="-tmpdir=c:\Users\Alex\dev\src\a" main.go

c:\Users\Alex\dev\src\a>dir
 Volume in drive C has no label.
 Volume Serial Number is 9012-A870

 Directory of c:\Users\Alex\dev\src\a

06/08/2017  02:02 PM    <DIR>          .
06/08/2017  02:02 PM    <DIR>          ..
06/08/2017  02:02 PM             2,055 000000.o
06/08/2017  02:02 PM            22,376 000001.o
06/08/2017  02:02 PM         2,017,382 a.exe
06/08/2017  02:02 PM               135 fix_debug_gdb_scripts.ld
06/08/2017  02:02 PM         2,402,226 go.o
06/08/2017  02:02 PM                77 main.go
06/08/2017  02:02 PM                24 trivial.c
               7 File(s)      4,444,275 bytes
               2 Dir(s)  430,804,631,552 bytes free

c:\Users\Alex\dev\src\a>

Alex

alexbrainman avatar Aug 06 '17 04:08 alexbrainman

This is just for my own reference, but this needs porting to msvc:

void
_cgo_sys_thread_start(ThreadStart *ts)
{
	uintptr_t thandle;

	thandle = _beginthread(threadentry, 0, ts);
	if(thandle == -1) {
		fprintf(stderr, "runtime: failed to create new OS thread (%d)\n", errno);
		abort();
	}
}

static void
threadentry(void *v)
{
	ThreadStart ts;

	ts = *(ThreadStart*)v;
	free(v);

	ts.g->stackhi = (uintptr)&ts;
	ts.g->stacklo = (uintptr)&ts - STACKSIZE + 8*1024;

	/*
	 * Set specific keys in thread local storage.
	 */
	__asm {
          "movq %0, %%gs:0x28\n"	// MOVL tls0, 0x28(GS)
          "movq %%gs:0x28, %%rax\n" // MOVQ 0x28(GS), tmp
          "movq %1, 0(%%rax)\n" // MOVQ g, 0(GS)
          :: "r"(ts.tls), "r"(ts.g) : "%rax"
	}

	crosscall_amd64(ts.fn);
}

I would not underestimate the time that it will take me to complete this task as I am not at all familiar with assembly.

  • [x] Understand what the assembly does
  • [x] Port to MSVC assembly
  • [x] Understand _beginthread vs CreateThread
  • [x] Switch to CreateThread

ghost avatar Aug 08 '17 20:08 ghost