bazel icon indicating copy to clipboard operation
bazel copied to clipboard

Building Objective-C code on non-OS X platforms

Open ivucica opened this issue 9 years ago • 17 comments

Please provide the following information. The more we know about your system and use case, the more easily and likely we can help.

Description of the problem / feature request / question:

I should be able to trivially build Objective-C code on non-OS X platforms.

Specifically, I'm a contributor to GNUstep which runs on various UNIX-like platforms (various Linuxen, BSDs) and on Windows.

  • There's compiler support for Objective-C in both Clang and GCC.
  • GNUstep uses its own Make-based build system to build its various libraries.
  • Basic Objective-C runtime library used on GNUstep systems is libobjc2, required before anything else is built, is CMake based and uses a mixture of C, assembly and Objective-C. (One could use GCC's runtime, but it's got far less features. And one still runs into the problems when trying to compile even the most elementary of the libraries, gnustep-base.)

I've began work on rules to build libobjc2 and I immediately ran into problems.

  • objc_library() and friends are written to build only OS X / iOS code. They try to
  • cc_library() prevents you from using .m files as inputs

A horrible workaround is to use a genrule to copy .m files into .m.c files, then use cc_library() together with copts = ["-x", "objective-c"].

Problem arises when the existing .c code cannot be built as Objective-C, but the codebase depends on having .c and .m files linked in the same step. I've tried to separate all .m code into one rule, and link it with .c code as a dependency, but this is not working out. Sometimes this stuff can't be easily worked around; trying to do so with libobjc2 is only causing me pain.

(This stuff, by the way, applies to Objective-C++ as well, with .mm extension.)

What to do about it?

Easiest fix would be to support .m code directly in native cc_*() rules. Compilers should already detect this as -x objective-c, but it can't be harmful to pass this in as well. I see no reason why native cc_*() rules would not support compiling a module that is otherwise supported by the underlying compilers. (I could probably submit a PR or CL for this.)

Another fix would be to make objc_*() rules less OS X/iOS specific.

I'd also also be happy with an outcome where I can, in a supported fashion, write a Skylark rule which separately generates actions for compile and link, and lets me compile C files as C, Objective-C as Objective-C, C++ as C++ and Objective-C++ as Objective-C++.

cc1obj problem

(On a separate note, it'd be pretty cool if the stock crosstool file would reference GCC correctly so it can find the cc1obj tool.)

gcc: error trying to exec 'cc1obj': execvp: No such file or directory

If possible, provide a minimal example to reproduce the problem:

BUILD

# -*- Python -*-

genrule(
    name = "trick-ccbinary",
    srcs = glob(["*.m"]),
    outs = [i + ".c" for i in glob(["*.m"])],
    cmd = "for i in $(SRCS); do cp $$i $(GENDIR)/$$i.c; done",
)


objc_binary(
    name = "try",
    srcs = ["try.m"],
)


cc_binary(
    name = "try_c",
    srcs = ["try.m.c"],
    copts = ["-x", "objective-c"],
)

try.m

@interface Hello
+ (void) world;
@end
@implementation Hello
+ (void) world {}
@end

int main() {}

crosstool/CROSSTOOL

This lets me use locally-installed clang as the compiler.

major_version: "local"
minor_version: ""
default_target_cpu: "same_as_host"

default_toolchain {
  cpu: "k8"
  toolchain_identifier: "local_clang"
}

toolchain {
  abi_version: "local"
  abi_libc_version: "local"
  builtin_sysroot: ""
  compiler: "clang"
  host_system_name: "local"
  needsPic: true
  supports_gold_linker: false
  supports_incremental_linker: false
  supports_fission: false
  supports_interface_shared_objects: false
  supports_normalizing_ar: false
  supports_start_end_lib: false
  supports_thin_archives: false
  target_libc: "local"
  target_cpu: "local"
  target_system_name: "local"
  toolchain_identifier: "local_clang"

  tool_path { name: "ar" path: "/usr/bin/ar" }
  tool_path { name: "compat-ld" path: "/usr/bin/ld" }
  tool_path { name: "cpp" path: "/usr/bin/cpp" }
  tool_path { name: "dwp" path: "/usr/bin/dwp" }
  tool_path { name: "gcc" path: "/usr/bin/clang" }
  cxx_flag: "-std=c++0x"
  linker_flag: "-lstdc++"
  linker_flag: "-B/usr/bin/"

  # TODO(bazel-team): In theory, the path here ought to exactly match the path
  # used by gcc. That works because bazel currently doesn't track files at
  # absolute locations and has no remote execution, yet. However, this will need
  # to be fixed, maybe with auto-detection?
  cxx_builtin_include_directory: "/usr/lib/gcc/"  # [ivucica] needed by clang as well
  cxx_builtin_include_directory: "/usr/lib/clang/" # [ivucica]
  cxx_builtin_include_directory: "/usr/local/include"
  cxx_builtin_include_directory: "/usr/include"
  tool_path { name: "gcov" path: "/usr/bin/gcov" }

  # C(++) compiles invoke the compiler (as that is the one knowing where
  # to find libraries), but we provide LD so other rules can invoke the linker.
  tool_path { name: "ld" path: "/usr/bin/ld" }

  tool_path { name: "nm" path: "/usr/bin/nm" }
  tool_path { name: "objcopy" path: "/usr/bin/objcopy" }
  objcopy_embed_flag: "-I"
  objcopy_embed_flag: "binary"
  tool_path { name: "objdump" path: "/usr/bin/objdump" }
  tool_path { name: "strip" path: "/usr/bin/strip" }

  # Anticipated future default.
  unfiltered_cxx_flag: "-no-canonical-prefixes"
  #unfiltered_cxx_flag: "-fno-canonical-system-headers" # [ivucica] not in clang :(

  # Make C++ compilation deterministic. Use linkstamping instead of these
  # compiler symbols.
  unfiltered_cxx_flag: "-Wno-builtin-macro-redefined"
  unfiltered_cxx_flag: "-D__DATE__=\"redacted\""
  unfiltered_cxx_flag: "-D__TIMESTAMP__=\"redacted\""
  unfiltered_cxx_flag: "-D__TIME__=\"redacted\""

  # Security hardening on by default.
  # Conservative choice; -D_FORTIFY_SOURCE=2 may be unsafe in some cases.
  # We need to undef it before redefining it as some distributions now have
  # it enabled by default.
  compiler_flag: "-U_FORTIFY_SOURCE"
  compiler_flag: "-D_FORTIFY_SOURCE=1"
  compiler_flag: "-fstack-protector"
  linker_flag: "-Wl,-z,relro,-z,now"

  # Enable coloring even if there's no attached terminal. Bazel removes the
  # escape sequences if --nocolor is specified. This isn't supported by gcc
  # on Ubuntu 14.04.
  # compiler_flag: "-fcolor-diagnostics"

  # All warnings are enabled. Maybe enable -Werror as well?
  compiler_flag: "-Wall"
  # Enable a few more warnings that aren't part of -Wall.
  #compiler_flag: "-Wunused-but-set-parameter"
  compiler_flag: "-Wunused-parameter"  # [ivucica] clang version
  # But disable some that are problematic.
  compiler_flag: "-Wno-free-nonheap-object" # has false positives

  # Keep stack frames for debugging, even in opt mode.
  compiler_flag: "-fno-omit-frame-pointer"

  # Anticipated future default.
  linker_flag: "-no-canonical-prefixes"
  # Have gcc return the exit code from ld.
  #linker_flag: "-pass-exit-codes" # [ivucica] not in clang 3.4.1
  # Stamp the binary with a unique identifier.
  linker_flag: "-Wl,--build-id=md5"
  linker_flag: "-Wl,--hash-style=gnu"
  # Gold linker only? Can we enable this by default?
  # linker_flag: "-Wl,--warn-execstack"
  # linker_flag: "-Wl,--detect-odr-violations"

  compilation_mode_flags {
    mode: DBG
    # Enable debug symbols.
    compiler_flag: "-g"
  }
  compilation_mode_flags {
    mode: OPT

    # No debug symbols.
    # Maybe we should enable https://gcc.gnu.org/wiki/DebugFission for opt or
    # even generally? However, that can't happen here, as it requires special
    # handling in Bazel.
    compiler_flag: "-g0"

    # Conservative choice for -O
    # -O3 can increase binary size and even slow down the resulting binaries.
    # Profile first and / or use FDO if you need better performance than this.
    compiler_flag: "-O2"

    # Disable assertions
    compiler_flag: "-DNDEBUG"

    # Removal of unused code and data at link time (can this increase binary size in some cases?).
    compiler_flag: "-ffunction-sections"
    compiler_flag: "-fdata-sections"
    linker_flag: "-Wl,--gc-sections"
  }
  linking_mode_flags { mode: DYNAMIC }
}

crosstool/BUILD

# -*- Python -*-

# for clang
filegroup(
    name = "toolchain",
    srcs = ["//external:cc_toolchain"],
)

filegroup(
    name = "empty",
    srcs = [],
)

cc_toolchain_suite(
    name = "default-toolchain",
    toolchains = {
        "local|clang": ":cc-compiler-local-clang",
    },
)

cc_toolchain(
    name = "cc-compiler-local-clang",
    all_files = ":empty",
    compiler_files = ":empty",
    cpu = "local",
    dwp_files = ":empty",
    dynamic_runtime_libs = [":empty"],
    linker_files = ":empty",
    objcopy_files = ":empty",
    static_runtime_libs = [":empty"],
    strip_files = ":empty",
    supports_param_files = 1,
    visibility = ["//visibility:public"],
)

execution: objc_binary() is broken on Linux

$ bazel build --crosstool_top=//crosstool:default-toolchain  :try
INFO: Reading 'startup' options from /home/ivucica/.bazelrc: --host_jvm_args=-Dbazel.DigestFunction=SHA1
INFO: Analysed target //:try.
INFO: Found 1 target...
ERROR: /home/ivucica/projects/test-bazel-objc/BUILD:11:1: output '_objs/try/try.o' was not created
ERROR: /home/ivucica/projects/test-bazel-objc/BUILD:11:1: output '_objs/try/try.d' was not created
ERROR: /home/ivucica/projects/test-bazel-objc/BUILD:11:1: not all outputs were created or valid
ERROR: /home/ivucica/projects/test-bazel-objc/BUILD:11:1: output 'plists/try-environment.plist' was not created
Target //:try failed to build
INFO: Elapsed time: 0.369s, Critical Path: 0.11s
FAILED: Build did NOT complete successfully

Execution: cc_binary() builds correctly

Note that, because libobjc2 is missing and not declared as a dependency, the errors such as lack of __objc_exec_class are expected. This would be resolved by providing a Skylark wrapper (e.g. gs_objc_binary and gs_objc_library).

$ bazel build --crosstool_top=//crosstool:default-toolchain  :try_c
INFO: Reading 'startup' options from /home/ivucica/.bazelrc: --host_jvm_args=-Dbazel.DigestFunction=SHA1
INFO: Analysed target //:try_c.
INFO: Found 1 target...
INFO: From Compiling try.m.c:
warning: unknown warning option '-Wno-free-nonheap-object'; did you mean '-Wno-sequence-point'? [-Wunknown-warning-option]
bazel-out/local_clang-fastbuild/genfiles/try.m.c:1:12: warning: class 'Hello' defined without specifying a base class [-Wobjc-root-class]
@interface Hello
           ^
bazel-out/local_clang-fastbuild/genfiles/try.m.c:1:17: note: add a super class to fix this problem
@interface Hello
                ^
2 warnings generated.
ERROR: /home/ivucica/projects/test-bazel-objc/BUILD:17:1: Linking of rule '//:try_c' failed: linux-sandbox failed: error executing command 
  (cd /home/ivucica/.cache/bazel/_bazel_ivucica/621cee260830f1100121dd48cb3d2f1f/bazel-sandbox/04bb9734-6291-4322-bf78-f923e70ccf4e-1/execroot/test-bazel-objc && \
  exec env - \
  /home/ivucica/.cache/bazel/_bazel_ivucica/621cee260830f1100121dd48cb3d2f1f/execroot/test-bazel-objc/_bin/linux-sandbox @/home/ivucica/.cache/bazel/_bazel_ivucica/621cee260830f1100121dd48cb3d2f1f/bazel-sandbox/04bb9734-6291-4322-bf78-f923e70ccf4e-1/linux-sandbox.params -- /usr/bin/clang -o bazel-out/local_clang-fastbuild/bin/try_c -B/usr/bin/ -Wl,-z,relro,-z,now -no-canonical-prefixes '-Wl,--build-id=md5' '-Wl,--hash-style=gnu' -Wl,-S -Wl,@bazel-out/local_clang-fastbuild/bin/try_c-2.params)
bazel-out/local_clang-fastbuild/bin/_objs/try_c/try.m.pic.o: In function `.objc_load_function':
bazel-out/local_clang-fastbuild/genfiles/try.m.c:(.text+0x2e): undefined reference to `__objc_exec_class'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Target //:try_c failed to build
INFO: Elapsed time: 0.631s, Critical Path: 0.43s
FAILED: Build did NOT complete successfully

Environment info

  • Operating System: Debian testing/unstable mix

  • Bazel version (output of bazel info release): 0.4.3

Have you found anything relevant by searching the web? (e.g. GitHub issues, email threads in the [email protected] archive)

I did a cursory search of issues on Github.

Anything else, information or logs or outputs that would be helpful?

(If they are large, please upload as attachment or provide link).

ivucica avatar Jan 25 '17 13:01 ivucica

Thanks for a greatly detailed and complete feature request! Adding all interested parties I know of.

laszlocsomor avatar Jan 25 '17 14:01 laszlocsomor

Thanks for the very detailed feature request! You'll be happy to hear (I hope) that we've been working on making this possible, by using a crosstool configurable toolchain in Objc rules. You can check out ExperimentalObjcLibrary to see roughly how this will work. Compilation is mostly supported already and we're implementing linking right now. I've assigned this request to calpeyser, he can update the issue with any flags you can use to enable the new functionality.

aragos avatar Jan 25 '17 14:01 aragos

Now that's a very welcome reply! Thank you! This has been bothering me for months.

I'm happy to test anything you throw my way against my work on libobjc2. If I can get libobjc2 working, I hope to get work on gnustep-base underway.

However, a cursory look at ExperimentalObjcLibrary presents mentions of Xcode (and a lot of them!). There is no Xcode on most platforms supported by GNUstep (or ObjFW or other Objective-C-based frameworks). Are you sure this is what I'm looking for?

All I need is the equivalent of cc_library() which supports .m and .mm extensions (and mixing them with .c, .cc and the usual variants). Just patching cc_library() will do as well.

ivucica avatar Jan 25 '17 17:01 ivucica

Any activity here?

Would there be some desire to have a mini-hackathon to get Objective-C to build acceptably with Bazel? Perhaps with a stretch goal of having libobjc2 (runtime) + gnustep-base (Foundation), or even gnustep-gui (AppKit), build with Bazel?

ivucica avatar May 17 '17 11:05 ivucica

+1 Also interested in cc_library with .m / .mm...

jgavris avatar May 19 '17 20:05 jgavris

Friendly ping.

Anything I can do to help out here? What would be the first step for me to do this?

With current objc_library, how do I make Bazel not run xcrunwrapper or define APPLE_SDK_{PLATFORM,VERSION_OVERRIDE} on Linux? I just need it to run clang and I need it to not pass the -F flags.

Or are we giving up on using objc_* and do we want to adapt cc_library instead, as one of the options I proposed?

ivucica avatar Jun 20 '17 20:06 ivucica

Hey - thanks so much for your patience.

An update: Setting --experimental_objc_crosstool=all will cause all compiling and linking actions arising from an objc_*/ios_* target to use the CROSSTOOL file to generate command lines. That is, the hardcoded, xcode/iOS-specific logic in the objc rules (particularly, in LegacyCompilationSupport.java) will no longer be used.

I haven't given much thought building objc for Linux. However, the complexity should, in principle, be restricted to writing a CROSSTOOL file that defines command lines that simply call clang.

So, for first steps, I think you should have a look at our CROSSTOOL at [1], and edit the features and action_configs to reflect the command line that you expect for a Linux build. For example, "wrapped_clang" [2], which is the given tool for the "objc-compile" action_config, should likely not call xcrunwrapper.sh, and should instead simply call clang.

Suppose you have a new crosstool at //custom:crosstool. Then test:

blaze build //my/objc/target --apple_crosstool_top=//custom:crosstool --crosstool_top=//custom_crosstool --apple_crosstool_transition --experimental_objc_crosstool=all

We'll be cleaning up that mess of flags shortly.

[1] https://github.com/bazelbuild/bazel/blob/master/tools/osx/crosstool/CROSSTOOL.tpl [2] https://github.com/bazelbuild/bazel/blob/master/tools/osx/crosstool/wrapped_clang.tpl

calpeyser avatar Jun 27 '17 13:06 calpeyser

Oh, wow, that crosstool file is very verbose. :smile_cat:

Interestingly, I took my old work on building libobjc2 and something in the build environment or in Bazel itself now helped it work using the above described, hacky approach. This is extra inspiring, and I'll be taking a look at using apple_crosstool_top as well.

Sidenote: If this turns out to work fine, can the flags et al be renamed into something that doesn't directly relate to a particular company? Is it worth opening a new bug about it?

ivucica avatar Jun 27 '17 16:06 ivucica

@mhlopko Commit e3312d9 noted. I may play with ObjC-on-Bazel-on-Linux this weekend.

ivucica avatar Jul 07 '17 09:07 ivucica

Also interested in this feature. It would be great to have some documentation on how setup a computer to build a project with j2objc and GNUStep too. Thank you very much!

System25 avatar Nov 10 '17 08:11 System25

tl;dr I've run into this:

ERROR: /......../bazel-hello/objc/BUILD:1:1: in objc_library rule //objc:lib: Expected action_config for 'objc-compile' to be configured
ERROR: Analysis of target '//objc:objc' failed; build aborted: Analysis of target '//objc:lib' failed; build aborted
INFO: Elapsed time: 1.689s
FAILED: Build did NOT complete successfully (0 packages loaded)

First goal: get Bazel to invoke a functional equivalent clang inputfile.m -c -o inputfile.o

Current attempt:

  1. I've tried copying the tools/cpp/CROSSTOOL as shipped inside my locally installed Bazel binary (i.e. I took it from ~/.cache/bazel). I took tools/osx/crosstool/CROSSTOOL.tpl from the same path as my reference material.

  2. I then duplicated the toolchain with identifier local_linux and replaced tool_path { name: "gcc" path: "/usr/bin/gcc" } to refer to a clang binary. I set toolchain_identifier to "local_linux_clang". I changed default toolchain to local_linux_clang. I had to change the CPU from local to k8 in a bunch of places.

  3. I omitted adding any feature {} proto fields for now, as I have a feeling they are not needed immediately. (Later it'd be nice to figure out how to pass -x objective-c, too).

  4. I added this to the toolchain:

    action_config {
      config_name: "objc_config"
      action_name: "objc_config"
      tool {
        tool_path: "gcc"
      }
    }
    
  5. This is my //objc/crosstool:BUILD:

    # for clang
    filegroup(
        name = "toolchain",
        srcs = ["//external:cc_toolchain"],
    )
    
    filegroup(
        name = "empty",
        srcs = [],
    )
    
    cc_toolchain_suite(
        name = "default-toolchain",
        toolchains = {
            "k8|clang": ":cc-compiler-local-clang", # TODO: this should be local|clang instead of k8|clang
        },
    )
    
    cc_toolchain(
        name = "cc-compiler-local-clang",
        all_files = ":empty",
        compiler_files = ":empty",
        cpu = "k8", #"local",
        dwp_files = ":empty",
        dynamic_runtime_libs = [":empty"],
        linker_files = ":empty",
        objcopy_files = ":empty",
        static_runtime_libs = [":empty"],
        strip_files = ":empty",
        supports_param_files = 1,
        visibility = ["//visibility:public"],
    )
    
  6. BUILDfile for the binary (the .m uses no ObjC features at this time, to avoid the problem of the missing runtime in case the whole thing would work):

    objc_library(
        name = "lib",
        srcs = ["main.m"],
    )
    cc_binary(
        name = "objc",
        deps = [":lib"],
    )
    
  7. This is how I tried building this:

    bazel build --crosstool_top=//objc/crosstool:default-toolchain --compiler clang --cpu k8  //objc:objc
    

ivucica avatar Mar 20 '18 17:03 ivucica

@calpeyser suggested using --apple_crosstool_top and optionally --ios_multi_cpus=k8. This necessitated creating a toolchain for the ios_k8 CPU. In this scenario, compiler is statically set to be compiler.

Therefore I added a toolchain with key ios_k8|compiler to the BUILD file, and target_cpu: "ios_k8"+compiler: "compiler"toolchain in the CROSSTOOL file.

This results in:

Unhandled exception thrown during build; message: Unrecoverable error while evaluating node '//objc:lib com.google.devtools.build.lib.skyframe.BuildConfigurationValue$Key@23e2fdef false (1684575854)' (requested by nodes '//objc:objc com.google.devtools.build.lib.skyframe.BuildConfigurationValue$Key@72cc162e false (1441728394)')
INFO: Elapsed time: 1.232s
FAILED: Build did NOT complete successfully (16 packages loaded)
java.lang.RuntimeException: Unrecoverable error while evaluating node '//objc:lib com.google.devtools.build.lib.skyframe.BuildConfigurationValue$Key@23e2fdef false (1684575854)' (requested by nodes '//objc:objc com.google.devtools.build.lib.skyframe.BuildConfigurationValue$Key@72cc162e false (1441728394)')
	at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:414)
	at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:355)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: No supported apple platform registered for target cpu ios_k8
	at com.google.devtools.build.lib.rules.apple.ApplePlatform.forTargetCpu(ApplePlatform.java:218)
	at com.google.devtools.build.lib.rules.apple.ApplePlatform.forTarget(ApplePlatform.java:204)
	at com.google.devtools.build.lib.rules.apple.AppleConfiguration.getSingleArchPlatform(AppleConfiguration.java:287)
	at com.google.devtools.build.lib.rules.objc.ObjcVariablesExtension.addFrameworkVariables(ObjcVariablesExtension.java:171)
	at com.google.devtools.build.lib.rules.objc.ObjcVariablesExtension.addVariables(ObjcVariablesExtension.java:133)
	at com.google.devtools.build.lib.rules.cpp.CppModel.setupCompileBuildVariables(CppModel.java:700)
	at com.google.devtools.build.lib.rules.cpp.CppModel.createSourceAction(CppModel.java:1090)
	at com.google.devtools.build.lib.rules.cpp.CppModel.createCcCompileActions(CppModel.java:775)
	at com.google.devtools.build.lib.rules.cpp.CcLibraryHelper.compile(CcLibraryHelper.java:1043)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.compile(CompilationSupport.java:368)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.ccCompileAndLink(CompilationSupport.java:402)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.registerCompileAndArchiveActions(CompilationSupport.java:1088)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.registerCompileAndArchiveActions(CompilationSupport.java:1132)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.registerCompileAndArchiveActions(CompilationSupport.java:924)
	at com.google.devtools.build.lib.rules.objc.ObjcLibrary.create(ObjcLibrary.java:77)
	at com.google.devtools.build.lib.rules.objc.ObjcLibrary.create(ObjcLibrary.java:34)
	at com.google.devtools.build.lib.analysis.ConfiguredTargetFactory.createRule(ConfiguredTargetFactory.java:364)
	at com.google.devtools.build.lib.analysis.ConfiguredTargetFactory.createConfiguredTarget(ConfiguredTargetFactory.java:240)
	at com.google.devtools.build.lib.skyframe.SkyframeBuildView.createConfiguredTarget(SkyframeBuildView.java:517)
	at com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction.createConfiguredTarget(ConfiguredTargetFunction.java:699)
	at com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction.compute(ConfiguredTargetFunction.java:278)
	at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:340)
	... 4 more
java.lang.RuntimeException: Unrecoverable error while evaluating node '//objc:lib com.google.devtools.build.lib.skyframe.BuildConfigurationValue$Key@23e2fdef false (1684575854)' (requested by nodes '//objc:objc com.google.devtools.build.lib.skyframe.BuildConfigurationValue$Key@72cc162e false (1441728394)')
	at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:414)
	at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:355)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: No supported apple platform registered for target cpu ios_k8
	at com.google.devtools.build.lib.rules.apple.ApplePlatform.forTargetCpu(ApplePlatform.java:218)
	at com.google.devtools.build.lib.rules.apple.ApplePlatform.forTarget(ApplePlatform.java:204)
	at com.google.devtools.build.lib.rules.apple.AppleConfiguration.getSingleArchPlatform(AppleConfiguration.java:287)
	at com.google.devtools.build.lib.rules.objc.ObjcVariablesExtension.addFrameworkVariables(ObjcVariablesExtension.java:171)
	at com.google.devtools.build.lib.rules.objc.ObjcVariablesExtension.addVariables(ObjcVariablesExtension.java:133)
	at com.google.devtools.build.lib.rules.cpp.CppModel.setupCompileBuildVariables(CppModel.java:700)
	at com.google.devtools.build.lib.rules.cpp.CppModel.createSourceAction(CppModel.java:1090)
	at com.google.devtools.build.lib.rules.cpp.CppModel.createCcCompileActions(CppModel.java:775)
	at com.google.devtools.build.lib.rules.cpp.CcLibraryHelper.compile(CcLibraryHelper.java:1043)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.compile(CompilationSupport.java:368)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.ccCompileAndLink(CompilationSupport.java:402)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.registerCompileAndArchiveActions(CompilationSupport.java:1088)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.registerCompileAndArchiveActions(CompilationSupport.java:1132)
	at com.google.devtools.build.lib.rules.objc.CompilationSupport.registerCompileAndArchiveActions(CompilationSupport.java:924)
	at com.google.devtools.build.lib.rules.objc.ObjcLibrary.create(ObjcLibrary.java:77)
	at com.google.devtools.build.lib.rules.objc.ObjcLibrary.create(ObjcLibrary.java:34)
	at com.google.devtools.build.lib.analysis.ConfiguredTargetFactory.createRule(ConfiguredTargetFactory.java:364)
	at com.google.devtools.build.lib.analysis.ConfiguredTargetFactory.createConfiguredTarget(ConfiguredTargetFactory.java:240)
	at com.google.devtools.build.lib.skyframe.SkyframeBuildView.createConfiguredTarget(SkyframeBuildView.java:517)
	at com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction.createConfiguredTarget(ConfiguredTargetFunction.java:699)
	at com.google.devtools.build.lib.skyframe.ConfiguredTargetFunction.compute(ConfiguredTargetFunction.java:278)
	at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:340)
	... 4 more

Available in ivucica/bazel-hello@c1f9d72c2b1c74b8880a80228263ccad0e544d39


I have then attempted to replace k8 with x86_64 in everything fake-"iOS"-related. This gets me a bit further:

ERROR: /home/ivucica/projects/bazel-hello/objc/BUILD:1:1: in objc_library rule //objc:lib: Expected action_config for 'objc-archive' to be configured
ERROR: /home/ivucica/projects/bazel-hello/objc/BUILD:1:1: in objc_library rule //objc:lib: Expected action_config for 'c++-link-dynamic-library' to be configured
ERROR: /home/ivucica/projects/bazel-hello/objc/BUILD:1:1: in objc_library rule //objc:lib: Expected action_config for 'objc-fully-link' to be configured
ERROR: Analysis of target '//objc:objc' failed; build aborted: Analysis of target '//objc:lib' failed; build aborted
INFO: Elapsed time: 0.714s
FAILED: Build did NOT complete successfully (11 packages loaded)

Now I defined these three actions; while objc-archive and objc-fully-link give me no trouble, c++-link-dynamic-library is suddenly not unconfigured, instead it's overly-configured, it seems:

ERROR: Invalid toolchain configuration: multiple action configs for action 'c++-link-dynamic-library'
ERROR: Analysis of target '//objc:objc' failed; build aborted: Invalid toolchain configuration: multiple action configs for action 'c++-link-dynamic-library'
INFO: Elapsed time: 0.176s
FAILED: Build did NOT complete successfully (1 packages loaded)

Available in ivucica/bazel-hello@897b0ad49b23917a8629a59a9160895d3cb039e4 (which also contains unrelated and irrelevant change to make host and target platform of the fake-"iOS"-toolchain to be "local").

I'm stumped once more.

Clearly there is still a lot of unfortunate entanglement between objc_ rules and Apple platforms :(

ivucica avatar Mar 20 '18 22:03 ivucica

I ran into this being an issue when I was trying to use GLFW to build a C++ application that can compile for macOS and Linux. It turns out that they swap out .c and .m files in their CMake build depending on the platform.

https://github.com/glfw/glfw/blob/781fbbadb0bccc749058177b1385c82da9ace880/src/CMakeLists.txt#L7-L25:

if (_GLFW_COCOA)
    target_sources(glfw PRIVATE cocoa_platform.h cocoa_joystick.h posix_thread.h
                                nsgl_context.h egl_context.h osmesa_context.h
                                cocoa_init.m cocoa_joystick.m cocoa_monitor.m
                                cocoa_window.m cocoa_time.c posix_thread.c
                                nsgl_context.m egl_context.c osmesa_context.c)
elseif (_GLFW_WIN32)
    target_sources(glfw PRIVATE win32_platform.h win32_joystick.h wgl_context.h
                                egl_context.h osmesa_context.h win32_init.c
                                win32_joystick.c win32_monitor.c win32_time.c
                                win32_thread.c win32_window.c wgl_context.c
                                egl_context.c osmesa_context.c)
elseif (_GLFW_X11)
    target_sources(glfw PRIVATE x11_platform.h xkb_unicode.h posix_time.h
                                posix_thread.h glx_context.h egl_context.h
                                osmesa_context.h x11_init.c x11_monitor.c
                                x11_window.c xkb_unicode.c posix_time.c
                                posix_thread.c glx_context.c egl_context.c
                                osmesa_context.c)

I got around this with a horrendous set of hacks related to the aforementioned "suggestion" of using a genrule that adds .c to all of the .m files. I think I'm going about this the wrong way, trying to use cc_library for everything, but I'm curious if this use case is interesting to bazel devs.

wolfd avatar Dec 31 '19 05:12 wolfd

AFAIK @calpeyser no longer works on Bazel, so I'll mark this as "untriaged".

laszlocsomor avatar Jan 02 '20 07:01 laszlocsomor

Despite this feature sounding like an "Apple request", I believe this is a request for the C rules and all of their machinery. Why? Because this request actually wants to strip out the Apple-related bits from ObjC compilation :) And because... well, we won't be able to get to this in team-Apple. Moving over there.

jmmv avatar Jan 09 '20 16:01 jmmv

ping on this issue...

is google open to enabling mm compilation in a cc_ rule context or working on it? This seems like a useful path to take, I'm experimenting with cross-compiling darwin code from linux and successfully compile and link c/c++ code but I can't try objc code due to the very xcode driven nature of the objc library rules, and the toolchain I set up is mostly just a plain clang with a macos sysroot.

chancila avatar Mar 01 '21 23:03 chancila

Hi there! We're doing a clean up of old issues and will be closing this one. Please reopen if you’d like to discuss anything further. We’ll respond as soon as we have the bandwidth/resources to do so.

ShreeM01 avatar Feb 16 '23 21:02 ShreeM01