Skip to content

"zig cc" doesn't work with cgo (golang) #7342

Closed

Description

@luantak

I would like to use "zig cc" for easily cross compiling cgo dependent go code, however the "drop-in" c compiler replacement doesn't work.

Example cgo code

main.go

package main

//int Add(int a, int b){
//    return a+b;
//}
import "C"
import "fmt"

func main() {
	a := C.int(10)
	b := C.int(20)
	c := C.Add(a, b)
	fmt.Println(c) // 30
}

other compilers

go build main.go //build works fine (uses gcc)
CC="clang" go build main.go //build works fine (uses clang)

zig cc

$ CC="zig cc" go build main.go
# runtime/cgo
info: Usage: zig [command] [options]

Commands:

  build            Build project from build.zig
  build-exe        Create executable from source or object files
  build-lib        Create library from source or object files
  build-obj        Create object from source or assembly
  cc               Use Zig as a drop-in C compiler
  c++              Use Zig as a drop-in C++ compiler
  env              Print lib path, std path, compiler id and version
  fmt              Parse file and render in canonical zig format
  init-exe         Initialize a `zig build` application in the cwd
  init-lib         Initialize a `zig build` library in the cwd
  libc             Display native libc paths file or validate one
  run              Create executable and run immediately
  translate-c      Convert C code to Zig code
  targets          List available compilation targets
  test             Create and run a test build
  version          Print version number and exit
  zen              Print zen of zig and exit

General Options:

  --help           Print command-specific usage

error: unknown command: -E
go version go1.15.5 linux/amd64

Activity

  1. added
    zig cc
    on Dec 8, 2020
  2. added this to the 0.8.0 milestone on Dec 8, 2020
  3. added
    downstream
    on Dec 8, 2020
  4. andrewrk commented on Dec 8, 2020

    @andrewrk
    Member

    So this looks like go is inserting flags before it passes cc. This will either need to be fixed in go, or you will have to work around this by creating a shell script like this:

    #!/bin/sh
    zig cc $@
    

    And then putting that as your CC. This way zig gets invoked with zig cc -E ... instead of zig -E ...

  5. andrewrk commented on Dec 8, 2020

    @andrewrk
    Member

    Downstream issue filed: golang/go#43078

  6. luantak commented on Dec 8, 2020

    @luantak
    Author
    #!/bin/sh
    zig cc $@
    

    This indeed works, but another weird thing is, that I get these errors:

    $ CC="zig-wrap" go build  main.go
    # runtime/cgo
    error: unable to create compilation: AccessDenied
    # runtime/cgo
    gcc_context.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_fatalf.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_libinit.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_linux_amd64.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_mmap.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_setenv.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_sigaction.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_traceback.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_util.c:1:1: error: unable to build C object: AccessDenied
    # runtime/cgo
    gcc_amd64.S:1:1: error: unable to build C object: AccessDenied
    

    Unless I use sudo, which produces a working binary:

    $ sudo CC="zig-wrap" go build  main.go                
    # command-line-arguments
    warning: unsupported linker arg: --compress-debug-sections=zlib-gnu
    
  7. andrewrk commented on Dec 8, 2020

    @andrewrk
    Member

    That error message would be more useful if it printed the path, sorry about that. Anyway that's a separate issue. Could you try using strace to find out which file paths are getting AccessDenied?

    My hunch is that it is the global cache, and go is running the compiler within a chroot or something. You can try messing with these options within your wrapper script:

      --cache-dir [path]        Override the local cache directory
      --global-cache-dir [path] Override the global cache directory
    

    Make sure they are writable paths. They are allowed to be the same.

  8. luantak commented on Dec 8, 2020

    @luantak
    Author

    strace example of what went wrong (I think, never used strace before)

    59864 openat(AT_FDCWD, "zig-cache", O_RDONLY|O_CLOEXEC|O_PATH|O_DIRECTORY)             = 5
    ...
    59864 openat(5, "h", O_RDONLY|O_CLOEXEC|O_PATH|O_DIRECTORY)             = 6
    ...
    59864 openat(6, "a1156d94bd5502d8ca9db1c6a76c576f.txt", O_RDWR|O_CREAT|O_CLOEXEC, 0666)             = -1 EACCES (Permission denied)
    
  9. luantak commented on Dec 8, 2020

    @luantak
    Author

    My hunch is that it is the global cache, and go is running the compiler within a chroot or something. You can try messing with these options within your wrapper script:

     --cache-dir [path]        Override the local cache directory
     --global-cache-dir [path] Override the global cache directory
    

    My zig cc doesn't have those options:

    error: Unknown Clang option: '--cache-dir=
    
  10. andrewrk commented on Dec 8, 2020

    @andrewrk
    Member

    Thanks, that strace output is exactly what I needed to see. This is a bit confusing - zig successfully was able to open zig-cache/o/ but then when it tried to create zig-cache/o/a1156d94bd5502d8ca9db1c6a76c576f.txt it got EACCES. When you ran the strace output, I think you might have had leftover cache artifacts from when you ran the command with sudo (never use sudo to work around an EACCES problem, you will only create more problems for yourself). Can you try this again with all the root-owned file system stuff deleted?

    My zig cc doesn't have those options:

    Ah, sorry about that. I forgot this was the zig cc CLI not the regular zig CLI. I'll need to introduce environment variables to control those paths when using zig cc.

    I'll look into this myself and see if I can get it working. Thanks for your help.

  11. luantak commented on Dec 8, 2020

    @luantak
    Author

    Can you try this again with all the root-owned file system stuff deleted?

    Then it's just:

    62606 mkdirat(AT_FDCWD, "zig-cache", 0755 = -1 EACCES (Permission denied)
    

    This is because the permissions of /usr/lib/go/src/runtime/cgo are restricted to root access:

    Access: (0755/drwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
    
  12. andrewrk commented on Dec 8, 2020

    @andrewrk
    Member

    Thanks - I'll look into a solution for this. I'm not sure why Go is preventing Zig from using a project-local directory as a cache folder. That seems like a reasonable thing for a compiler to do. But I'll add support for configuring the cache directory via an environment variable so that it can be modified when using zig cc.

  13. luantak commented on Dec 8, 2020

    @luantak
    Author

    It's not because of a project local cache folder, it's because zig tries to create a directory inside a stdlib package.

  14. luantak commented on Dec 8, 2020

    @luantak
    Author

    I think zig cc should put all caches inside --global-cache-dir.

  15. andrewrk commented on Dec 8, 2020

    @andrewrk
    Member

    After 2759313 (which I just pushed to master) and the following zcc script:

    #!/bin/sh
    ZIG_LOCAL_CACHE_DIR="$HOME/misc/gozig" zig cc $@

    (where $HOME/misc/gozig is my project path)

    It produced a viable binary.

    [nix-shell:~/misc/gozig]$ ./main 
    30
    

    It gave the following harmless linker warning:

    warning: unsupported linker arg: --compress-debug-sections=zlib-gnu
    

    You could also try passing /tmp or any other writable directory for that value.

  16. 18 remaining items

  17. andrewrk commented on Dec 10, 2020

    @andrewrk
    Member

    I solved the cache directory issue with f7d6006.

    Until https://golang.org/cl/276412 lands, zig can be used with cgo using a wrapper script, as demonstrated in #7342 (comment).

    After that go patch lands, zig can be used with cgo without a wrapper, as demonstrated in #7342 (comment)

    Feel free to discuss the topic further.

  18. added a commit that references this issue on Dec 11, 2020
    21236c0
  19. modified the milestones: 0.8.0, 0.7.1 on Dec 11, 2020
  20. andrewrk commented on Dec 11, 2020

    @andrewrk
    Member

    I cherry-picked the new cache directory logic so that it will be available in the upcoming 0.7.1 release: 21236c0

  21. added a commit that references this issue on Jan 4, 2021
    5272bed
  22. dosgo commented on Aug 19, 2021

    @dosgo

    I developed a small tool to automatically judge the compilation target based on the GOOS GOARCH environment.
    github.com/dosgo/zigtool

  23. krumberg commented on Aug 29, 2021

    @krumberg

    I developed a small tool to automatically judge the compilation target based on the GOOS GOARCH environment.
    github.com/dosgo/zigtool

    Thanks a lot for this!

  24. JohnDDuncanIII commented on Sep 13, 2021

    @JohnDDuncanIII
  25. akkuman commented on Jan 19, 2022

    @akkuman

    @andrewrk

    When I cross compile from linux to macos, compile error

    cat $HOME/.bin/zcc
    #!/bin/sh
    ZIG_LOCAL_CACHE_DIR="$HOME/tmp" zig cc -target x86_64-macos-gnu
    
    cat $HOME/.bin/zxx
    #!/bin/sh
    ZIG_LOCAL_CACHE_DIR="$HOME/tmp" zig c++ -target x86_64-macos-gnu
    

    error

    # github.com/akkuman/rotateproxy/cmd/rotateproxy
    /opt/hostedtoolcache/go/1.17.6/x64/pkg/tool/linux_amd64/link: running zcc failed: exit status 1
    warning: unsupported linker arg: -S
    warning: unsupported linker arg: -no_pie
    warning: unsupported linker arg: -pagezero_size
    warning: unsupported linker arg: 4000000
    warning: unsupported linker arg: --compress-debug-sections
    warning: unsupported linker arg: zlib-gnu
    warning(link): framework not found for '-framework CoreFoundation'
    warning(link): framework not found for '-framework Security'
    warning(link): Framework search paths:
    error(link): undefined reference to symbol '_SecTrustSettingsCopyTrustSettings'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_SecTrustSettingsCopyCertificates'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_SecPolicyCopyProperties'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_SecItemExport'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFStringCreateWithBytes'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFRelease'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFNumberGetValue'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFEqual'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFDictionaryGetValueIfPresent'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFDataGetLength'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFDataGetBytePtr'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFArrayGetValueAtIndex'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error(link): undefined reference to symbol '_CFArrayGetCount'
    error(link):   first referenced in '/tmp/go-link-800811870/go.o'
    error: UndefinedSymbolReference
    

    see https://github.com/akkuman/rotateproxy/runs/4863624753?check_suite_focus=true

  26. ostcar commented on Jul 9, 2024

    @ostcar

    After reading this, I am not sure, what the current status is. Should it be possible to use cgo with zig without a wrapper script now?

    I was able to cross compile a go app from linux to macos without a wrapper script using zig 0.11.0. But it stopped working with zig 0.12.0 or 0.13.0. I get the error:

    # runtime/cgo
    error: unable to create compilation: AccessDenied
    

    The command I am running (that works with zig 0.11.0) is:

    GOOS=darwin GOARCH=amd64 CC="zig cc -target x86_64-macos" CGO_ENABLED=1 go build -C host -buildmode c-archive -o ../platform/macos-x64.a
    

    Should this work with newer versions of zig? Should I create a separate issue for that?

  27. kristoff-it commented on Jul 18, 2024

    @kristoff-it
    Member

    @ostcar yes it should work with Go >= 1.18, please open a separate issue.

  28. ostcar commented on Jul 20, 2024

    @ostcar

    @ostcar yes it should work with Go >= 1.18, please open a separate issue.

    Thanks. I created a new issue: #20689

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    downstreamzig cc

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions