instance_id
stringlengths 17
39
| repo
stringclasses 8
values | issue_id
stringlengths 14
34
| pr_id
stringlengths 14
34
| linking_methods
sequencelengths 1
3
| base_commit
stringlengths 40
40
| merge_commit
stringlengths 0
40
⌀ | hints_text
sequencelengths 0
106
| resolved_comments
sequencelengths 0
119
| created_at
unknown | labeled_as
sequencelengths 0
7
| problem_title
stringlengths 7
174
| problem_statement
stringlengths 0
55.4k
| gold_files
sequencelengths 0
10
| gold_files_postpatch
sequencelengths 1
10
| test_files
sequencelengths 0
60
| gold_patch
stringlengths 220
5.83M
| test_patch
stringlengths 386
194k
⌀ | split_random
stringclasses 3
values | split_time
stringclasses 3
values | issue_start_time
timestamp[ns] | issue_created_at
unknown | issue_by_user
stringlengths 3
21
| split_repo
stringclasses 3
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bazelbuild/bazel/5307_5455 | bazelbuild/bazel | bazelbuild/bazel/5307 | bazelbuild/bazel/5455 | [
"timestamp(timedelta=0.0, similarity=0.8566144616384757)"
] | 88d1caeef07533429468515f63b3d4e2cb9a7a80 | 5b4462c434b2cf87a520abf15cf06926a63cd8d1 | [
"This is a reasonable feature request.\r\nShould be easy to implement."
] | [
"Why are we allocating a copy of the list here, only to throw it away?",
"Python allows only string or tuple-of-string here, not list of string, and so should we.",
"Done",
"Done",
"I believe we don't check the element type, that the `generic1` part of `ParamType` is just for documentation generation purposes. This should be replaced by\r\n\r\n for (String s : subs.getContents(String.class, \"string\")) {\r\n ...\r\n }\r\n\r\nSame for `startsWith` below.",
"Can we add cases for:\r\n- singleton tuple\r\n- empty tuple\r\n- tuple with element of wrong type",
"Could be a good idea to document that.",
"Done",
"Indeed, I'll add that caveat to Param's javadoc now.\r\n\r\nNote that the var `subs` and the `@SuppressWarnings` are no longer needed, since the cast is done by `getContents`. `ConversionException` extends `EvalException` so this can just be `EvalException`. (Same below, of course.)",
"Thanks."
] | "2018-06-23T00:15:24Z" | [
"type: feature request",
"good first issue"
] | support passing tuples to str.startswith and str.endswith | Python supports passing a tuple to the first argument of `str.startswith` and `str.endswith` to allow testing multiple prefixes or suffixes in one go. I've now wanted this feature in Skylark a few times, so I'm formally submitting a request. | [
"src/main/java/com/google/devtools/build/lib/syntax/StringModule.java"
] | [
"src/main/java/com/google/devtools/build/lib/syntax/StringModule.java"
] | [
"src/test/skylark/testdata/string_misc.sky"
] | diff --git a/src/main/java/com/google/devtools/build/lib/syntax/StringModule.java b/src/main/java/com/google/devtools/build/lib/syntax/StringModule.java
index e18c833097e384..2f2287911f31ff 100644
--- a/src/main/java/com/google/devtools/build/lib/syntax/StringModule.java
+++ b/src/main/java/com/google/devtools/build/lib/syntax/StringModule.java
@@ -19,6 +19,7 @@
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.skylarkinterface.Param;
+import com.google.devtools.build.lib.skylarkinterface.ParamType;
import com.google.devtools.build.lib.skylarkinterface.SkylarkCallable;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory;
@@ -893,7 +894,13 @@ public SkylarkList<String> elems(String self) throws ConversionException {
+ "and <code>end</code> being exclusive.",
parameters = {
@Param(name = "self", type = String.class, doc = "This string."),
- @Param(name = "sub", type = String.class, legacyNamed = true,
+ @Param(
+ name = "sub",
+ allowedTypes = {
+ @ParamType(type = String.class),
+ @ParamType(type = Tuple.class, generic1 = String.class),
+ },
+ legacyNamed = true,
doc = "The substring to check."),
@Param(
name = "start",
@@ -909,9 +916,21 @@ public SkylarkList<String> elems(String self) throws ConversionException {
defaultValue = "None",
doc = "optional position at which to stop comparing.")
})
- public Boolean endsWith(String self, String sub, Integer start, Object end)
- throws ConversionException {
- return pythonSubstring(self, start, end, "'end' operand of 'endswith'").endsWith(sub);
+ public Boolean endsWith(String self, Object sub, Integer start, Object end)
+ throws ConversionException, EvalException {
+ String str = pythonSubstring(self, start, end, "'end' operand of 'endswith'");
+ if (sub instanceof String) {
+ return str.endsWith((String)sub);
+ }
+
+ @SuppressWarnings("unchecked")
+ Tuple<Object> subs = (Tuple<Object>) sub;
+ for (String s : subs.getContents(String.class, "string")) {
+ if (str.endsWith(s)) {
+ return true;
+ }
+ }
+ return false;
}
// In Python, formatting is very complex.
@@ -966,7 +985,13 @@ public String format(String self, SkylarkList<?> args, SkylarkDict<?, ?> kwargs,
+ "<code>end</code> being exclusive.",
parameters = {
@Param(name = "self", type = String.class, doc = "This string."),
- @Param(name = "sub", type = String.class, legacyNamed = true,
+ @Param(
+ name = "sub",
+ allowedTypes = {
+ @ParamType(type = String.class),
+ @ParamType(type = Tuple.class, generic1 = String.class),
+ },
+ legacyNamed = true,
doc = "The substring to check."),
@Param(
name = "start",
@@ -982,9 +1007,21 @@ public String format(String self, SkylarkList<?> args, SkylarkDict<?, ?> kwargs,
defaultValue = "None",
doc = "Stop comparing at this position.")
})
- public Boolean startsWith(String self, String sub, Integer start, Object end)
- throws ConversionException {
- return pythonSubstring(self, start, end, "'end' operand of 'startswith'").startsWith(sub);
+ public Boolean startsWith(String self, Object sub, Integer start, Object end)
+ throws ConversionException, EvalException {
+ String str = pythonSubstring(self, start, end, "'end' operand of 'startswith'");
+ if (sub instanceof String) {
+ return str.startsWith((String)sub);
+ }
+
+ @SuppressWarnings("unchecked")
+ Tuple<Object> subs = (Tuple<Object>) sub;
+ for (String s : subs.getContents(String.class, "string")) {
+ if (str.startsWith(s)) {
+ return true;
+ }
+ }
+ return false;
}
public static final StringModule INSTANCE = new StringModule();
| diff --git a/src/test/skylark/testdata/string_misc.sky b/src/test/skylark/testdata/string_misc.sky
index 901d7f3091ca7f..87708f9fae3b64 100644
--- a/src/test/skylark/testdata/string_misc.sky
+++ b/src/test/skylark/testdata/string_misc.sky
@@ -62,6 +62,26 @@ assert_eq('Apricot'.endswith('co', -1), False)
assert_eq('abcd'.endswith('c', -2, -1), True)
assert_eq('abcd'.endswith('c', 1, 8), False)
assert_eq('abcd'.endswith('d', 1, 8), True)
+assert_eq('Apricot'.endswith(('cot', 'toc')), True)
+assert_eq('Apricot'.endswith(('toc', 'cot')), True)
+assert_eq('a'.endswith(('', '')), True)
+assert_eq('a'.endswith(('', 'a')), True)
+assert_eq('a'.endswith(('a', 'a')), True)
+assert_eq(''.endswith(('a', '')), True)
+assert_eq(''.endswith(('', '')), True)
+assert_eq(''.endswith(('a', 'a')), False)
+assert_eq('a'.endswith(('a')), True)
+assert_eq('a'.endswith(('a',)), True)
+assert_eq('a'.endswith(('b',)), False)
+assert_eq('a'.endswith(()), False)
+assert_eq(''.endswith(()), False)
+---
+'a'.endswith(['a']) ### expected value of type 'string or tuple of strings' for parameter 'sub', in method call endswith(list) of 'string'
+---
+'1'.endswith((1,)) ### expected type 'string' for 'string' element but got type 'int' instead
+---
+'a'.endswith(('1', 1)) ### expected type 'string' for 'string' element but got type 'int' instead
+---
# startswith
assert_eq('Apricot'.startswith('Apr'), True)
@@ -70,6 +90,26 @@ assert_eq('Apricot'.startswith(''), True)
assert_eq('Apricot'.startswith('z'), False)
assert_eq(''.startswith(''), True)
assert_eq(''.startswith('a'), False)
+assert_eq('Apricot'.startswith(('Apr', 'rpA')), True)
+assert_eq('Apricot'.startswith(('rpA', 'Apr')), True)
+assert_eq('a'.startswith(('', '')), True)
+assert_eq('a'.startswith(('', 'a')), True)
+assert_eq('a'.startswith(('a', 'a')), True)
+assert_eq(''.startswith(('a', '')), True)
+assert_eq(''.startswith(('', '')), True)
+assert_eq(''.startswith(('a', 'a')), False)
+assert_eq('a'.startswith(('a')), True)
+assert_eq('a'.startswith(('a',)), True)
+assert_eq('a'.startswith(('b',)), False)
+assert_eq('a'.startswith(()), False)
+assert_eq(''.startswith(()), False)
+---
+'a'.startswith(['a']) ### expected value of type 'string or tuple of strings' for parameter 'sub', in method call startswith(list) of 'string'
+---
+'1'.startswith((1,)) ### expected type 'string' for 'string' element but got type 'int' instead
+---
+'a'.startswith(('1', 1)) ### expected type 'string' for 'string' element but got type 'int' instead
+---
# substring
assert_eq('012345678'[0:-1], "01234567")
| train | train | 2018-06-23T00:13:51 | "2018-06-01T01:52:04Z" | benjaminp | test |
bazelbuild/bazel/5345_5650 | bazelbuild/bazel | bazelbuild/bazel/5345 | bazelbuild/bazel/5650 | [
"timestamp(timedelta=147727.0, similarity=0.8530386804142502)"
] | fc8b9bfe2fc81c0e264ba93a3f7f74e28f7c1643 | 7c97690869f17f8d60a4199f7b4aeebf6995c9e0 | [
"cc @katre",
"I think the only way to handle this will be to use two toolchain types: one for the bootstrapping, one for actual usage. If you write the implementation functions modularly, and use the same property names on the toolchain providers, you should be able to re-use a lot of code.\r\n\r\nI'm closing this issue because I don't think this is something Bazel can support at this time."
] | [] | "2018-07-21T15:44:18Z" | [
"type: feature request",
"team-Configurability"
] | Support for execution-only "bootstrap" toolchains | ### Description of the problem / feature request:
I'd like to be able to define toolchains that only target the execution platform. This would be useful for bootstrap toolchains that build tools that run on the execution platform and are used in other toolchains.
### Feature requests: what underlying problem are you trying to solve with this feature?
In rules_go, we're building a pluggable static analysis framework. Users will define a `go_checker` rule, which depends on `go_library` rules that implement custom checks. The `go_checker` rule does some code generation and produces a binary for the execution platform. A specific `go_checker` binary is registered in WORKSPACE. This `go_checker` binary should ideally be part of the toolchain for the target platform and should run on all the source files compiled using that toolchain.
The problem is a cyclic dependency: the Go toolchain should contain a `go_checker`, but we need a toolchain to build a `go_checker`, since it depends on regular `go_library` rules. Ideally, we would be able to select an execution-only bootstrap toolchain that doesn't include the `go_checker`, and `go_library` rules would only use `go_checker` if it were available in the toolchain.
Currently, we're working around this by using a special rule, `go_tool_library` that does not depend on `go_checker`. `go_library` has an implicit dependency on `go_checker` (`go_checker` is not currently part of the toolchain).
| [
"src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java"
] | [
"src/test/shell/bazel/toolchain_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java b/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java
index 0ae17e2093b747..b2b56b9b3ada08 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/DependencyResolver.java
@@ -236,7 +236,8 @@ private void visitRule(
Attribute toolchainsAttribute =
attributeMap.getAttributeDefinition(PlatformSemantics.RESOLVED_TOOLCHAINS_ATTR);
- resolveToolchainDependencies(outgoingEdges.get(toolchainsAttribute), toolchainLabels);
+ resolveToolchainDependencies(
+ outgoingEdges.get(toolchainsAttribute), toolchainLabels, ruleConfig);
}
/**
@@ -447,11 +448,10 @@ private void resolveLateBoundAttributes(
}
private void resolveToolchainDependencies(
- Set<Dependency> dependencies, ImmutableSet<Label> toolchainLabels) {
+ Set<Dependency> dependencies, ImmutableSet<Label> toolchainLabels,
+ BuildConfiguration ruleConfig) {
for (Label label : toolchainLabels) {
- Dependency dependency =
- Dependency.withTransitionAndAspects(
- label, HostTransition.INSTANCE, AspectCollection.EMPTY);
+ Dependency dependency = Dependency.withConfiguration(label, ruleConfig);
dependencies.add(dependency);
}
}
| diff --git a/src/test/shell/bazel/toolchain_test.sh b/src/test/shell/bazel/toolchain_test.sh
index 097e874641ca60..12b22f892e26f5 100755
--- a/src/test/shell/bazel/toolchain_test.sh
+++ b/src/test/shell/bazel/toolchain_test.sh
@@ -168,6 +168,25 @@ EOF
expect_log 'extra_str = "bar"'
}
+function test_toolchain_build_with_target_configuration {
+ write_test_toolchain
+ write_test_rule
+ write_register_toolchain
+
+ mkdir -p demo
+ cat >> demo/BUILD <<EOF
+load('//toolchain:rule_use_toolchain.bzl', 'use_toolchain')
+# Use the toolchain.
+use_toolchain(
+ name = 'use',
+ message = 'this is the rule')
+EOF
+
+ bazel cquery 'kind("test_toolchain", deps(//demo:use))' | grep -Fv HOST \
+ &> $TEST_log || fail "cquery failed"
+ expect_log "//:test_toolchain_impl_1"
+}
+
function test_toolchain_use_in_rule {
write_test_toolchain
write_test_rule
| train | train | 2018-07-20T22:51:42 | "2018-06-07T19:01:48Z" | jayconrod | test |
bazelbuild/bazel/5358_5363 | bazelbuild/bazel | bazelbuild/bazel/5358 | bazelbuild/bazel/5363 | [
"timestamp(timedelta=0.0, similarity=0.8992251828312009)"
] | c720152ec1936a537c9519d522d3cb41d19cff77 | b214aa6897a598fa7b1622cba5c1ffeb7a669c41 | [] | [] | "2018-06-11T12:03:59Z" | [] | Broken link to mobile application tutorial in Java build tutorial | ### Description of the problem / feature request:
On the page https://docs.bazel.build/versions/master/tutorial/java.html, the link at the bottom of the page titled `mobile application tutorial` points to the URL https://docs.bazel.build/versions/master/tutorial/app.html but this page does not exist, so a 404 is displayed instead. | [
"site/docs/tutorial/java.md"
] | [
"site/docs/tutorial/java.md"
] | [] | diff --git a/site/docs/tutorial/java.md b/site/docs/tutorial/java.md
index 4fbaefdbe7d19e..8352229a6b4adb 100644
--- a/site/docs/tutorial/java.md
+++ b/site/docs/tutorial/java.md
@@ -412,7 +412,8 @@ dependencies.
* The [C++ build tutorial](../tutorial/cpp.md) to get started with building
C++ projects with Bazel.
-* The [mobile application tutorial](../tutorial/app.md) to get started with
+* The [Android application tutorial](../tutorial/android-app.md) and
+ [iOS application tutorial](../tutorial/ios-app.md) to get started with
building mobile applications for Android and iOS with Bazel.
Happy building!
| null | val | train | 2018-06-11T13:39:31 | "2018-06-09T18:24:00Z" | karltk | test |
bazelbuild/bazel/5362_5364 | bazelbuild/bazel | bazelbuild/bazel/5362 | bazelbuild/bazel/5364 | [
"timestamp(timedelta=1.0, similarity=0.8610414419473065)"
] | c720152ec1936a537c9519d522d3cb41d19cff77 | cea4f10e14f801efa8bf33d31d1af2b5d74864a8 | [
"Thanks! If you feel like fixing it, here's the source for the doc file: https://github.com/bazelbuild/bazel/blob/master/site/docs/build-ref.html",
"(Otherwise someone else will fix it later.)"
] | [] | "2018-06-11T12:10:49Z" | [
"type: bug",
"type: documentation (cleanup)"
] | Documentation does not list all attribute types | ### Description of the problem / feature request:
https://docs.bazel.build/versions/master/build-ref.html#rules says:
> The full set of types that an attribute can have is: integer, label, list of labels, string, list of strings, output label, list of output labels
But there are quite a few more types that are available: https://docs.bazel.build/versions/master/skylark/lib/attr.html#modules.attr | [
"site/docs/build-ref.html"
] | [
"site/docs/build-ref.html"
] | [] | diff --git a/site/docs/build-ref.html b/site/docs/build-ref.html
index 1b4d9ce3aa3562..944a692ff6bf0f 100644
--- a/site/docs/build-ref.html
+++ b/site/docs/build-ref.html
@@ -358,7 +358,7 @@ <h3 id="rules">Rules</h3>
the <a href='be/overview.html'>Build
Encyclopedia</a> for the full list of supported rules and their
corresponding attributes. Each attribute has a name and a
- type. The full set of types that an attribute can have is: integer,
+ type. Some of the common types an attribute can have are integer,
label, list of labels, string, list of strings, output label,
list of output labels. Not all attributes need to be specified in
every rule. Attributes thus form a dictionary from keys (names) to
| null | val | train | 2018-06-11T13:39:31 | "2018-06-11T11:26:30Z" | ash2k | test |
bazelbuild/bazel/5389_5399 | bazelbuild/bazel | bazelbuild/bazel/5389 | bazelbuild/bazel/5399 | [
"timestamp(timedelta=77901.0, similarity=0.845440601490151)"
] | 522f76ae5e50ae9848b6f407acbcce62bb808016 | 6cccefdcdd486e9e21836dfae506ad8e4452b40c | [
"Please provide the contents of jvm.out.",
"> Please provide the contents of jvm.out.\r\n\r\nI ssh'd into CircleCI when this failure occurs and checked jvm.out and it an empty file after the crash. The failure looks like this:\r\n\r\n```\r\n[1] Segmentation fault\r\n[0] \r\n[0] Server terminated abruptly (error code: 14, error message: '', log file: '/home/circleci/.cache/bazel/_bazel_circleci/9ce5c2144ecf75d11717c0aa41e45a8d/server/jvm.out')\r\n[0] \r\n[0] bazel run //src:prodserver exited with code 37\r\n```\r\n\r\nIt doesn't always occur in the same place (there are a few steps in CI that I've seen it fail at) and on occasion it passes.\r\n\r\nIs there anywhere else besides jvm.out that might give a hint on the crash?",
"If the file is empty then that's a sign that the gRPC client/server connection crashed. We've seen a similar case before where we didn't implement flow control correctly for file uploads to remote machines.\r\n\r\nDo you have remote caching or execution enabled? If yes, please provide the flags you are using.",
"If these are the right flags, then it doesn't look like it:\r\n\r\n```\r\n[0] INFO: Options provided by the client:\r\n[0] Inherited 'common' options: --isatty=0 --terminal_columns=80\r\n\r\n[0] INFO: Reading rc options for 'run' from /home/circleci/ng/tools/bazel.rc:\r\n[0] Inherited 'build' options: --strategy=TypeScriptCompile=worker --strategy=AngularTemplateCompile=worker --symlink_prefix=dist/\r\n\r\n[0] INFO: Reading rc options for 'run' from /etc/bazel.bazelrc:\r\n[0] Inherited 'build' options: --noshow_progress --announce_rc --experimental_strict_action_env --experimental_repository_cache=/home/circleci/bazel_repository_cache --local_resources=3072,2.0,1.0\r\n```",
"Hmm, that's odd - this seems to be a null build. Here's a more complete snippet from a passing run:\r\n```\r\n$ bazel build test/...\r\n...\r\nINFO: Analysed target //test/e2e:e2e (1 packages loaded).\r\nINFO: Found 1 target...\r\nTarget //test/e2e:e2e up-to-date:\r\n dist/bin/test/e2e/app.spec.d.ts\r\n...\r\n$ yarn e2e-prodserver && yarn e2e-devserver\r\n$ concurrently \"bazel run //src:prodserver\" \"while ! nc -z 127.0.0.1 5432; do sleep 1; done && protractor\" --kill-others --success first\r\n...\r\n[0] INFO: Analysed target //src:prodserver (1 packages loaded).\r\n[0] INFO: Found 1 target...\r\n[0] Target //src:prodserver up-to-date:\r\n[0] dist/bin/src/prodserver_bin.sh\r\n[0] dist/bin/src/prodserver\r\n[0] INFO: Elapsed time: 15.070s, Critical Path: 9.76s\r\n[0] INFO: 2 processes: 1 processwrapper-sandbox, 1 worker.\r\n[0] INFO: Running command line: dist/bin/src/prodserver src -p 5432\r\n...\r\n[0] history-server listening on port 5432; Ctrl+C to stop\r\n...\r\n[0] bazel run //src:prodserver exited with code null\r\n$ concurrently \"bazel run //src:devserver\" \"while ! nc -z 127.0.0.1 5432; do sleep 1; done && protractor\" --kill-others --success first\r\n...\r\n[0] INFO: Analysed target //src:devserver (0 packages loaded).\r\n[0] INFO: Found 1 target...\r\n[0] Target //src:devserver up-to-date:\r\n[0] dist/bin/src/devserver.MF\r\n[0] dist/bin/src/scripts_devserver.MF\r\n[0] dist/bin/src/devserver\r\n[0] INFO: Elapsed time: 4.219s, Critical Path: 0.07s\r\n[0] INFO: 0 processes.\r\n[0] INFO: Running command line: dist/bin/src/devserver\r\n[0] Server listening on http://ad2f21ad8e4a:5432/\r\n```",
"The failing build fails to run //src:prodserver, but it's still just two actions.",
"I think the reference to #3645 is a red herring.",
"If I understand correctly, then you're running the containers with a 4 GB limit. --local_resources does not actually restrict Bazel's own memory usage, but maybe that's the intent?\r\n\r\nIIRC, Bazel is set to 4 GB max memory, which is unaffected by --local_resources. Maybe Bazel is trying to allocate too much memory and the container is killing it? Technically, this doesn't imply that Bazel's memory use has actually increased - we might be using a slightly different gc configuration or allocate memory more rapidly, and that might push it over the limit.\r\n\r\nIf that's correct, then you should try adding --host_jvm_args=-Xmx2G to the Bazel invocation, like this:\r\n```\r\nbazel --host_jvm_args=-Xmx2G build ...\r\n```\r\nor like this in the bazelrc:\r\n```\r\nstartup --host_jvm_args=-Xmx2G\r\n```",
"Thanks for investigating, Ulf!\r\n\r\nYour simple explanation is right. The build passes three times in a row with the 2G heap limit for the bazel JVM. https://circleci.com/gh/alexeagle/workflows/angular-bazel-example/tree/test-bazel-0.14.1\r\n\r\nI also have a PR out to update Angular to use 0.14 again\r\nhttps://github.com/angular/angular/pull/24512\r\nwhere I've increased the size of the VM used to run one of the jobs.\r\n\r\nThis should fix it for us. I'm not sure what else we could do on this issue, other than improve the \"guard rails\" here so it's harder to get the wrong memory limit, or easier to debug. Feel free to close if you don't want to take further action."
] | [
"can assert_size itself be a test? then you don't need this extra rule, and dummy.sh can be hidden away.",
"Do nothing, feel better?",
"This is an interesting approach. What was the reasoning behind? assert_size is a nice Skylark rule, it only feels weird to be used like this in a BUILD file. Can you create and run an assert_size() target from the sh test?",
"> can assert_size itself be a test?\r\n\r\nYes it can! Done.\r\n\r\n> Can you create and run an assert_size() target from the sh test?\r\n\r\nThat'd beat the purpose of analysis-time assertion and of not building the inputs. See the new comments in the docstring.",
"Now even less! (Removed.)",
"Oh, I see now! That's smart!"
] | "2018-06-14T15:26:58Z" | [
"under investigation",
"P1"
] | Memory usage regression in bazel 0.14.0 and 0.14.1 | On Angular and related projects, we run builds on CI in a docker container. We use the `--local_resources` flag to workaround
https://github.com/bazelbuild/bazel/issues/3645
which causes random failures where Bazel tries to allocate too much memory, since it asks the OS how much RAM is available rather than the containerization host.
After updating to 0.14.0 (and also observed in 0.14.1) we have the problem again:
https://github.com/angular/angular/issues/24484
it affects Angular users who send PRs which are failing on CI.
An example failure:
https://circleci.com/gh/gregmagolan/angular-bazel-example/442?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link
There is not much indication what is going wrong, but it looks the same as errors we got before adding the `--local_resources` flag.
We are rolling back Bazel in Angular and related projects to 0.13. | [
"src/BUILD"
] | [
"src/BUILD",
"src/rule_size_test.bzl"
] | [] | diff --git a/src/BUILD b/src/BUILD
index d2431844fb6fed..0d8d060237f92b 100644
--- a/src/BUILD
+++ b/src/BUILD
@@ -1,6 +1,7 @@
# Packaging
load(":embedded_tools.bzl", "srcsfile")
+load(":rule_size_test.bzl", "rule_size_test")
md5_cmd = "set -e -o pipefail && cat $(SRCS) | sort | %s | awk '{ print $$1; }' > $@"
@@ -182,6 +183,17 @@ py_binary(
"_with_jdk",
]]
+rule_size_test(
+ name = "embedded_tools_size_test",
+ src = ":embedded_tools_srcs",
+ # WARNING: Only adjust the number in `expect` if you are intentionally
+ # adding or removing embedded tools. Know that the more embedded tools there
+ # are in Bazel, the bigger the binary becomes and the slower Bazel starts.
+ expect = 503,
+ margin = 5, # percentage
+ visibility = ["//visibility:private"],
+)
+
filegroup(
name = "embedded_jdk",
srcs = select({
diff --git a/src/rule_size_test.bzl b/src/rule_size_test.bzl
new file mode 100644
index 00000000000000..29d0e813d26874
--- /dev/null
+++ b/src/rule_size_test.bzl
@@ -0,0 +1,130 @@
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Defines a test rule that asserts the number of output files in another rule.
+
+This rule operates in Bazel's analysis phase, not in its execution phase, and so
+it's faster than a conventional test rule would be.
+
+Furthermore this rule's action does not depend on any of the inputs (because the
+assertion is done in the analysis phase) so Bazel won't even build the input
+files to run the test. The test has constant execution time.
+
+=== Use ===
+
+Use this rule to assert the size of a filegroup or any other rule and catch
+sudden, unexpected changes in the size.
+
+The `margin` attribute allows specifying a tolerance value (percentage), to
+allow for organic, expected growth or shrinkage of the target rule.
+
+=== Example ===
+
+The "resources_size_test" test fails if the number of files in
+"resources" changes from 123 by more than 3 percent:
+
+ filegroup(
+ name = "resources",
+ srcs = glob(["**"]) + [
+ "//foo/bar:resources"
+ "//baz:resources",
+ ],
+ )
+
+ rule_size_test(
+ name = "resources_size_test",
+ src = ":resources",
+
+ # Expect 123 files in ":resources", with an error margin of 3% to allow
+ # for slight changes.
+ expect = 123,
+ margin = 3,
+ )
+
+"""
+
+def _impl(ctx):
+ if ctx.attr.expect < 0:
+ fail("ERROR: rule_size_test.expect must be positive")
+
+ if ctx.attr.margin < 0 or ctx.attr.margin > 100:
+ # Do not allow more than 100% change in size.
+ fail("ERROR: rule_size_test.margin must be in range [0..100]")
+
+ if ctx.attr.expect == 0 and ctx.attr.margin != 0:
+ # Allow no margin when expecting 0 files, to avoid division by zero.
+ fail("ERROR: rule_size_test.margin must be 0 when " +
+ "rule_size_test.expect is 0")
+
+ amount = len(ctx.attr.src[DefaultInfo].files)
+
+ if ctx.attr.margin > 0:
+ if amount >= ctx.attr.expect:
+ diff = amount - ctx.attr.expect
+ else:
+ diff = ctx.attr.expect - amount
+
+ if ((diff * 100) / ctx.attr.expect) > ctx.attr.margin:
+ fail(("ERROR: rule_size_test: expected %d file(s) within %d%% " +
+ "error margin, got %d file(s) (%d%% difference)") % (
+ ctx.attr.expect,
+ ctx.attr.margin,
+ amount,
+ (diff * 100) / ctx.attr.expect,
+ ))
+ elif amount != ctx.attr.expect:
+ fail(("ERROR: rule_size_test: expected exactly %d file(s), got %d " +
+ "file(s)") % (ctx.attr.expect, amount))
+
+ if ctx.attr.is_windows:
+ test_bin = ctx.actions.declare_file(ctx.label.name + ".bat")
+ ctx.actions.write(output = test_bin, content = "", is_executable = True)
+ else:
+ test_bin = ctx.actions.declare_file(ctx.label.name + ".sh")
+ ctx.actions.write(
+ output = test_bin,
+ content = "#!/bin/sh",
+ is_executable = True,
+ )
+
+ return [DefaultInfo(executable = test_bin)]
+
+_rule_size_test = rule(
+ implementation = _impl,
+ attrs = {
+ # The target whose number of output files this rule asserts. The number
+ # of output files is the size of the target's DefaultInfo.files field.
+ "src": attr.label(allow_files = True),
+ # A non-negative integer, the expected number of files that the target
+ # in `src` outputs. If 0, then `margin` must also be 0.
+ "expect": attr.int(mandatory = True),
+ # A percentage value, in the range of [0..100]. Allows for tolerance in
+ # the difference between expected and actual number of files in `src`.
+ # If 0, then the target in `src` must output exactly `expect` many
+ # files.
+ "margin": attr.int(mandatory = True),
+ # True if running on Windows, False otherwise.
+ "is_windows": attr.bool(mandatory = True),
+ },
+ test = True,
+)
+
+def rule_size_test(name, **kwargs):
+ _rule_size_test(
+ name = name,
+ is_windows = select({
+ "@bazel_tools//src/conditions:windows": True,
+ "//conditions:default": False,
+ }),
+ **kwargs)
| null | train | train | 2018-06-15T01:51:08 | "2018-06-13T23:20:35Z" | alexeagle | test |
bazelbuild/bazel/5512_5600 | bazelbuild/bazel | bazelbuild/bazel/5512 | bazelbuild/bazel/5600 | [
"timestamp(timedelta=80842.0, similarity=0.8454423582900445)"
] | e14a7d4f156c28244a491c65083273f57734cdbe | 34e100abc472d795c4c77e2baf327156967ca4c0 | [
"I think this is all fixed now."
] | [
"Try not to introduce more `using std::type` aliases. When reader sees `mutex` in a function, it is not immediately clear if it is `std::mutex` or Bazel's own custom mutex implementation.\r\n\r\n`using MagicMap = std::unordered_map<std::string, MagicItem>` that saves significant amount of typing is strongly encouraged.",
"Done. Thanks for the advice!"
] | "2018-07-16T13:35:49Z" | [
"type: bug",
"P1",
"type: process",
"category: misc > misc"
] | Bazel server: ensure file streams are closed | ### Description of the problem / feature request:
The Bazel server (the Java code) sometimes opens streams without closing them, relying on the garbage collector to finalize the InputStream and close the file. This leads to Bazel holding on to files and (on Windows) being unable to delete them later.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Examples:
https://github.com/bazelbuild/bazel/blob/52035c1c2d0ad494fb4318a6c10a6a46749ea6a2/src/main/java/com/google/devtools/build/lib/vfs/FileSystem.java#L270-L276
https://github.com/bazelbuild/bazel/blob/52035c1c2d0ad494fb4318a6c10a6a46749ea6a2/src/main/java/com/google/devtools/build/lib/analysis/actions/LauncherFileWriteAction.java#L78
https://github.com/bazelbuild/bazel/blob/52035c1c2d0ad494fb4318a6c10a6a46749ea6a2/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidSdkRepositoryFunction.java#L314
https://github.com/bazelbuild/bazel/blob/52035c1c2d0ad494fb4318a6c10a6a46749ea6a2/src/main/java/com/google/devtools/build/lib/bazel/rules/android/SdkMavenRepository.java#L203
Correct usage would be try-with-resources:
https://github.com/bazelbuild/bazel/blob/52035c1c2d0ad494fb4318a6c10a6a46749ea6a2/src/main/java/com/google/devtools/build/lib/exec/BinTools.java#L242
### What's the output of `bazel info release`?
release 0.15.0 | [
"src/main/cpp/blaze.cc",
"src/main/cpp/blaze_util_platform.h",
"src/main/cpp/blaze_util_posix.cc",
"src/main/cpp/blaze_util_windows.cc"
] | [
"src/main/cpp/blaze.cc",
"src/main/cpp/blaze_util_platform.h",
"src/main/cpp/blaze_util_posix.cc",
"src/main/cpp/blaze_util_windows.cc"
] | [] | diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index 09760fcba3c7f4..c50503379cbddb 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -878,8 +878,9 @@ static void StartServerAndConnect(const WorkspaceLayout *workspace_layout,
// A PureZipExtractorProcessor to extract the files from the blaze zip.
class ExtractBlazeZipProcessor : public PureZipExtractorProcessor {
public:
- explicit ExtractBlazeZipProcessor(const string &embedded_binaries)
- : embedded_binaries_(embedded_binaries) {}
+ explicit ExtractBlazeZipProcessor(const string &embedded_binaries,
+ blaze::embedded_binaries::Dumper* dumper)
+ : embedded_binaries_(embedded_binaries), dumper_(dumper) {}
bool AcceptPure(const char *filename,
const devtools_ijar::u4 attr) const override {
@@ -892,29 +893,13 @@ class ExtractBlazeZipProcessor : public PureZipExtractorProcessor {
void Process(const char *filename, const devtools_ijar::u4 attr,
const devtools_ijar::u1 *data, const size_t size) override {
- string path = blaze_util::JoinPath(embedded_binaries_, filename);
- string dirname = blaze_util::Dirname(path);
- // Performance optimization: memoize the paths we already created a
- // directory for, to spare a stat in attempting to recreate an already
- // existing directory. This optimization alone shaves off seconds from the
- // extraction time on Windows.
- if (created_directories_.insert(dirname).second) {
- if (!blaze_util::MakeDirectories(dirname, 0777)) {
- BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
- << "couldn't create '" << path << "': " << GetLastErrorString();
- }
- }
-
- if (!blaze_util::WriteFile(data, size, path, 0755)) {
- BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
- << "Failed to write zipped file '" << path
- << "': " << GetLastErrorString();
- }
+ dumper_->Dump(
+ data, size, blaze_util::JoinPath(embedded_binaries_, filename));
}
private:
const string embedded_binaries_;
- set<string> created_directories_;
+ blaze::embedded_binaries::Dumper* dumper_;
};
// Actually extracts the embedded data files into the tree whose root
@@ -923,7 +908,16 @@ static void ActuallyExtractData(const string &argv0,
const string &embedded_binaries) {
std::string install_md5;
GetInstallKeyFileProcessor install_key_processor(&install_md5);
- ExtractBlazeZipProcessor extract_blaze_processor(embedded_binaries);
+
+ std::string error;
+ std::unique_ptr<blaze::embedded_binaries::Dumper> dumper(
+ blaze::embedded_binaries::Create(&error));
+ if (dumper == nullptr) {
+ BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR) << error;
+ }
+ ExtractBlazeZipProcessor extract_blaze_processor(embedded_binaries,
+ dumper.get());
+
CompoundZipProcessor processor({&extract_blaze_processor,
&install_key_processor});
if (!blaze_util::MakeDirectories(embedded_binaries, 0777)) {
@@ -948,6 +942,11 @@ static void ActuallyExtractData(const string &argv0,
<< " as a zip file: " << extractor->GetError();
}
+ if (!dumper->Finish(&error)) {
+ BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
+ << "Failed to extract embedded binaries: " << error;
+ }
+
if (install_md5 != globals->install_md5) {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "The " << globals->options->product_name << " binary at " << argv0
diff --git a/src/main/cpp/blaze_util_platform.h b/src/main/cpp/blaze_util_platform.h
index 29596df57bdaf9..24a28eb6e7db06 100644
--- a/src/main/cpp/blaze_util_platform.h
+++ b/src/main/cpp/blaze_util_platform.h
@@ -25,6 +25,50 @@
namespace blaze {
+namespace embedded_binaries {
+
+// Dumps embedded binaries that were extracted from the Bazel zip to disk.
+// The platform-specific implementations may use multi-threaded I/O.
+class Dumper {
+ public:
+ // Requests to write the `data` of `size` bytes to disk under `path`.
+ // The actual writing may happen asynchronously.
+ // `path` must be an absolute path. All of its parent directories will be
+ // created.
+ // The caller retains ownership of `data` and may release it immediately after
+ // this method returns.
+ // Callers may call this method repeatedly, but only from the same thread
+ // (this method is not thread-safe).
+ // If writing fails, this method sets a flag in the `Dumper`, and `Finish`
+ // will return false. Subsequent `Dump` calls will have no effect.
+ virtual void Dump(const void* data, const size_t size,
+ const std::string& path) = 0;
+
+ // Finishes dumping data.
+ //
+ // This method may block in case the Dumper is asynchronous and some async
+ // writes are still in progress.
+ // Subsequent `Dump` calls after this method have no effect.
+ //
+ // Returns true if there were no errors in any of the `Dump` calls.
+ // Returns false if any of the `Dump` calls failed, and if `error` is not
+ // null then puts an error message in `error`.
+ virtual bool Finish(std::string* error) = 0;
+
+ // Destructor. Subclasses should make sure it calls `Finish(nullptr)`.
+ virtual ~Dumper() {}
+
+ protected:
+ Dumper() {}
+};
+
+// Creates a new Dumper. The caller takes ownership of the returned object.
+// Returns nullptr upon failure and puts an error message in `error` (if `error`
+// is not nullptr).
+Dumper* Create(std::string* error = nullptr);
+
+} // namespace embedded_binaries
+
struct GlobalVariables;
class SignalHandler {
diff --git a/src/main/cpp/blaze_util_posix.cc b/src/main/cpp/blaze_util_posix.cc
index 0a3daaab81ef86..b24aba14ed871a 100644
--- a/src/main/cpp/blaze_util_posix.cc
+++ b/src/main/cpp/blaze_util_posix.cc
@@ -36,6 +36,8 @@
#include <cassert>
#include <cinttypes>
+#include <set>
+#include <string>
#include "src/main/cpp/blaze_util.h"
#include "src/main/cpp/global_variables.h"
@@ -54,9 +56,74 @@ namespace blaze {
using blaze_exit_code::INTERNAL_ERROR;
using blaze_util::GetLastErrorString;
+using std::set;
using std::string;
using std::vector;
+namespace embedded_binaries {
+
+class PosixDumper : public Dumper {
+ public:
+ static PosixDumper* Create(string* error);
+ ~PosixDumper() { Finish(nullptr); }
+ virtual void Dump(const void* data, const size_t size, const string& path)
+ override;
+ virtual bool Finish(string* error) override;
+
+ private:
+ PosixDumper() : was_error_(false) {}
+
+ set<string> dir_cache_;
+ string error_msg_;
+ bool was_error_;
+};
+
+Dumper* Create(string* error) {
+ return PosixDumper::Create(error);
+}
+
+PosixDumper* PosixDumper::Create(string* error) {
+ return new PosixDumper();
+}
+
+void PosixDumper::Dump(const void* data, const size_t size,
+ const string& path) {
+ if (was_error_) {
+ return;
+ }
+
+ string dirname = blaze_util::Dirname(path);
+ // Performance optimization: memoize the paths we already created a
+ // directory for, to spare a stat in attempting to recreate an already
+ // existing directory.
+ if (dir_cache_.insert(dirname).second) {
+ if (!blaze_util::MakeDirectories(dirname, 0777)) {
+ was_error_ = true;
+ string msg = GetLastErrorString();
+ error_msg_ = string("couldn't create '") + path + "': " + msg;
+ }
+ }
+
+ if (was_error_) {
+ return;
+ }
+
+ if (!blaze_util::WriteFile(data, size, path, 0755)) {
+ was_error_ = true;
+ string msg = GetLastErrorString();
+ error_msg_ = string("Failed to write zipped file '") + path + "': " + msg;
+ }
+}
+
+bool PosixDumper::Finish(string* error) {
+ if (was_error_ && error) {
+ *error = error_msg_;
+ }
+ return !was_error_;
+}
+
+} // namespace embedded_binaries
+
SignalHandler SignalHandler::INSTANCE;
// The number of the last received signal that should cause the client
diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc
index 3751a1d0b1cd41..b6730871c6115d 100644
--- a/src/main/cpp/blaze_util_windows.cc
+++ b/src/main/cpp/blaze_util_windows.cc
@@ -27,10 +27,13 @@
#include <shlobj.h> // SHGetKnownFolderPath
#include <algorithm>
+#include <atomic>
#include <cstdio>
#include <cstdlib>
+#include <mutex> // NOLINT
+#include <set>
#include <sstream>
-#include <thread> // NOLINT (to slience Google-internal linter)
+#include <thread> // NOLINT (to silence Google-internal linter)
#include <type_traits> // static_assert
#include <vector>
@@ -76,6 +79,203 @@ using std::string;
using std::unique_ptr;
using std::wstring;
+namespace embedded_binaries {
+
+class WindowsDumper : public Dumper {
+ public:
+ static WindowsDumper* Create(string* error);
+ ~WindowsDumper() { Finish(nullptr); }
+ virtual void Dump(const void* data, const size_t size,
+ const string& path) override;
+ virtual bool Finish(string* error) override;
+
+ private:
+ WindowsDumper()
+ : threadpool_(NULL), cleanup_group_(NULL), was_error_(false) {}
+
+ PTP_POOL threadpool_;
+ PTP_CLEANUP_GROUP cleanup_group_;
+ TP_CALLBACK_ENVIRON threadpool_env_;
+ std::mutex dir_cache_lock_;
+ std::set<string> dir_cache_;
+ std::atomic_bool was_error_;
+ string error_msg_;
+};
+
+namespace {
+
+class DumpContext {
+ public:
+ DumpContext(unique_ptr<uint8_t[]> data, const size_t size, const string path,
+ std::mutex* dir_cache_lock, std::set<string>* dir_cache,
+ std::atomic_bool* was_error, string* error_msg);
+ void Run();
+
+ private:
+ void MaybeSignalError(const string& msg);
+
+ unique_ptr<uint8_t[]> data_;
+ const size_t size_;
+ const string path_;
+ std::mutex* dir_cache_lock_;
+ std::set<string>* dir_cache_;
+ std::atomic_bool* was_error_;
+ string* error_msg_;
+};
+
+VOID CALLBACK WorkCallback(
+ _Inout_ PTP_CALLBACK_INSTANCE Instance,
+ _Inout_opt_ PVOID Context,
+ _Inout_ PTP_WORK Work);
+
+} // namespace
+
+Dumper* Create(string* error) {
+ return WindowsDumper::Create(error);
+}
+
+WindowsDumper* WindowsDumper::Create(string* error) {
+ unique_ptr<WindowsDumper> result(new WindowsDumper());
+
+ result->threadpool_ = CreateThreadpool(NULL);
+ if (result->threadpool_ == NULL) {
+ if (error) {
+ string msg = GetLastErrorString();
+ *error = "CreateThreadpool failed: " + msg;
+ }
+ return nullptr;
+ }
+
+ result->cleanup_group_ = CreateThreadpoolCleanupGroup();
+ if (result->cleanup_group_ == NULL) {
+ string msg = GetLastErrorString();
+ CloseThreadpool(result->threadpool_);
+ if (error) {
+ string msg = GetLastErrorString();
+ *error = "CreateThreadpoolCleanupGroup failed: " + msg;
+ }
+ return nullptr;
+ }
+
+ // I (@laszlocsomor) experimented with different thread counts and found that
+ // 8 threads provide a significant advantage over 1 thread, but adding more
+ // threads provides only marginal speedup.
+ SetThreadpoolThreadMaximum(result->threadpool_, 16);
+ SetThreadpoolThreadMinimum(result->threadpool_, 8);
+
+ InitializeThreadpoolEnvironment(&result->threadpool_env_);
+ SetThreadpoolCallbackPool(&result->threadpool_env_, result->threadpool_);
+ SetThreadpoolCallbackCleanupGroup(&result->threadpool_env_,
+ result->cleanup_group_, NULL);
+
+ return result.release(); // release pointer ownership
+}
+
+void WindowsDumper::Dump(const void* data, const size_t size,
+ const string& path) {
+ if (was_error_) {
+ return;
+ }
+
+ unique_ptr<uint8_t[]> data_copy(new uint8_t[size]);
+ memcpy(data_copy.get(), data, size);
+ unique_ptr<DumpContext> ctx(
+ new DumpContext(std::move(data_copy), size, path, &dir_cache_lock_,
+ &dir_cache_, &was_error_, &error_msg_));
+ PTP_WORK w = CreateThreadpoolWork(WorkCallback, ctx.get(), &threadpool_env_);
+ if (w == NULL) {
+ string err = GetLastErrorString();
+ if (!was_error_.exchange(true)) {
+ // Benign race condition: though we use no locks to access `error_msg_`,
+ // only one thread may ever flip `was_error_` from false to true and enter
+ // the body of this if-clause. Since `was_error_` is the same object as
+ // used by all other threads trying to write to `error_msg_` (see
+ // DumpContext::MaybeSignalError), using it provides adequate mutual
+ // exclusion to write `error_msg_`.
+ error_msg_ = string("WindowsDumper::Dump() couldn't submit work: ") + err;
+ }
+ } else {
+ ctx.release(); // release pointer ownership
+ SubmitThreadpoolWork(w);
+ }
+}
+
+bool WindowsDumper::Finish(string* error) {
+ if (threadpool_ == NULL) {
+ return true;
+ }
+ CloseThreadpoolCleanupGroupMembers(cleanup_group_, FALSE, NULL);
+ CloseThreadpoolCleanupGroup(cleanup_group_);
+ CloseThreadpool(threadpool_);
+ threadpool_ = NULL;
+ cleanup_group_ = NULL;
+ if (was_error_ && error) {
+ // No race condition reading `error_msg_`: all worker threads terminated
+ // by now.
+ *error = error_msg_;
+ }
+ return !was_error_;
+}
+
+namespace {
+
+DumpContext::DumpContext(
+ unique_ptr<uint8_t[]> data, const size_t size, const string path,
+ std::mutex* dir_cache_lock, std::set<string>* dir_cache,
+ std::atomic_bool* was_error, string* error_msg)
+ : data_(std::move(data)), size_(size), path_(path),
+ dir_cache_lock_(dir_cache_lock), dir_cache_(dir_cache),
+ was_error_(was_error), error_msg_(error_msg) {}
+
+void DumpContext::Run() {
+ string dirname = blaze_util::Dirname(path_);
+
+ bool success = true;
+ // Performance optimization: memoize the paths we already created a
+ // directory for, to spare a stat in attempting to recreate an already
+ // existing directory. This optimization alone shaves off seconds from the
+ // extraction time on Windows.
+ {
+ std::lock_guard<std::mutex> guard(*dir_cache_lock_);
+ if (dir_cache_->insert(dirname).second) {
+ success = blaze_util::MakeDirectories(dirname, 0777);
+ }
+ }
+
+ if (!success) {
+ MaybeSignalError(string("Couldn't create directory '") + dirname + "'");
+ return;
+ }
+
+ if (!blaze_util::WriteFile(data_.get(), size_, path_, 0755)) {
+ MaybeSignalError(string("Failed to write zipped file '") + path_ + "'");
+ }
+}
+
+void DumpContext::MaybeSignalError(const string& msg) {
+ if (!was_error_->exchange(true)) {
+ // Benign race condition: though we use no locks to access `error_msg_`,
+ // only one thread may ever flip `was_error_` from false to true and enter
+ // the body of this if-clause. Since `was_error_` is the same object as used
+ // by all other threads and by WindowsDumper::Dump(), using it provides
+ // adequate mutual exclusion to write `error_msg_`.
+ *error_msg_ = msg;
+ }
+}
+
+VOID CALLBACK WorkCallback(
+ _Inout_ PTP_CALLBACK_INSTANCE Instance,
+ _Inout_opt_ PVOID Context,
+ _Inout_ PTP_WORK Work) {
+ unique_ptr<DumpContext> ctx(reinterpret_cast<DumpContext*>(Context));
+ ctx->Run();
+}
+
+
+} // namespace
+
+} // namespace embedded_binaries
+
SignalHandler SignalHandler::INSTANCE;
class WindowsClock {
| null | train | train | 2018-07-16T10:12:34 | "2018-07-04T11:46:48Z" | laszlocsomor | test |
bazelbuild/bazel/5513_5527 | bazelbuild/bazel | bazelbuild/bazel/5513 | bazelbuild/bazel/5527 | [
"timestamp(timedelta=0.0, similarity=0.9050090693317487)"
] | bc898cabe7cece0cf868447392f6863cb134d85c | 102b05b49fa757361a4488d91745c69f8f41c828 | [] | [] | "2018-07-06T10:41:05Z" | [
"type: bug"
] | Bazel server: race condition in JavaIoFileSystem.delete() | ### Description of the problem / feature request:
There's a race condition in: https://github.com/bazelbuild/bazel/blob/a320e4460f35767da7fc8eb824ce1f4b304b5e0f/src/main/java/com/google/devtools/build/lib/vfs/JavaIoFileSystem.java#L353
If the directory is deleted or replaced by a file between the `file.isDirectory()` check and the `file.list()` call, then `file.list()` returns null and throws an NPE.
There may be other such race conditions in Bazel's VFS library.
### What's the output of `bazel info release`?
release 0.15.0 | [
"src/main/java/com/google/devtools/build/lib/vfs/JavaIoFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/BUILD",
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java"
] | [
"src/main/java/com/google/devtools/build/lib/vfs/JavaIoFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/BUILD",
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/vfs/JavaIoFileSystem.java b/src/main/java/com/google/devtools/build/lib/vfs/JavaIoFileSystem.java
index ea541b4a1e020a..25fafac67bb3f7 100644
--- a/src/main/java/com/google/devtools/build/lib/vfs/JavaIoFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/vfs/JavaIoFileSystem.java
@@ -343,22 +343,42 @@ protected long getFileSize(Path path, boolean followSymlinks) throws IOException
@Override
public boolean delete(Path path) throws IOException {
- File file = getIoFile(path);
+ java.nio.file.Path nioPath = getNioPath(path);
long startTime = Profiler.nanoTimeMaybe();
try {
- if (file.delete()) {
- return true;
- }
- if (file.exists()) {
- if (file.isDirectory() && file.list().length > 0) {
- throw new IOException(path + ERR_DIRECTORY_NOT_EMPTY);
- } else {
- throw new IOException(path + ERR_PERMISSION_DENIED);
- }
+ return Files.deleteIfExists(nioPath);
+ } catch (java.nio.file.DirectoryNotEmptyException e) {
+ throw new IOException(path.getPathString() + ERR_DIRECTORY_NOT_EMPTY);
+ } catch (java.nio.file.AccessDeniedException e) {
+ throw new IOException(path.getPathString() + ERR_PERMISSION_DENIED);
+ } catch (java.nio.file.AtomicMoveNotSupportedException
+ | java.nio.file.FileAlreadyExistsException
+ | java.nio.file.FileSystemLoopException
+ | java.nio.file.NoSuchFileException
+ | java.nio.file.NotDirectoryException
+ | java.nio.file.NotLinkException e) {
+ // All known but unexpected subclasses of FileSystemException.
+ throw new IOException(path.getPathString() + ": unexpected FileSystemException", e);
+ } catch (java.nio.file.FileSystemException e) {
+ // Files.deleteIfExists() throws FileSystemException on Linux if a path component is a file.
+ // We caught all known subclasses of FileSystemException so `e` is either an unknown
+ // subclass or it is indeed a "Not a directory" error. Non-English JDKs may use a different
+ // error message than "Not a directory", so we should not look for that text. Checking the
+ // parent directory if it's indeed a directory is unrealiable, because another process may
+ // modify it concurrently... but we have no better choice.
+ if (e.getClass().equals(java.nio.file.FileSystemException.class)
+ && !nioPath.getParent().toFile().isDirectory()) {
+ // Hopefully the try-block failed because a parent directory was in fact not a directory.
+ // Theoretically it's possible that the try-block failed for some other reason and all
+ // parent directories were indeed directories, but another process changed a parent
+ // directory into a file after the try-block failed but before this catch-block started, and
+ // we return false here losing the real exception in `e`, but we cannot know.
+ return false;
+ } else {
+ throw new IOException(path.getPathString() + ": unexpected FileSystemException", e);
}
- return false;
} finally {
- profiler.logSimpleTask(startTime, ProfilerTask.VFS_DELETE, file.getPath());
+ profiler.logSimpleTask(startTime, ProfilerTask.VFS_DELETE, path.getPathString());
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/windows/BUILD b/src/main/java/com/google/devtools/build/lib/windows/BUILD
index 4b6e08c73a3285..61eb83acee2bcf 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/windows/BUILD
@@ -33,6 +33,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib:os_util",
"//src/main/java/com/google/devtools/build/lib/clock",
"//src/main/java/com/google/devtools/build/lib/concurrent",
+ "//src/main/java/com/google/devtools/build/lib/profiler",
"//src/main/java/com/google/devtools/build/lib/shell",
"//src/main/java/com/google/devtools/build/lib/vfs",
"//src/main/java/com/google/devtools/build/lib/windows/jni",
diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
index 0fd7028d6b7b62..869ba85d627039 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
@@ -15,6 +15,8 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.devtools.build.lib.concurrent.ThreadSafety.ThreadSafe;
+import com.google.devtools.build.lib.profiler.Profiler;
+import com.google.devtools.build.lib.profiler.ProfilerTask;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileStatus;
import com.google.devtools.build.lib.vfs.JavaIoFileSystem;
@@ -48,6 +50,20 @@ public String getFileSystemType(Path path) {
return "ntfs";
}
+ @Override
+ public boolean delete(Path path) throws IOException {
+ long startTime = Profiler.nanoTimeMaybe();
+ try {
+ return WindowsFileOperations.deletePath(path.getPathString());
+ } catch (java.nio.file.DirectoryNotEmptyException e) {
+ throw new IOException(path.getPathString() + ERR_DIRECTORY_NOT_EMPTY);
+ } catch (java.nio.file.AccessDeniedException e) {
+ throw new IOException(path.getPathString() + ERR_PERMISSION_DENIED);
+ } finally {
+ profiler.logSimpleTask(startTime, ProfilerTask.VFS_DELETE, path.getPathString());
+ }
+ }
+
@Override
protected void createSymbolicLink(Path linkPath, PathFragment targetFragment) throws IOException {
Path targetPath =
diff --git a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
index 32868c204db75a..6a16ab8aab7668 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
@@ -49,12 +49,21 @@ private WindowsFileOperations() {
private static final int IS_JUNCTION_NO = 1;
private static final int IS_JUNCTION_ERROR = 2;
+ // Keep DELETE_PATH_* values in sync with src/main/native/windows/file.cc.
+ private static final int DELETE_PATH_SUCCESS = 0;
+ private static final int DELETE_PATH_DOES_NOT_EXIST = 1;
+ private static final int DELETE_PATH_DIRECTORY_NOT_EMPTY = 2;
+ private static final int DELETE_PATH_ACCESS_DENIED = 3;
+ private static final int DELETE_PATH_ERROR = 4;
+
private static native int nativeIsJunction(String path, String[] error);
private static native boolean nativeGetLongPath(String path, String[] result, String[] error);
private static native boolean nativeCreateJunction(String name, String target, String[] error);
+ private static native int nativeDeletePath(String path, String[] error);
+
/** Determines whether `path` is a junction point or directory symlink. */
public static boolean isJunction(String path) throws IOException {
WindowsJniLoader.loadJni();
@@ -121,4 +130,22 @@ public static void createJunction(String name, String target) throws IOException
String.format("Cannot create junction (name=%s, target=%s): %s", name, target, error[0]));
}
}
+
+ public static boolean deletePath(String path) throws IOException {
+ WindowsJniLoader.loadJni();
+ String[] error = new String[] {null};
+ int result = nativeDeletePath(asLongPath(path), error);
+ switch (result) {
+ case DELETE_PATH_SUCCESS:
+ return true;
+ case DELETE_PATH_DOES_NOT_EXIST:
+ return false;
+ case DELETE_PATH_DIRECTORY_NOT_EMPTY:
+ throw new java.nio.file.DirectoryNotEmptyException(path);
+ case DELETE_PATH_ACCESS_DENIED:
+ throw new java.nio.file.AccessDeniedException(path);
+ default:
+ throw new IOException(String.format("Cannot delete path '%s': %s", path, error[0]));
+ }
+ }
}
| null | val | train | 2018-07-06T12:24:31 | "2018-07-04T11:55:36Z" | laszlocsomor | test |
bazelbuild/bazel/5534_5535 | bazelbuild/bazel | bazelbuild/bazel/5534 | bazelbuild/bazel/5535 | [
"timestamp(timedelta=1.0, similarity=0.931227190370861)"
] | 3ac44db0427b7db46b6c39f7dbfab7b5f31f8c37 | 74afaca6f9e050c92e92a8d8aeaa4955ff2472a1 | [] | [] | "2018-07-07T01:56:41Z" | [] | Skylint crashes on augmented assignments to IndexExpression. | ### Description of the problem / feature request:
> Skylint crashes when invoked on a snippet like:
```
d["foo"] += "bar"
```
### Feature requests: what underlying problem are you trying to solve with this feature?
> Skylint crash
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
> Run Skylint on a file with `d["foo"] += "bar"`
| [
"src/tools/skylark/java/com/google/devtools/skylark/skylint/BadOperationChecker.java",
"src/tools/skylark/javatests/com/google/devtools/skylark/skylint/BadOperationCheckerTest.java"
] | [
"src/tools/skylark/java/com/google/devtools/skylark/skylint/BadOperationChecker.java",
"src/tools/skylark/javatests/com/google/devtools/skylark/skylint/BadOperationCheckerTest.java"
] | [] | diff --git a/src/tools/skylark/java/com/google/devtools/skylark/skylint/BadOperationChecker.java b/src/tools/skylark/java/com/google/devtools/skylark/skylint/BadOperationChecker.java
index 09df8ff7fe7e0e..cb9460ad010a9b 100644
--- a/src/tools/skylark/java/com/google/devtools/skylark/skylint/BadOperationChecker.java
+++ b/src/tools/skylark/java/com/google/devtools/skylark/skylint/BadOperationChecker.java
@@ -137,7 +137,13 @@ public void visit(BinaryOperatorExpression node) {
@Override
public void visit(AugmentedAssignmentStatement node) {
super.visit(node);
- Identifier ident = Iterables.getOnlyElement(node.getLValue().boundIdentifiers());
+ ImmutableSet<Identifier> lvalues = node.getLValue().boundIdentifiers();
+ if (lvalues.size() != 1) {
+ // assignment visitor does not track information about assignments to IndexExpressions like
+ // kwargs["name"] += "foo" so nothing to do here until that changes
+ return;
+ }
+ Identifier ident = Iterables.getOnlyElement(lvalues);
NodeType identType = getInferredTypeOrNull(ident);
NodeType expressionType = getInferredTypeOrNull(node.getExpression());
if (identType == NodeType.DICT || expressionType == NodeType.DICT) {
diff --git a/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/BadOperationCheckerTest.java b/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/BadOperationCheckerTest.java
index 27c1063147d9d8..20cd662de72bea 100644
--- a/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/BadOperationCheckerTest.java
+++ b/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/BadOperationCheckerTest.java
@@ -152,4 +152,9 @@ public void divisionOperator() {
.contains("1:1-1:5: '/' operator is deprecated");
Truth.assertThat(findIssues("5 // 2")).isEmpty();
}
+
+ @Test
+ public void augmentedAssignmentOperator() {
+ Truth.assertThat(findIssues("kwargs['name'] += 'foo'")).isEmpty();
+ }
}
| null | train | train | 2018-07-06T20:19:22 | "2018-07-07T01:55:37Z" | ttsugriy | test |
bazelbuild/bazel/5585_6296 | bazelbuild/bazel | bazelbuild/bazel/5585 | bazelbuild/bazel/6296 | [
"timestamp(timedelta=1.0, similarity=0.9596030179739292)"
] | c5bb9b018764c257cf9d36c0e310423ec61a4594 | 1fc559620f9c0af78be1e5f545ca165b27d5ae46 | [
"Looking at this, support should be pretty simple it seems? Even almost working as-is?",
"Looking at the commit, never mind 😄 "
] | [] | "2018-10-03T18:07:49Z" | [
"type: feature request",
"P2",
"team-Android"
] | Support NDK r18 | Expected release date: [September 2018](https://github.com/android-ndk/ndk/wiki#ndk-r18)
Beta 1 should be out later this month.
Roadmap: https://android.googlesource.com/platform/ndk/+/master/docs/Roadmap.md
Expected changes to Bazel:
- Remove support for non-`libc++` STLs
> libc++ has been the default for a release and has proven to be stable. It is a strict improvement over the other STLs (more features, better Clang compatibility, Apache licensed, most reliable). The fact that the NDK supports multiple STLs is a common pain point for users (it's confusing for newcomers, and it makes sharing libraries difficult because they must all use the same STL).
> Now that we have a good choice for a single STL, we‘ll remove the others. We’ll most likely move the source we have for these along with building instructions to a separate project so that people that need these for ABI compatibility reasons can continue using them, but support for these will end completely.
- Remove support for GCC
> GCC is still in the NDK today because some of gnustl's C++11 features were written such that they do not work with Clang (threading and atomics, mostly). Now that libc++ is the best choice of STL, this is no longer blocking, so GCC can be removed. | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpl.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpls.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpl.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpls.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/AndroidNdkCrosstoolsR18.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ApiLevelR18.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/NdkMajorRevisionR18.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/X86Crosstools.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java
index c4a1d77e278593..716135552158fe 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryFunction.java
@@ -211,7 +211,7 @@ public RepositoryDirectoryValue.Builder fetch(
String hostPlatform = AndroidNdkCrosstools.getHostPlatform(ndkRelease);
NdkPaths ndkPaths = new NdkPaths(ruleName, hostPlatform, apiLevel, ndkRelease.majorRevision);
- for (StlImpl stlImpl : StlImpls.get(ndkPaths)) {
+ for (StlImpl stlImpl : StlImpls.get(ndkPaths, ndkRelease.majorRevision)) {
CrosstoolRelease crosstoolRelease =
ndkMajorRevision.crosstoolRelease(ndkPaths, stlImpl, hostPlatform);
crosstoolsAndStls.add(new CrosstoolStlPair(crosstoolRelease, stlImpl));
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
index 8823899c055306..d595dfe5b340d2 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
@@ -22,6 +22,7 @@
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r13.NdkMajorRevisionR13;
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r15.NdkMajorRevisionR15;
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r17.NdkMajorRevisionR17;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18.NdkMajorRevisionR18;
import com.google.devtools.build.lib.util.OS;
import java.util.Map;
@@ -48,6 +49,7 @@ private AndroidNdkCrosstools() {}
// usage of the unified headers. Support for unified headers were added in r15.
.put(16, new NdkMajorRevisionR15("5.0.300080")) // no changes relevant to Bazel
.put(17, new NdkMajorRevisionR17("6.0.2"))
+ .put(18, new NdkMajorRevisionR18("7.0.2"))
.build();
public static final Map.Entry<Integer, NdkMajorRevision> LATEST_KNOWN_REVISION =
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpl.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpl.java
index b132258aeba370..f9ae3f889b3936 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpl.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpl.java
@@ -21,6 +21,7 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import javax.annotation.Nullable;
/**
* An NdkStlImpl adds a specific Android NDK C++ STL implementation to a given CToolchain proto
@@ -55,7 +56,7 @@ protected StlImpl(String name, NdkPaths ndkPaths) {
}
public void addStlImpl(
- List<CToolchain.Builder> baseToolchains, String gccVersion) {
+ List<CToolchain.Builder> baseToolchains, @Nullable String gccVersion) {
for (CToolchain.Builder baseToolchain : baseToolchains) {
addStlImpl(baseToolchain, gccVersion);
@@ -68,9 +69,9 @@ public void addStlImpl(
* @param toolchain the toolchain to add the STL implementation to
* @param gccVersion the gcc version for the STL impl. Applicable only to gnu-libstdc++
*/
- public abstract void addStlImpl(CToolchain.Builder toolchain, String gccVersion);
+ public abstract void addStlImpl(CToolchain.Builder toolchain, @Nullable String gccVersion);
- protected void addBaseStlImpl(CToolchain.Builder toolchain, String gccVersion) {
+ protected void addBaseStlImpl(CToolchain.Builder toolchain, @Nullable String gccVersion) {
toolchain
.setToolchainIdentifier(toolchain.getToolchainIdentifier() + "-" + name)
@@ -84,7 +85,7 @@ protected void addBaseStlImpl(CToolchain.Builder toolchain, String gccVersion) {
}
private String createRuntimeLibrariesFilegroup(
- String stl, String gccVersion, String targetCpu, RuntimeType type) {
+ String stl, @Nullable String gccVersion, String targetCpu, RuntimeType type) {
// gnu-libstlc++ has separate libraries for 4.8 and 4.9
String fullStlName = stl;
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpls.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpls.java
index 9c64b18df99ac4..4a0fed51c6cf9e 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpls.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/StlImpls.java
@@ -17,6 +17,7 @@
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
import java.util.List;
+import javax.annotation.Nullable;
/**
* Class that contains implementations of NdkStlImpl, one for each STL implementation of the STL
@@ -35,7 +36,7 @@ public GnuLibStdCppStlImpl(NdkPaths ndkPaths) {
}
@Override
- public void addStlImpl(CToolchain.Builder toolchain, String gccVersion) {
+ public void addStlImpl(CToolchain.Builder toolchain, @Nullable String gccVersion) {
addBaseStlImpl(toolchain, gccVersion);
toolchain.addAllUnfilteredCxxFlag(createIncludeFlags(
ndkPaths.createGnuLibstdcIncludePaths(gccVersion, toolchain.getTargetCpu())));
@@ -51,7 +52,7 @@ public LibCppStlImpl(NdkPaths ndkPaths) {
}
@Override
- public void addStlImpl(CToolchain.Builder toolchain, String gccVersion) {
+ public void addStlImpl(CToolchain.Builder toolchain, @Nullable String gccVersion) {
addBaseStlImpl(toolchain, null);
toolchain.addAllUnfilteredCxxFlag(createIncludeFlags(ndkPaths.createLibcxxIncludePaths()));
toolchain.addLinkerFlag("-L" + ndkPaths.createLibcppLinkerPath(toolchain.getTargetCpu()));
@@ -67,20 +68,27 @@ public StlPortStlImpl(NdkPaths ndkPaths) {
}
@Override
- public void addStlImpl(CToolchain.Builder toolchain, String gccVersion) {
+ public void addStlImpl(CToolchain.Builder toolchain, @Nullable String gccVersion) {
addBaseStlImpl(toolchain, null);
toolchain.addAllUnfilteredCxxFlag(createIncludeFlags(ndkPaths.createStlportIncludePaths()));
}
}
/**
+ * Gets the list of runtime libraries (STL) in the NDK.
+ *
+ * NDK r17 and lower contains gnustl, STLport and libc++.
+ * NDK r18 and above contains libc++ only.
+ *
* @param ndkPaths NdkPaths to use for creating the NdkStlImpls
* @return an ImmutableList of every available NdkStlImpl
*/
- public static List<StlImpl> get(NdkPaths ndkPaths) {
- return ImmutableList.of(
- new GnuLibStdCppStlImpl(ndkPaths),
- new StlPortStlImpl(ndkPaths),
- new LibCppStlImpl(ndkPaths));
+ public static List<StlImpl> get(NdkPaths ndkPaths, Integer ndkMajorRevision) {
+ return ndkMajorRevision < 18
+ ? ImmutableList.of(
+ new GnuLibStdCppStlImpl(ndkPaths),
+ new StlPortStlImpl(ndkPaths),
+ new LibCppStlImpl(ndkPaths))
+ : ImmutableList.of(new LibCppStlImpl(ndkPaths));
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/AndroidNdkCrosstoolsR18.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/AndroidNdkCrosstoolsR18.java
new file mode 100644
index 00000000000000..7f241986e383cb
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/AndroidNdkCrosstoolsR18.java
@@ -0,0 +1,108 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.DefaultCpuToolchain;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/** Generates a CrosstoolRelease proto for the Android NDK. */
+final class AndroidNdkCrosstoolsR18 {
+
+ /**
+ * Creates a CrosstoolRelease proto for the Android NDK, given the API level to use and the
+ * release revision. The crosstools are generated through code rather than checked in as a flat
+ * file to reduce the amount of templating needed (for parameters like the release name and
+ * certain paths), to reduce duplication, and to make it easier to support future versions of the
+ * NDK. TODO(bazel-team): Eventually we should move this into Skylark so the crosstools can be
+ * updated independently of Bazel itself.
+ *
+ * @return A CrosstoolRelease for the Android NDK.
+ */
+ static CrosstoolRelease create(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+ return CrosstoolRelease.newBuilder()
+ .setMajorVersion("android")
+ .setMinorVersion("")
+ .setDefaultTargetCpu("armeabi")
+ .addAllDefaultToolchain(getDefaultCpuToolchains(stlImpl, clangVersion))
+ .addAllToolchain(createToolchains(ndkPaths, stlImpl, hostPlatform, clangVersion))
+ .build();
+ }
+
+ private static ImmutableList<CToolchain> createToolchains(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+
+ List<CToolchain.Builder> toolchainBuilders = new ArrayList<>();
+ toolchainBuilders.addAll(new ArmCrosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+ toolchainBuilders.addAll(new X86Crosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+
+ ImmutableList.Builder<CToolchain> toolchains = new ImmutableList.Builder<>();
+
+ // Set attributes common to all toolchains.
+ for (CToolchain.Builder toolchainBuilder : toolchainBuilders) {
+ toolchainBuilder
+ .setHostSystemName(hostPlatform)
+ .setTargetLibc("local")
+ .setAbiVersion(toolchainBuilder.getTargetCpu())
+ .setAbiLibcVersion("local");
+
+ // builtin_sysroot is set individually on each toolchain.
+ // platforms/arch sysroot
+ toolchainBuilder.addCxxBuiltinIncludeDirectory("%sysroot%/usr/include");
+ toolchainBuilder.addCxxBuiltinIncludeDirectory(
+ ndkPaths.createBuiltinSysroot() + "/usr/include");
+ toolchainBuilder.addUnfilteredCxxFlag(
+ "-isystem%ndk%/usr/include".replace("%ndk%", ndkPaths.createBuiltinSysroot()));
+
+ toolchains.add(toolchainBuilder.build());
+ }
+
+ return toolchains.build();
+ }
+
+ private static ImmutableList<DefaultCpuToolchain> getDefaultCpuToolchains(
+ StlImpl stlImpl, String clangVersion) {
+ // TODO(bazel-team): It would be better to auto-generate this somehow.
+
+ ImmutableMap<String, String> defaultCpus =
+ ImmutableMap.<String, String>builder()
+ // arm
+ .put("armeabi-v7a", "arm-linux-androideabi-clang" + clangVersion + "-v7a")
+ .put("arm64-v8a", "aarch64-linux-android-clang" + clangVersion)
+
+ // x86
+ .put("x86", "x86-clang" + clangVersion)
+ .put("x86_64", "x86_64-clang" + clangVersion)
+ .build();
+
+ ImmutableList.Builder<DefaultCpuToolchain> defaultCpuToolchains = ImmutableList.builder();
+ for (Map.Entry<String, String> defaultCpu : defaultCpus.entrySet()) {
+ defaultCpuToolchains.add(
+ DefaultCpuToolchain.newBuilder()
+ .setCpu(defaultCpu.getKey())
+ .setToolchainIdentifier(defaultCpu.getValue() + "-" + stlImpl.getName())
+ .build());
+ }
+ return defaultCpuToolchains.build();
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ApiLevelR18.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ApiLevelR18.java
new file mode 100644
index 00000000000000..42a739a1f2feb1
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ApiLevelR18.java
@@ -0,0 +1,61 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18;
+
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.events.EventHandler;
+
+/** Class which encodes information from the Android NDK makefiles about API levels. */
+final class ApiLevelR18 extends ApiLevel {
+ /** This is the contents of {@code platforms/android-*} */
+ private static final ImmutableListMultimap<String, String> API_LEVEL_TO_ARCHITECTURES =
+ ImmutableListMultimap.<String, String>builder()
+ .putAll("16", "arm", "x86")
+ .putAll("17", "arm", "x86")
+ .putAll("18", "arm", "x86")
+ .putAll("19", "arm", "x86")
+ .putAll("21", "arm", "x86", "arm64", "x86_64")
+ .putAll("22", "arm", "x86", "arm64", "x86_64")
+ .putAll("23", "arm", "x86", "arm64", "x86_64")
+ .putAll("24", "arm", "x86", "arm64", "x86_64")
+ .putAll("26", "arm", "x86", "arm64", "x86_64")
+ .putAll("27", "arm", "x86", "arm64", "x86_64")
+ .putAll("28", "arm", "x86", "arm64", "x86_64")
+ .build();
+
+ /** This map fill in the gaps of {@code API_LEVEL_TO_ARCHITECTURES}. */
+ private static final ImmutableMap<String, String> API_EQUIVALENCIES =
+ ImmutableMap.<String, String>builder()
+ .put("16", "16")
+ .put("17", "16")
+ .put("18", "18")
+ .put("19", "19")
+ .put("20", "19")
+ .put("21", "21")
+ .put("22", "22")
+ .put("23", "23")
+ .put("24", "24")
+ .put("25", "24")
+ .put("26", "26")
+ .put("27", "27")
+ .put("28", "28")
+ .build();
+
+ ApiLevelR18(EventHandler eventHandler, String repositoryName, String apiLevel) {
+ super(API_LEVEL_TO_ARCHITECTURES, API_EQUIVALENCIES, eventHandler, repositoryName, apiLevel);
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ArmCrosstools.java
new file mode 100644
index 00000000000000..9e0d9e7f24fa32
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ArmCrosstools.java
@@ -0,0 +1,172 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for ARM. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class ArmCrosstools {
+ private final NdkPaths ndkPaths;
+ private final StlImpl stlImpl;
+ private final String clangVersion;
+
+ ArmCrosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+ this.ndkPaths = ndkPaths;
+ this.stlImpl = stlImpl;
+ this.clangVersion = clangVersion;
+ }
+
+ ImmutableList<CToolchain.Builder> createCrosstools() {
+ CToolchain.Builder aarch64Toolchain = createAarch64ClangToolchain();
+ CToolchain.Builder armeabiToolchain = createArmeabiClangToolchain();
+
+ stlImpl.addStlImpl(aarch64Toolchain, "4.9");
+ stlImpl.addStlImpl(armeabiToolchain, "4.9");
+
+ return ImmutableList.<CToolchain.Builder>builder()
+ .add(aarch64Toolchain)
+ .add(armeabiToolchain)
+ .build();
+ }
+
+ private CToolchain.Builder createAarch64ClangToolchain() {
+ String toolchainName = "aarch64-linux-android-4.9";
+ String targetPlatform = "aarch64-linux-android";
+ String gccToolchain = ndkPaths.createGccToolchainPath(toolchainName);
+ String llvmTriple = "aarch64-none-linux-android";
+
+ return CToolchain.newBuilder()
+ .setToolchainIdentifier("aarch64-linux-android-clang" + clangVersion)
+ .setTargetSystemName(targetPlatform)
+ .setTargetCpu("arm64-v8a")
+ .setCompiler("clang" + clangVersion)
+ .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm64"))
+
+ // Compiler flags
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-target")
+ .addCompilerFlag(llvmTriple)
+ .addCompilerFlag("-ffunction-sections")
+ .addCompilerFlag("-funwind-tables")
+ .addCompilerFlag("-fstack-protector-strong")
+ .addCompilerFlag("-fpic")
+ .addCompilerFlag("-Wno-invalid-command-line-argument")
+ .addCompilerFlag("-Wno-unused-command-line-argument")
+ .addCompilerFlag("-no-canonical-prefixes")
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", targetPlatform))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+
+ // Linker flags
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-target")
+ .addLinkerFlag(llvmTriple)
+ .addLinkerFlag("-no-canonical-prefixes")
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-O2")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-UNDEBUG"));
+ }
+
+ private CToolchain.Builder createArmeabiClangToolchain() {
+ String toolchainName = "arm-linux-androideabi-4.9";
+ String targetPlatform = "arm-linux-androideabi";
+ String gccToolchain = ndkPaths.createGccToolchainPath("arm-linux-androideabi-4.9");
+
+ return CToolchain.newBuilder()
+ .setToolchainIdentifier("arm-linux-androideabi-clang" + clangVersion + "-v7a")
+ .setTargetCpu("armeabi-v7a")
+ .setTargetSystemName("arm-linux-androideabi")
+ .setCompiler("clang" + clangVersion)
+ .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm"))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", targetPlatform))
+
+ // Compiler flags
+ .addCompilerFlag("-target")
+ .addCompilerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+ .addCompilerFlag("-march=armv7-a")
+ .addCompilerFlag("-mfloat-abi=softfp")
+ .addCompilerFlag("-mfpu=vfpv3-d16")
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-fpic")
+ .addCompilerFlag("-ffunction-sections")
+ .addCompilerFlag("-funwind-tables")
+ .addCompilerFlag("-fstack-protector-strong")
+ .addCompilerFlag("-Wno-invalid-command-line-argument")
+ .addCompilerFlag("-Wno-unused-command-line-argument")
+ .addCompilerFlag("-no-canonical-prefixes")
+
+ // Linker flags
+ .addLinkerFlag("-target")
+ .addLinkerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+ .addLinkerFlag("-Wl,--fix-cortex-a8")
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-no-canonical-prefixes")
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-mthumb")
+ .addCompilerFlag("-Os")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-fno-strict-aliasing")
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-UNDEBUG"));
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/NdkMajorRevisionR18.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/NdkMajorRevisionR18.java
new file mode 100644
index 00000000000000..44a01ea445d80c
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/NdkMajorRevisionR18.java
@@ -0,0 +1,43 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18;
+
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkMajorRevision;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.events.EventHandler;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+
+/** Logic specific to Android NDK R17. */
+public class NdkMajorRevisionR18 implements NdkMajorRevision {
+ private final String clangVersion;
+
+ public NdkMajorRevisionR18(String clangVersion) {
+ this.clangVersion = clangVersion;
+ }
+
+ @Override
+ public CrosstoolRelease crosstoolRelease(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform) {
+ return AndroidNdkCrosstoolsR18
+ .create(ndkPaths, stlImpl, hostPlatform, clangVersion);
+ }
+
+ @Override
+ public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
+ return new ApiLevelR18(eventHandler, name, apiLevel);
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/X86Crosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/X86Crosstools.java
new file mode 100644
index 00000000000000..dd01408d92c1f5
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/X86Crosstools.java
@@ -0,0 +1,118 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for x86. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class X86Crosstools {
+ private final NdkPaths ndkPaths;
+ private final StlImpl stlImpl;
+ private final String clangVersion;
+
+ X86Crosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+ this.ndkPaths = ndkPaths;
+ this.stlImpl = stlImpl;
+ this.clangVersion = clangVersion;
+ }
+
+ ImmutableList<CToolchain.Builder> createCrosstools() {
+ /** x86 */
+ // clang
+ CToolchain.Builder x86Clang =
+ createBaseX86ClangToolchain("x86", "i686", "i686-linux-android")
+ // Workaround for https://code.google.com/p/android/issues/detail?id=220159.
+ .addCompilerFlag("-mstackrealign")
+ .setToolchainIdentifier("x86-clang" + clangVersion)
+ .setTargetCpu("x86")
+ .addAllToolPath(ndkPaths.createClangToolpaths("x86-4.9", "i686-linux-android", null))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86"));
+
+ stlImpl.addStlImpl(x86Clang, null);
+
+ /** x86_64 */
+ CToolchain.Builder x8664Clang =
+ createBaseX86ClangToolchain("x86_64", "x86_64", "x86_64-linux-android")
+ .setToolchainIdentifier("x86_64-clang" + clangVersion)
+ .setTargetCpu("x86_64")
+ .addAllToolPath(
+ ndkPaths.createClangToolpaths("x86_64-4.9", "x86_64-linux-android", null))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86_64"));
+
+ stlImpl.addStlImpl(x8664Clang, null);
+
+ return ImmutableList.of(x86Clang, x8664Clang);
+ }
+
+ private CToolchain.Builder createBaseX86ClangToolchain(
+ String x86Arch, String llvmArch, String triple) {
+ String gccToolchain = ndkPaths.createGccToolchainPath(x86Arch + "-4.9");
+ String llvmTriple = llvmArch + "-none-linux-android";
+
+ return CToolchain.newBuilder()
+ .setCompiler("clang" + clangVersion)
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+
+ // Compiler flags
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-target")
+ .addCompilerFlag(llvmTriple)
+ .addCompilerFlag("-ffunction-sections")
+ .addCompilerFlag("-funwind-tables")
+ .addCompilerFlag("-fstack-protector-strong")
+ .addCompilerFlag("-fPIC")
+ .addCompilerFlag("-Wno-invalid-command-line-argument")
+ .addCompilerFlag("-Wno-unused-command-line-argument")
+ .addCompilerFlag("-no-canonical-prefixes")
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", triple))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel(x86Arch))
+
+ // Linker flags
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-target")
+ .addLinkerFlag(llvmTriple)
+ .addLinkerFlag("-no-canonical-prefixes")
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-O2")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-g"))
+ .setTargetSystemName("x86-linux-android");
+ }
+}
| null | test | train | 2018-10-03T19:47:25 | "2018-07-12T20:30:17Z" | jin | test |
bazelbuild/bazel/5589_5628 | bazelbuild/bazel | bazelbuild/bazel/5589 | bazelbuild/bazel/5628 | [
"timestamp(timedelta=0.0, similarity=0.9743079330526386)"
] | 80eb1935e9d8de5a566c36015f5457f8dca13a65 | 1d232fc59df9e6fc94e7b8d8df01fed15950f68d | [
"@meisterT for triage since this is perf related. I do agree that \"every 10 seconds full gc\" is not awesome.",
"I think we should delete this code. I have yet to see a benchmark showing that the application logic choosing to do a GC results in better performance than the JVM triggering the GC itself."
] | [
"I think it's better not to create the IdleServerTasks if we don't have to, so perhaps rename the option and check for nullness below. WDYT?",
"Contrary to my earlier statement, I think it's safer to default to the old behavior. Then, we can release it with the toggle and flip the default value in a later release.",
"You mean rename the command line option or something else?\r\n\r\nThe name `IdleServerTasks` implies a generic framework for executing tasks at idle not just GC. Of course, it's not currently used for anything else. So, if I make the refactor I think you're suggesting, maybe I should just rename it `IdleGCTaskRunner`.",
"That makes sense.",
"My suggestion is to keep the name IdleServerTasks and the generic framework.\r\nBut instead of disabling the GC part of it with --idle_gc=no, I would disable the whole IdleServerTasks with --idle_server_tasks=no. "
] | "2018-07-18T17:52:13Z" | [
"type: feature request"
] | add an option to disable the idle GC | If a Bazel server is idle for 10 seconds after finishing a command, it will invoke `System.gc()`. On HotSpot, `System.gc()` triggers an aggressive full GC. In practice, I see `System.gc()` in a Bazel server with a 2GB heap fully consume 4 cores for several seconds. This behavior is problematic for workflows that involve building a binary and then immediately running it; if the binary itself is resource intensive and long-running, Bazel will steal CPU from it. One can effectively disable the idle GC today with `--host_jvm_args=-XX:+DisableExplicitGC`, but this is hacky and makes instrumentation commands like `bazel info used-heap-size-after-gc` silently useless. So, I propose introducing an official startup flag to disable idle GC.
A new option is my conservative proposal. Going further, I'd be interested in learning the reasons for Bazel's idle GC behavior. To me, it's polite to only use lots of CPU when Bazel is synchronously processing a command. I suppose in theory an idle GC saves GC work during synchronous work, but can the value of that be measured? If a user is iterating by running `build` or `test` on the same target, most server state should be essentially persistent and won't benefit from being repeatedly walked by a full GC. If the idle GC is valuable, could Bazel use a whole-system idleness check in lieu of the current 10 second heuristic? | [
"src/main/cpp/blaze.cc",
"src/main/cpp/startup_options.cc",
"src/main/cpp/startup_options.h",
"src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java",
"src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java",
"src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java",
"src/main/java/com/google/devtools/build/lib/server/IdleServerTasks.java",
"src/main/java/com/google/devtools/build/lib/server/RPCServer.java"
] | [
"src/main/cpp/blaze.cc",
"src/main/cpp/startup_options.cc",
"src/main/cpp/startup_options.h",
"src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java",
"src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java",
"src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java",
"src/main/java/com/google/devtools/build/lib/server/IdleServerTasks.java",
"src/main/java/com/google/devtools/build/lib/server/RPCServer.java"
] | [] | diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index 9e7d9798552d30..801a9314c00593 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -541,6 +541,11 @@ static vector<string> GetArgumentArray(
// being "null" to set the programmatic default in the server.
result.push_back("--digest_function=" + globals->options->digest_function);
}
+ if (globals->options->idle_server_tasks) {
+ result.push_back("--idle_server_tasks");
+ } else {
+ result.push_back("--noidle_server_tasks");
+ }
if (globals->options->oom_more_eagerly) {
result.push_back("--experimental_oom_more_eagerly");
} else {
diff --git a/src/main/cpp/startup_options.cc b/src/main/cpp/startup_options.cc
index a2d26b74d3f048..c54728f92e0a2a 100644
--- a/src/main/cpp/startup_options.cc
+++ b/src/main/cpp/startup_options.cc
@@ -93,6 +93,7 @@ StartupOptions::StartupOptions(const string &product_name,
"com.google.devtools.build.lib.util.SingleLineFormatter"),
expand_configs_in_place(true),
digest_function(),
+ idle_server_tasks(true),
original_startup_options_(std::vector<RcStartupFlag>()) {
bool testing = !blaze::GetEnv("TEST_TMPDIR").empty();
if (testing) {
@@ -133,6 +134,7 @@ StartupOptions::StartupOptions(const string &product_name,
RegisterNullaryStartupFlag("experimental_oom_more_eagerly");
RegisterNullaryStartupFlag("fatal_event_bus_exceptions");
RegisterNullaryStartupFlag("host_jvm_debug");
+ RegisterNullaryStartupFlag("idle_server_tasks");
RegisterNullaryStartupFlag("ignore_all_rc_files");
RegisterNullaryStartupFlag("watchfs");
RegisterNullaryStartupFlag("write_command_log");
@@ -334,6 +336,12 @@ blaze_exit_code::ExitCode StartupOptions::ProcessArg(
} else if (GetNullaryOption(arg, "--noexpand_configs_in_place")) {
expand_configs_in_place = false;
option_sources["expand_configs_in_place"] = rcfile;
+ } else if (GetNullaryOption(arg, "--idle_server_tasks")) {
+ idle_server_tasks = true;
+ option_sources["idle_server_tasks"] = rcfile;
+ } else if (GetNullaryOption(arg, "--noidle_server_tasks")) {
+ idle_server_tasks = false;
+ option_sources["idle_server_tasks"] = rcfile;
} else if ((value = GetUnaryOption(arg, next_arg,
"--connect_timeout_secs")) != NULL) {
if (!blaze_util::safe_strto32(value, &connect_timeout_secs) ||
diff --git a/src/main/cpp/startup_options.h b/src/main/cpp/startup_options.h
index cca38369c33b0a..9f4cd0c622bdcd 100644
--- a/src/main/cpp/startup_options.h
+++ b/src/main/cpp/startup_options.h
@@ -301,6 +301,8 @@ class StartupOptions {
// The hash function to use when computing file digests.
std::string digest_function;
+ bool idle_server_tasks;
+
// The startup options as received from the user and rc files, tagged with
// their origin. This is populated by ProcessArgs.
std::vector<RcStartupFlag> original_startup_options_;
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java b/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java
index a8b1d0ae75d1cf..f3d86fcac1f65d 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java
@@ -925,11 +925,14 @@ private static int serverMain(Iterable<BlazeModule> modules, OutErr outErr, Stri
Class<?> factoryClass = Class.forName(
"com.google.devtools.build.lib.server.GrpcServerImpl$Factory");
RPCServer.Factory factory = (RPCServer.Factory) factoryClass.getConstructor().newInstance();
- rpcServer[0] = factory.create(dispatcher, runtime.getClock(),
+ rpcServer[0] = factory.create(
+ dispatcher,
+ runtime.getClock(),
startupOptions.commandPort,
runtime.getWorkspace().getWorkspace(),
runtime.getServerDirectory(),
- startupOptions.maxIdleSeconds);
+ startupOptions.maxIdleSeconds,
+ startupOptions.idleServerTasks);
} catch (ReflectiveOperationException | IllegalArgumentException e) {
throw new AbruptExitException("gRPC server not compiled in", ExitCode.BLAZE_INTERNAL_ERROR);
}
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java b/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java
index 6d434f8d568044..6b35fcde85905f 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java
@@ -430,4 +430,16 @@ public String getTypeDescription() {
"Changed the expansion of --config flags to be done in-place, as opposed to in a fixed "
+ "point expansion between normal rc options and command-line specified options.")
public boolean expandConfigsInPlace;
+
+ @Option(
+ name = "idle_server_tasks",
+ defaultValue = "true", // NOTE: only for documentation, value is set and used by the client.
+ documentationCategory = OptionDocumentationCategory.BAZEL_CLIENT_OPTIONS,
+ effectTags = {
+ OptionEffectTag.LOSES_INCREMENTAL_STATE,
+ OptionEffectTag.HOST_MACHINE_RESOURCE_OPTIMIZATIONS,
+ },
+ help = "Run System.gc() when the server is idle"
+ )
+ public boolean idleServerTasks;
}
diff --git a/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java b/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java
index 2d02631e409b81..43f9ab1713156d 100644
--- a/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java
+++ b/src/main/java/com/google/devtools/build/lib/server/GrpcServerImpl.java
@@ -152,10 +152,16 @@ public void close() {
*/
public static class Factory implements RPCServer.Factory {
@Override
- public RPCServer create(BlazeCommandDispatcher dispatcher, Clock clock, int port,
- Path workspace, Path serverDirectory, int maxIdleSeconds) throws IOException {
+ public RPCServer create(
+ BlazeCommandDispatcher dispatcher,
+ Clock clock,
+ int port,
+ Path workspace,
+ Path serverDirectory,
+ int maxIdleSeconds,
+ boolean idleServerTasks) throws IOException {
return new GrpcServerImpl(
- dispatcher, clock, port, workspace, serverDirectory, maxIdleSeconds);
+ dispatcher, clock, port, workspace, serverDirectory, maxIdleSeconds, idleServerTasks);
}
}
@@ -512,13 +518,20 @@ public void run() {
private final String pidInFile;
private final List<Path> filesToDeleteAtExit = new ArrayList<>();
private final int port;
+ private final boolean doIdleServerTasks;
private Server server;
private IdleServerTasks idleServerTasks;
boolean serving;
- public GrpcServerImpl(BlazeCommandDispatcher dispatcher, Clock clock, int port,
- Path workspace, Path serverDirectory, int maxIdleSeconds) throws IOException {
+ public GrpcServerImpl(
+ BlazeCommandDispatcher dispatcher,
+ Clock clock,
+ int port,
+ Path workspace,
+ Path serverDirectory,
+ int maxIdleSeconds,
+ boolean doIdleServerTasks) throws IOException {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
@@ -555,20 +568,24 @@ public void run() {
pidFileWatcherThread = new PidFileWatcherThread();
pidFileWatcherThread.start();
- idleServerTasks = new IdleServerTasks();
- idleServerTasks.idle();
+ this.doIdleServerTasks = doIdleServerTasks;
+ idle();
}
private void idle() {
Preconditions.checkState(idleServerTasks == null);
- idleServerTasks = new IdleServerTasks();
- idleServerTasks.idle();
+ if (doIdleServerTasks) {
+ idleServerTasks = new IdleServerTasks();
+ idleServerTasks.idle();
+ }
}
private void busy() {
- Preconditions.checkState(idleServerTasks != null);
- idleServerTasks.busy();
- idleServerTasks = null;
+ if (doIdleServerTasks) {
+ Preconditions.checkState(idleServerTasks != null);
+ idleServerTasks.busy();
+ idleServerTasks = null;
+ }
}
private static String generateCookie(SecureRandom random, int byteCount) {
diff --git a/src/main/java/com/google/devtools/build/lib/server/IdleServerTasks.java b/src/main/java/com/google/devtools/build/lib/server/IdleServerTasks.java
index 01e596a00c94f9..d8cb41a2b3ff92 100644
--- a/src/main/java/com/google/devtools/build/lib/server/IdleServerTasks.java
+++ b/src/main/java/com/google/devtools/build/lib/server/IdleServerTasks.java
@@ -16,6 +16,10 @@
import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.profiler.AutoProfiler;
+import com.google.devtools.build.lib.util.StringUtilities;
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryMXBean;
+import java.lang.management.MemoryUsage;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@@ -29,9 +33,7 @@ class IdleServerTasks {
private final ScheduledThreadPoolExecutor executor;
private static final Logger logger = Logger.getLogger(IdleServerTasks.class.getName());
- /**
- * Must be called from the main thread.
- */
+ /** Must be called from the main thread. */
public IdleServerTasks() {
this.executor = new ScheduledThreadPoolExecutor(1);
}
@@ -43,14 +45,23 @@ public IdleServerTasks() {
public void idle() {
Preconditions.checkState(!executor.isShutdown());
- // Do a GC cycle while the server is idle.
@SuppressWarnings("unused")
Future<?> possiblyIgnoredError =
executor.schedule(
() -> {
+ MemoryMXBean memBean = ManagementFactory.getMemoryMXBean();
+ MemoryUsage before = memBean.getHeapMemoryUsage();
try (AutoProfiler p = AutoProfiler.logged("Idle GC", logger)) {
System.gc();
}
+ MemoryUsage after = memBean.getHeapMemoryUsage();
+ logger.info(
+ String.format(
+ "[Idle GC] used: %s -> %s, committed: %s -> %s",
+ StringUtilities.prettyPrintBytes(before.getUsed()),
+ StringUtilities.prettyPrintBytes(after.getUsed()),
+ StringUtilities.prettyPrintBytes(before.getCommitted()),
+ StringUtilities.prettyPrintBytes(after.getCommitted())));
},
10,
TimeUnit.SECONDS);
diff --git a/src/main/java/com/google/devtools/build/lib/server/RPCServer.java b/src/main/java/com/google/devtools/build/lib/server/RPCServer.java
index 014b17b5ae423a..45833b2e3574f1 100644
--- a/src/main/java/com/google/devtools/build/lib/server/RPCServer.java
+++ b/src/main/java/com/google/devtools/build/lib/server/RPCServer.java
@@ -28,8 +28,14 @@ public interface RPCServer {
* Present so that we don't need to invoke a constructor with multiple arguments by reflection.
*/
interface Factory {
- RPCServer create(BlazeCommandDispatcher dispatcher, Clock clock, int port,
- Path workspace, Path serverDirectory, int maxIdleSeconds) throws IOException;
+ RPCServer create(
+ BlazeCommandDispatcher dispatcher,
+ Clock clock,
+ int port,
+ Path workspace,
+ Path serverDirectory,
+ int maxIdleSeconds,
+ boolean idleServerTasks) throws IOException;
}
/**
| null | val | train | 2018-08-06T07:22:58 | "2018-07-13T06:22:45Z" | benjaminp | test |
bazelbuild/bazel/5594_5894 | bazelbuild/bazel | bazelbuild/bazel/5594 | bazelbuild/bazel/5894 | [
"timestamp(timedelta=130064.0, similarity=0.8452684891346447)"
] | 8dece49bed76b5f372ff5d3a3f25a32b2a9c1f52 | 85b6b1d341d93c497e29609b2ed584c4bea12458 | [
"To confirm, is the request to support using the embedded JDK as the `--javabase`?\r\n\r\nIf the goal is to have `--javabase` versioned with your respository, have you considered versioning a separate JDK?",
"Not quite. What I'm really looking for is a way to completely eliminate uses of any JDKs found via `which javac` or `$JAVA_HOME` or any other form of looking around on the system. Experimenting with `--javabase=@embedded_jdk//:jdk --host_javabase=@embedded_jdk//:jdk` just now, builds still fail on a machine with a weird (broken?) JDK exposed via `which javac` because that JDK is missing jar files in places bazel expects them.\r\n\r\nI would also like a way to use the embedded JDK as the alternative so I have less stuff to version, but I wouldn't mind versioning a separate one via a bazel package too much.\r\n\r\nAs far as I can see, there are no user-accessible flags to change `@local_jdk`. src/main/cpp/blaze.cc always passes its own value for `--default_system_javabase`, and then everything else just uses that value. If there was some way to do that, I think it would be enough for my use case. I guess I could make my tools/bazel wrapper script download a fixed JDK, extract it, and set JAVA_HOME to point to it, but that seems like an awful lot of infrastructure to add to emulate something that used to just work. It's also a super trivial 1-line patch to make `StartupOptions::GetSystemJavabase()` return an empty string, and seems like it wouldn't be much harder to control that via a flag.",
"> > To confirm, is the request to support using the embedded JDK as the --javabase?\r\n>\r\n> Not quite. What I'm really looking for is a way to completely eliminate uses of any JDKs found via which javac or $JAVA_HOME or any other form of looking around on the system.\r\n\r\nTo try to recap, there are three JDKs:\r\n1) the JDK used to run Bazel itself. This is the `startup --host_javabase` (i.e. the LHS host_javabase)\r\n2) the JDK used to run host tools that run during the build, e.g. javac. This is the `build --host_javabase` (i.e. the RHS host_javabase)\r\n3) the JDK that the build is targeting, that is used to run any `java_binary` and `java_tests` that a build produces. This is the `--javabase`.\r\n\r\n(1) and (2) now default to the embedded JDK (which is not the local JDK). They should be unaffected by `JAVA_HOME` and the presence of `javac` on the path.\r\n\r\n(3) is the one that depends on `JAVA_HOME` / `javac`. You can set it explicitly using `--javabase`. `--javabase=@embedded_jdk//:jdk` doesn't work because Bazel doesn't support using JDK 9 as a target `--javabase` yet.\r\n\r\nIf you obtain a separate JDK 8, create a `java_runtime` rule and set the `java_runtime.java_home` attribute to the root of that JDK 8, and then set `--javabase` to the label of the `java_runtime` rule, that should guarantee that Bazel's behaviour is unaffected by `JAVA_HOME` etc.\r\n\r\nDoes that match what you're seeing?\r\n\r\n> I would also like a way to use the embedded JDK as the alternative so I have less stuff to version\r\n\r\nThis makes sense, but it isn't really the intended use-case for the embedded JDK. There's some discussion about shipping a minimal JDK that contains only what's need for the host_javabase use-case, which probably isn't what's wanted fro a target `--javabase`. It would be less fragile to explicitly choose the JDK version to target instead of using whatever version Bazel happens to be currently using.",
"@philwo @buchgr FYI\r\n\r\nThere's some discussion happening about making it possible to configure host JDKs using remote repositories or similar, and it would probably be possible to use the same approach for target JDKs. So if you want the ability to version the host and target JDKs and avoid implicitly depending on the local JDK that'd be another way to approach it.\r\n\r\nThis original feature request (of using the embedded JDK as a target JDK) is not something we're likely to pursue for the reason I mentioned above: we want to make the embedded JDK image as a small as possible to reduce the installation size.",
"@cushon\nAre there tickets for these discussions (depending on an external versioned\njdk for host/target)?\nOn Thu, 26 Jul 2018 at 17:30 Liam Miller-Cushon <[email protected]>\nwrote:\n\n> @philwo <https://github.com/philwo> @buchgr <https://github.com/buchgr>\n> FYI\n>\n> There's some discussion happening about making it possible to configure\n> host JDKs using remote repositories or similar, and it would probably be\n> possible to use the same approach for target JDKs. So if you want the\n> ability to version the host and target JDKs and avoid implicitly depending\n> on the local JDK that'd be another way to approach it.\n>\n> This original feature request (of using the embedded JDK as a target JDK)\n> is not something we're likely to pursue for the reason I mentioned above:\n> we want to make the embedded JDK image as a small as possible to reduce the\n> installation size.\n>\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/bazelbuild/bazel/issues/5594#issuecomment-408137102>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/ABUIFxQaUNJTbTzOh8lWcW80q_ySjISJks5uKeCsgaJpZM4VPYjF>\n> .\n>\n",
"@ittaiz https://groups.google.com/d/topic/bazel-sig-jvm/noXlM1HOvVY/discussion",
"Even if I set --javabase and --host_javabase, builds still don't work on a machine where `which javac` finds a broken JDK. Is there some other flag that also needs to be set to completely avoid the system-installed JDK from affecting builds?",
"Specifically, with this WORKSPACE:\r\n```python\r\nnew_http_archive(\r\n name = \"zulu_jdk8\",\r\n build_file = \"zulu_jdk8.BUILD\",\r\n sha256 = \"65a1b180ad46c5a1cc2f9ffff29b85d682c0e937b7b964b557f2a3b9084de5b9\",\r\n strip_prefix = \"zulu8.30.0.1-jdk8.0.172-linux_x64\",\r\n url = \"https://cdn.azul.com/zulu/bin/zulu8.30.0.1-jdk8.0.172-linux_x64.tar.gz\",\r\n)\r\n```\r\nAnd this BUILD:\r\n```python\r\ngenrule(\r\n name = \"gen_main\",\r\n outs = [\"Main.java\"],\r\n cmd = \"echo \\\"class Main { public static void main(String[] args) {} }\\\" > $@\",\r\n)\r\n\r\njava_binary(\r\n name = \"main\",\r\n srcs = [\"Main.java\"],\r\n main_class = \"Main\",\r\n)\r\n```\r\n\r\nThis works (I'm doing this on a machine with a working JDK found via `which javac`):\r\n```console\r\n$ /tmp/bazel-0.15.2-linux-x86_64 build //...\r\nINFO: Build options have changed, discarding analysis cache.\r\nINFO: Analysed 2 targets (16 packages loaded).\r\nINFO: Found 2 targets...\r\nINFO: Elapsed time: 5.201s, Critical Path: 2.85s\r\nINFO: 2 processes: 1 linux-sandbox, 1 worker.\r\nINFO: Build completed successfully, 7 total actions\r\n```\r\nBut this fails:\r\n```console\r\n$ JAVA_HOME=/nonexistent /tmp/bazel-0.15.2-linux-x86_64 build //...\r\nWARNING: Running Bazel server needs to be killed, because the startup options are different.\r\nStarting local Bazel server and connecting to it...\r\n.....................\r\nERROR: /x1/home/brian/.cache/bazel/_bazel_brian/9a14994a41429a580e5cd8b6f1b379ce/external/bazel_tools/tools/jdk/BUILD:181:1: no such package '@local_jdk//': Expected directory at /nonexistent but it does not exist. and referenced by '@bazel_tools//tools/jdk:jdk'\r\nERROR: Analysis of target '//:main' failed; build aborted: Analysis failed\r\nINFO: Elapsed time: 6.264s\r\nINFO: 0 processes.\r\nFAILED: Build did NOT complete successfully (10 packages loaded)\r\n currently loading: @bazel_tools//src/tools/launcher ... (2 packages)\r\n```",
"> Even if I set --javabase and --host_javabase, builds still don't work on a machine where which javac finds a broken JDK.\r\n\r\nAre you setting the `--host_javabase` build flag, or startup flag, or both?",
"I was using the build flag because I didn't realize there was a startup one. What version of JDK is supported for the startup one? If I use a Java 8 one, it breaks because `src/main/cpp/blaze.cc` says `TODO(b/109998449): only assume JDK >= 9 for embedded JDKs`, and then adds a Java 9-only flag for passing to the JVM found via the `--host_javabase` startup flag. If I use a Java 9 one, then compilation via the `java_*` rules breaks because they don't support Java 9 JDKs yet. Neither the `--host_javabase` or `--javabase` build flags seem to make any difference whatsoever because `@local_jdk` fails to load either way.",
"> If I use a Java 9 one, then compilation via the java_* rules breaks because they don't support Java 9 JDKs yet.\r\n\r\nThe default `startup --host_javabase` is the embedded JDK, which is a JDK 10 in Bazel at head. It was JDK 9 until recently, and JDK 9 should still work.\r\n\r\nJDK 9 isn't supported as a target `--javabase` yet.\r\n\r\nIf you use `bazel --host_javabase=<jdk 9> build ...` that should work. If it doesn't, what error are you seeing?",
"Oh, I was testing the wrong bazel binary... `bazel --host_javabase=<jdk 9> build ...` works with 0.6.0, but setting `JAVA_HOME=/dev/null/nonexistent` still breaks it. Same error as before:\r\n```console\r\nERROR: /x1/home/brian/.cache/bazel/_bazel_brian/efaa4e6bb8c9b0585e183b73359e618d/external/bazel_tools/tools/jdk/BUILD:149:1: no such package '@local_jdk//': Expected directory at /dev/null/nonexistent but it does not exist. and referenced by '@bazel_tools//tools/jdk:bootclasspath'\r\n```",
"@buchgr @meisterT FYI. I think this is exactly the bug I found when we discussed ~2 weeks ago, which `--{host_,}javabase` flag influences what part of the build: Namely, the `@local_jdk` repo, which is *not* set to the path given by `--javabase` (which would be the right behavior), but is always taken from the JAVA_HOME environment variable (or calculated from `which javac`) and cannot be influenced at all via flags.\r\n\r\nHere's the current set of flags and what they do:\r\n\r\n- `bazel --host_javabase=... build ...` = Defines what JDK Bazel itself runs under.\r\n- `bazel build --host_javabase=...` = Defines the JDK that Bazel uses to run Java tools that run on your machine as part of the build (e.g. JavaBuilder, SingleJar and friends).\r\n- `bazel build --javabase=...` = Defines what Bazel puts into the launcher script of java_binary and java_test targets as their Java runtime. So, if you run `bazel test --javabase=//my:jdk //:javatest`, then `//my:jdk` would be used to run the test.\r\n- `$JAVA_HOME` = what is made available as `@local_jdk` and used by JavaBuilder as the classpath to build against.\r\n\r\nAFAIU the proposed fix is to merge the last two and make `bazel build --javabase=$JAVA_HOME` the default, so that people who have a JDK installed can just go and build stuff, but when you explicitly set `bazel build --javabase=//my:jdk`, then that would also redirect `@local_jdk` to `//my:jdk` and your system JDK (if it exists) would be completely ignored.\r\n\r\n(@cushon Please correct me if I'm wrong!)\r\n",
"@philwo that all sounds right to me.\r\n\r\nIf I'm following, the goal should be that `@local_jdk` is used only as the default value of `--javabase`, and that all other uses of it (e.g. in `@bazel_tools//tools/jdk:bootclasspath` should be migrated to use `current_java_runtime`). By default the host-config `current_java_runtime` will still be `@local_jdk`, but changing `--javabase` will be sufficient to avoid using `JAVA_HOME` anywhere.",
"That sounds like it would work for my use case. Any ETA on implementing it? I'm currently stuck not being able to roll out a new bazel release with other helpful bugfixes and new features due to this.",
"cc @buchgr \r\n\r\n> That sounds like it would work for my use case. Any ETA on implementing it?\r\n\r\nI'm re-opening this bug to track breaking dependencies on `JAVA_HOME` / `@local_jdk` except as the default value of `--javabase`. I'm hoping that will be ready 'soon', but Bazel team may have other ideas to mitigate this issue.",
"This is fixed at head, and the fix will be included in the upcoming 0.17 release.",
"Almost. https://github.com/bazelbuild/bazel/issues/6341",
"In case someone else gets confused about how to refer to the java toolchain from genrules etc., please have a look here: https://stackoverflow.com/questions/53066974/how-can-i-use-the-jar-tool-with-bazel-v0-19",
"copying jdk tools.jar introduced bugs. refer to, https://github.com/bazelbuild/intellij/issues/2164"
] | [] | "2018-08-14T21:15:42Z" | [
"type: feature request"
] | Only use JAVA_HOME/@local_jdk as the default --javabase | ### Description of the problem / feature request:
Since 849df36c5ad31ebe8791c4228321c38c6d0ae56c, bazel will always pick up a JDK from `which javac` or $JAVA_HOME in preference to an embedded one for `@local_jdk//`. I want to always use the embedded one instead. A startup option to do this would be fine.
### Feature requests: what underlying problem are you trying to solve with this feature?
I version the bazel binary in my repository. I want this to fix the version of the JDK being used too, like it did before.
### What operating system are you running Bazel on?
Debian Jessie amd64
### What's the output of `bazel info release`?
release 0.15.0-peloton-201807111305+9c52124
This is 0.15.0 with a few local patches that aren't relevant.
### Have you found anything relevant by searching the web?
@cushon changed this. | [
"tools/jdk/BUILD",
"tools/jdk/DumpPlatformClassPath.java"
] | [
"tools/jdk/BUILD",
"tools/jdk/DumpPlatformClassPath.java"
] | [] | diff --git a/tools/jdk/BUILD b/tools/jdk/BUILD
index 8598fdfa9a72ed..ff52e25b1f49c6 100644
--- a/tools/jdk/BUILD
+++ b/tools/jdk/BUILD
@@ -176,8 +176,12 @@ genrule(
cmd = """
set -eu
TMPDIR=$$(mktemp -d -t tmp.XXXXXXXX)
-$(JAVABASE)/bin/javac $< -d $$TMPDIR
-$(JAVA) -cp $$TMPDIR DumpPlatformClassPath $@
+$(JAVABASE)/bin/javac -source 8 -target 8 \
+ -cp $(JAVABASE)/lib/tools.jar \
+ -d $$TMPDIR $<
+$(JAVA) -XX:+IgnoreUnrecognizedVMOptions \
+ --add-exports=jdk.compiler/com.sun.tools.javac.platform=ALL-UNNAMED \
+ -cp $$TMPDIR DumpPlatformClassPath $@
rm -rf $$TMPDIR
""",
toolchains = ["@bazel_tools//tools/jdk:current_host_java_runtime"],
diff --git a/tools/jdk/DumpPlatformClassPath.java b/tools/jdk/DumpPlatformClassPath.java
index 1e97fb052dab76..c81ab5d50ca51a 100644
--- a/tools/jdk/DumpPlatformClassPath.java
+++ b/tools/jdk/DumpPlatformClassPath.java
@@ -12,11 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+import static java.util.Comparator.comparing;
+
+import com.sun.tools.javac.api.JavacTool;
+import com.sun.tools.javac.util.Context;
import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
+import java.io.UncheckedIOException;
import java.net.URI;
-import java.nio.file.DirectoryStream;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
@@ -24,11 +30,20 @@
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Arrays;
+import java.util.EnumSet;
import java.util.GregorianCalendar;
+import java.util.HashMap;
+import java.util.Map;
import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
+import javax.tools.JavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.JavaFileObject.Kind;
+import javax.tools.StandardLocation;
/**
* Output a jar file containing all classes on the platform classpath of the current JDK.
@@ -37,42 +52,93 @@
*/
public class DumpPlatformClassPath {
- public static void main(String[] args) throws IOException {
+ public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("usage: DumpPlatformClassPath <output jar>");
System.exit(1);
}
Path output = Paths.get(args[0]);
- Path path = Paths.get(System.getProperty("java.home"));
- if (path.endsWith("jre")) {
- path = path.getParent();
+
+ Map<String, byte[]> entries = new HashMap<>();
+
+ // JDK 8 bootclasspath handling
+ Path javaHome = Paths.get(System.getProperty("java.home"));
+ if (javaHome.endsWith("jre")) {
+ javaHome = javaHome.getParent();
}
- Path rtJar = path.resolve("jre/lib/rt.jar");
- if (Files.exists(rtJar)) {
- Files.copy(rtJar, output);
- return;
+ for (String jar :
+ Arrays.asList("rt.jar", "resources.jar", "jsse.jar", "jce.jar", "charsets.jar")) {
+ Path path = javaHome.resolve("jre/lib").resolve(jar);
+ if (!Files.exists(path)) {
+ continue;
+ }
+ try (JarFile jf = new JarFile(path.toFile())) {
+ jf.stream()
+ .forEachOrdered(
+ entry -> {
+ try {
+ entries.put(entry.getName(), toByteArray(jf.getInputStream(entry)));
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ });
+ }
}
- Path modules = FileSystems.getFileSystem(URI.create("jrt:/")).getPath("modules");
+
+ if (entries.isEmpty()) {
+ // JDK > 8 bootclasspath handling
+
+ // Set up a compilation with --release 8 to initialize a filemanager
+ Context context = new Context();
+ JavacTool.create()
+ .getTask(null, null, null, Arrays.asList("--release", "8"), null, null, context);
+ JavaFileManager fileManager = context.get(JavaFileManager.class);
+
+ for (JavaFileObject fileObject :
+ fileManager.list(
+ StandardLocation.PLATFORM_CLASS_PATH,
+ "",
+ EnumSet.of(Kind.CLASS),
+ /* recurse= */ true)) {
+ String binaryName =
+ fileManager.inferBinaryName(StandardLocation.PLATFORM_CLASS_PATH, fileObject);
+ entries.put(
+ binaryName.replace('.', '/') + ".class", toByteArray(fileObject.openInputStream()));
+ }
+
+ // Include the jdk.unsupported module for compatibility with JDK 8.
+ // (see: https://bugs.openjdk.java.net/browse/JDK-8206937)
+ // `--release 8` only provides access to supported APIs, which excludes e.g. sun.misc.Unsafe.
+ Path module =
+ FileSystems.getFileSystem(URI.create("jrt:/")).getPath("modules/jdk.unsupported");
+ Files.walkFileTree(
+ module,
+ new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
+ throws IOException {
+ String name = path.getFileName().toString();
+ if (name.endsWith(".class") && !name.equals("module-info.class")) {
+ entries.put(module.relativize(path).toString(), Files.readAllBytes(path));
+ }
+ return super.visitFile(path, attrs);
+ }
+ });
+ }
+
try (OutputStream os = Files.newOutputStream(output);
BufferedOutputStream bos = new BufferedOutputStream(os, 65536);
JarOutputStream jos = new JarOutputStream(bos)) {
- try (DirectoryStream<Path> modulePaths = Files.newDirectoryStream(modules)) {
- for (Path modulePath : modulePaths) {
- Files.walkFileTree(
- modulePath,
- new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult visitFile(Path path, BasicFileAttributes attrs)
- throws IOException {
- String name = path.getFileName().toString();
- if (name.endsWith(".class") && !name.equals("module-info.class")) {
- addEntry(jos, modulePath.relativize(path).toString(), Files.readAllBytes(path));
- }
- return super.visitFile(path, attrs);
+ entries.entrySet().stream()
+ .sorted(comparing(Map.Entry::getKey))
+ .forEachOrdered(
+ entry -> {
+ try {
+ addEntry(jos, entry.getKey(), entry.getValue());
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
}
});
- }
- }
}
}
@@ -91,4 +157,17 @@ private static void addEntry(JarOutputStream jos, String name, byte[] bytes) thr
jos.putNextEntry(je);
jos.write(bytes);
}
+
+ private static byte[] toByteArray(InputStream is) throws IOException {
+ byte[] buffer = new byte[8192];
+ ByteArrayOutputStream boas = new ByteArrayOutputStream();
+ while (true) {
+ int r = is.read(buffer);
+ if (r == -1) {
+ break;
+ }
+ boas.write(buffer, 0, r);
+ }
+ return boas.toByteArray();
+ }
}
| null | train | train | 2018-08-15T02:55:14 | "2018-07-13T19:15:47Z" | brian-peloton | test |
bazelbuild/bazel/5634_6360 | bazelbuild/bazel | bazelbuild/bazel/5634 | bazelbuild/bazel/6360 | [
"timestamp(timedelta=1.0, similarity=0.8469261201945434)"
] | aab8beefb70862c225bfd21732bb2d6e7f09a9a9 | ce2f86e2d33f5e654407ba3777b66c1a4c18b0b9 | [
"Thanks for the report. I don't plan to work on this until https://github.com/bazelbuild/bazel/issues/5187 is done. And I can see an universe in which we won't need so many env vars to tweak C++ toolchain. But nothing concrete yet. If this is urgent, let me know, and I will help the PR.",
"+1 to fixing this. This blocks using non-standard toolchains with bazel.\r\nE.g. in our experiments with downloading a toolchain on-the-fly in Tensorflow, we can't currently use the LLD linker from the downloaded package, because -B flag is added by bazel and can't be overriden (so we end up picking LLD in /usr/bin/ if it's installed).\r\n\r\nMy intuition is that there should be a fix for https://github.com/bazelbuild/bazel/issues/760 that does not involve setting -B."
] | [] | "2018-10-11T18:33:37Z" | [
"type: feature request",
"P2",
"team-Rules-CPP"
] | Stop unconditionally adding -B/usr/bin flag to C/C++ toolchains | The addition of this flag was done as a fix to Issue #760
The problem with this is that it completely breaks any custom toolchain setup because it forces use of tools such as `ld`, `as`, `ar` and others from /usr/bin. And since this is added so early in the process it is not possible override it in the build files.
I see that the original problem in #760 was that `process-wrapper` and `build-runfiles` could not run because they failed to find libstdc++ which has a better solution to just link them statically as described in #4137
At the end of #760 there are other comments mentioning that hard coding -B/usr/bin is wrong. | [
"tools/cpp/CROSSTOOL",
"tools/cpp/unix_cc_configure.bzl"
] | [
"tools/cpp/CROSSTOOL",
"tools/cpp/unix_cc_configure.bzl"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/mock/MOCK_CROSSTOOL",
"src/test/shell/bazel/testdata/bazel_toolchain_test_data/tools/arm_compiler/CROSSTOOL"
] | diff --git a/tools/cpp/CROSSTOOL b/tools/cpp/CROSSTOOL
index a41b8822a964a4..5b9cd3d5356167 100644
--- a/tools/cpp/CROSSTOOL
+++ b/tools/cpp/CROSSTOOL
@@ -59,7 +59,6 @@ toolchain {
tool_path { name: "gcc" path: "/usr/bin/gcc" }
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
@@ -271,7 +270,6 @@ toolchain {
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
diff --git a/tools/cpp/unix_cc_configure.bzl b/tools/cpp/unix_cc_configure.bzl
index 361931b47b88b1..0279b1939f76b8 100644
--- a/tools/cpp/unix_cc_configure.bzl
+++ b/tools/cpp/unix_cc_configure.bzl
@@ -282,8 +282,6 @@ def _crosstool_content(repository_ctx, cc, cpu_value, darwin):
"dynamic_lookup",
"-headerpad_max_install_names",
] if darwin else bin_search_flag + [
- # Always have -B/usr/bin, see https://github.com/bazelbuild/bazel/issues/760.
- "-B/usr/bin",
# Gold linker only? Can we enable this by default?
# "-Wl,--warn-execstack",
# "-Wl,--detect-odr-violations"
@@ -318,10 +316,7 @@ def _crosstool_content(repository_ctx, cc, cpu_value, darwin):
] + ((
_add_compiler_option_if_supported(repository_ctx, cc, "-Wthread-safety") +
_add_compiler_option_if_supported(repository_ctx, cc, "-Wself-assign")
- ) if darwin else bin_search_flag + [
- # Always have -B/usr/bin, see https://github.com/bazelbuild/bazel/issues/760.
- "-B/usr/bin",
- ]) + (
+ )) + (
# Disable problematic warnings.
_add_compiler_option_if_supported(repository_ctx, cc, "-Wunused-but-set-parameter") +
# has false positives
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/mock/MOCK_CROSSTOOL b/src/test/java/com/google/devtools/build/lib/analysis/mock/MOCK_CROSSTOOL
index 0ef230997778ed..3392cf5f3d153a 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/mock/MOCK_CROSSTOOL
+++ b/src/test/java/com/google/devtools/build/lib/analysis/mock/MOCK_CROSSTOOL
@@ -62,7 +62,6 @@ toolchain {
tool_path { name: "gcc" path: "/usr/bin/gcc" }
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
diff --git a/src/test/shell/bazel/testdata/bazel_toolchain_test_data/tools/arm_compiler/CROSSTOOL b/src/test/shell/bazel/testdata/bazel_toolchain_test_data/tools/arm_compiler/CROSSTOOL
index d9e45a4e01d109..55148f0daa1df5 100644
--- a/src/test/shell/bazel/testdata/bazel_toolchain_test_data/tools/arm_compiler/CROSSTOOL
+++ b/src/test/shell/bazel/testdata/bazel_toolchain_test_data/tools/arm_compiler/CROSSTOOL
@@ -155,8 +155,6 @@ toolchain {
compiler_flag: "-fstack-protector"
compiler_flag: "-Wall"
compiler_flag: "-Wl,-z,-relro,-z,now"
- compiler_flag: "-B/usr/bin"
- compiler_flag: "-B/usr/bin"
compiler_flag: "-Wunused-but-set-parameter"
compiler_flag: "-Wno-free-nonheap-object"
compiler_flag: "-fno-omit-frame-pointer"
@@ -173,8 +171,6 @@ toolchain {
linker_flag: "-lstdc++"
linker_flag: "-lm"
linker_flag: "-Wl,-no-as-needed"
- linker_flag: "-B/usr/bin"
- linker_flag: "-B/usr/bin"
linker_flag: "-pass-exit-codes"
needsPic: true
objcopy_embed_flag: "-I"
| train | train | 2018-10-11T21:08:25 | "2018-07-19T08:03:25Z" | georgi-d | test |
bazelbuild/bazel/5720_5739 | bazelbuild/bazel | bazelbuild/bazel/5720 | bazelbuild/bazel/5739 | [
"timestamp(timedelta=1.0, similarity=0.9344559452588765)"
] | 78142a6bf3dbf802e3140c1098cf3fda8d4be883 | 99a58d0de6283cb79ba4f53ac665c342f46449a7 | [
"Thanks for reporting it!"
] | [
"This link downloads a \"visualcppbuildtools_full.exe\" which seems pretty confusing to say the least. Maybe we should link the page where all the Visual C++ Build Tools are?",
"I agree. Microsoft is notorious for orphaning download links.",
"Done."
] | "2018-08-02T07:15:34Z" | [
"type: documentation (cleanup)",
"platform: windows",
"bazel.build"
] | Docs link to Visual C++ Build Tools 2015 is broken | ### Description of the problem / feature request:
Link to `Visual C++ Build Tools 2015` in https://docs.bazel.build/versions/master/windows.html lead to a 404
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Open https://docs.bazel.build/versions/master/windows.html, click on `Visual C++ Build Tools 2015 or later`.
### What operating system are you running Bazel on?
N/A.
### What's the output of `bazel info release`?
N/A.
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
N/A.
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
N/A.
### Have you found anything relevant by searching the web?
Actually found it super hard to find the mentioned Visual C++ Build Tools 2015 at all. Googling it doesn't seem to give a direct download page.
I found a link that works in [this](https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/) python page: http://go.microsoft.com/fwlink/?LinkId=691126
### Any other information, logs, or outputs that you want to share?
N/A.
| [
"site/docs/windows.md"
] | [
"site/docs/windows.md"
] | [] | diff --git a/site/docs/windows.md b/site/docs/windows.md
index 9049fbbdd63cdc..3f454b693c6798 100644
--- a/site/docs/windows.md
+++ b/site/docs/windows.md
@@ -58,7 +58,7 @@ To build C++ targets, you need:
features are not installed by default.
* Install the [Visual C++ Build
- Tools 2015 or later](http://landinghub.visualstudio.com/visual-cpp-build-tools).
+ Tools 2015 or later](https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2017).
If [alwayslink](be/c-cpp.html#cc_library.alwayslink) doesn't work with
VS 2017, that is due to a
| null | train | train | 2018-08-02T04:26:50 | "2018-07-31T16:06:58Z" | filipesilva | test |
bazelbuild/bazel/5751_5752 | bazelbuild/bazel | bazelbuild/bazel/5751 | bazelbuild/bazel/5752 | [
"timestamp(timedelta=0.0, similarity=0.9462255836554451)"
] | ed75f38d5857177bd7730b60c9fd3eb66dea5300 | 10187c568655e63d56713c58bf89fccb661ef16d | [] | [] | "2018-08-03T10:12:18Z" | [
"type: bug",
"P1",
"platform: windows"
] | Windows,Bash detection: do not detect Git Bash | ### Description of the problem / feature request:
When `BAZEL_SH` envvar is not defined and Bazel searches for a suitable bash.exe, it should not look for Git Bash nor should it recommend installing it as a Bash implementation.
Git Bash does not support the full set of bintools that MSYS2 Bash does, nor does Git Bash support Pacman to install those tools. Git Bash is therefore unsuitable as a general-purpose Bash for Windows.
Even worse, if you have both Git Bash and MSYS Bash installed, they may collide if you run one's binaries from the other (see repro below).
Bazel should only look for MSYS2 Bash and recommend only that.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. Have both Git Bash and MSYS2 Bash installed, have paths to them that have no space characters:
```
C:\src\tmp>mklink /j C:\git "C:\Program Files\Git"
Junction created for C:\git <<===>> C:\Program Files\Git
```
2. In MSYS2 Bash install "zip" by running `pacman -Syu zip`.
3. Set "BAZEL_SH" envvar to point to Git Bash, put Git then MSYS on the PATH:
```
BAZEL_SH=C:\git\usr\bin\bash.exe
PATH=C:\git\usr\bin;C:\msys64\usr\bin
```
4. Build a genrule that runs `zip`.
```
C:\src\tmp>type BUILD
genrule(
name = "foo",
outs = ["foo.txt"],
cmd = ("echo \"DEBUG: $$(cygpath -w $$(which bash))\" ; " +
"echo \"DEBUG: $$(cygpath -w $$(which zip))\" ; " +
"zip > $@")
)
C:\src\tmp>c:\src\bazel-releases\0.16.0\bazel.exe build --verbose_failures //:foo.txt
INFO: Analysed target //:foo.txt (0 packages loaded).
INFO: Found 1 target...
SUBCOMMAND: # //:foo [action 'Executing genrule //:foo']
cd C:/users/laszlocsomor/_bazel_laszlocsomor/zovul4l7/execroot/__main__
SET PATH=C:\git\usr\bin;C:\git\bin;C:\git\usr\bin;C:\msys64\usr\bin
C:/git/usr/bin/bash.exe -c source external/bazel_tools/tools/genrule/genrule-setup.sh; echo "DEBUG: $(cygpath -w $(which bash))" ; echo "DEBUG: $(cygpath -w $(which zip))" ; zip > bazel-out/x64_windows-fastbuild/genfiles/foo.txt
ERROR: C:/src/tmp/BUILD:107:1: Executing genrule //:foo failed (Exit 127): bash.exe failed: error executing command
cd C:/users/laszlocsomor/_bazel_laszlocsomor/zovul4l7/execroot/__main__
SET PATH=C:\git\usr\bin;C:\git\bin;C:\git\usr\bin;C:\msys64\usr\bin
C:/git/usr/bin/bash.exe -c source external/bazel_tools/tools/genrule/genrule-setup.sh; echo "DEBUG: $(cygpath -w $(which bash))" ; echo "DEBUG: $(cygpath -w $(which zip))" ; zip > bazel-out/x64_windows-fastbuild/genfiles/foo.txt
DEBUG: C:\git\usr\bin\bash.exe
DEBUG: C:\msys64\usr\bin\zip.exe
1 [main] zip (6740) C:\msys64\usr\bin\zip.exe: *** fatal error - cygheap base mismatch detected - 0x180318410/0x1802FF410.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version. The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution. Rebooting is also suggested if you
are unable to find another cygwin DLL.
Target //:foo.txt failed to build
INFO: Elapsed time: 1.160s, Critical Path: 0.70s
INFO: 0 processes.
FAILED: Build did NOT complete successfully
```
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
```
C:\src\tmp>c:\src\bazel-releases\0.16.0\bazel.exe info release
release 0.16.0
``` | [
"src/main/cpp/blaze_util_windows.cc"
] | [
"src/main/cpp/blaze_util_windows.cc"
] | [] | diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc
index e851ef041a5378..d811a944548df1 100644
--- a/src/main/cpp/blaze_util_windows.cc
+++ b/src/main/cpp/blaze_util_windows.cc
@@ -1413,58 +1413,6 @@ static string GetMsysBash() {
return string();
}
-// Implements heuristics to discover Git-on-Win installation.
-static string GetBashFromGitOnWin() {
- HKEY h_GitOnWin_uninstall;
-
- // Well-known registry key for Git-on-Windows.
- static constexpr const char key[] =
- "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1";
- if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, // _In_ HKEY hKey,
- key, // _In_opt_ LPCTSTR lpSubKey,
- 0, // _In_ DWORD ulOptions,
- KEY_QUERY_VALUE, // _In_ REGSAM samDesired,
- &h_GitOnWin_uninstall // _Out_ PHKEY phkResult
- )) {
- BAZEL_LOG(INFO) << "Cannot open HKCU\\" << key;
- return string();
- }
- AutoHandle auto_h_GitOnWin_uninstall(h_GitOnWin_uninstall);
-
- BAZEL_LOG(INFO) << "Getting install location of HKLM\\" << key;
- BYTE path[REG_VALUE_BUFFER_SIZE];
- DWORD path_length = sizeof(path);
- DWORD path_type;
- if (RegQueryValueEx(h_GitOnWin_uninstall, // _In_ HKEY hKey,
- "InstallLocation", // _In_opt_ LPCTSTR lpValueName,
- 0, // _Reserved_ LPDWORD lpReserved,
- &path_type, // _Out_opt_ LPDWORD lpType,
- path, // _Out_opt_ LPBYTE lpData,
- &path_length // _Inout_opt_ LPDWORD lpcbData
- )) {
- BAZEL_LOG(ERROR) << "Failed to query InstallLocation of HKLM\\" << key;
- return string();
- }
-
- if (path_length == 0 || path_type != REG_SZ) {
- BAZEL_LOG(ERROR) << "Zero-length (" << path_length
- << ") install location or wrong type (" << path_type
- << ")";
- return string();
- }
-
- BAZEL_LOG(INFO) << "Install location of HKLM\\" << key << " is " << path;
- string path_as_string(path, path + path_length - 1);
- string bash_exe = path_as_string + "\\usr\\bin\\bash.exe";
- if (!blaze_util::PathExists(bash_exe)) {
- BAZEL_LOG(ERROR) << "%s does not exist", bash_exe.c_str();
- return string();
- }
-
- BAZEL_LOG(INFO) << "Detected git-on-Windows bash at " << bash_exe.c_str();
- return bash_exe;
-}
-
static string GetBinaryFromPath(const string& binary_name) {
char found[MAX_PATH];
string path_list = blaze::GetEnv("PATH");
@@ -1508,11 +1456,6 @@ static string LocateBash() {
return msys_bash;
}
- string git_on_win_bash = GetBashFromGitOnWin();
- if (!git_on_win_bash.empty()) {
- return git_on_win_bash;
- }
-
return GetBinaryFromPath("bash.exe");
}
@@ -1533,17 +1476,13 @@ void DetectBashOrDie() {
// TODO(bazel-team) should this be printed to stderr? If so, it should use
// BAZEL_LOG(ERROR)
printf(
- "Bazel on Windows requires bash.exe and other Unix tools, but we could "
- "not find them.\n"
- "If you do not have them installed, the easiest is to install MSYS2 "
- "from\n"
+ "Bazel on Windows requires MSYS2 Bash, but we could not find it.\n"
+ "If you do not have it installed, you can install MSYS2 from\n"
" http://repo.msys2.org/distrib/msys2-x86_64-latest.exe\n"
- "or git-on-Windows from\n"
- " https://git-scm.com/download/win\n"
"\n"
- "If you already have bash.exe installed but Bazel cannot find it,\n"
+ "If you already have it installed but Bazel cannot find it,\n"
"set BAZEL_SH environment variable to its location:\n"
- " set BAZEL_SH=c:\\path\\to\\bash.exe\n");
+ " set BAZEL_SH=c:\\path\\to\\msys2\\usr\\bin\\bash.exe\n");
exit(1);
}
}
| null | train | train | 2018-08-03T11:53:31 | "2018-08-03T10:07:59Z" | laszlocsomor | test |
bazelbuild/bazel/5803_5804 | bazelbuild/bazel | bazelbuild/bazel/5803 | bazelbuild/bazel/5804 | [
"timestamp(timedelta=96914.0, similarity=0.9177194223528519)"
] | f05c0a48dc298ad3e90f3acb399cc53c2944a801 | adbdea18f70b4d1aebdf574d9b6b782c68322251 | [
"Workaround for the time being (because of https://github.com/bazelbuild/bazel/issues/5802):\r\n- add a new `java_library` to `src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD.tools` called \"runfiles-deprecated\" with a `deprecation` attribute\r\n- change the `alias` rule in `tools/runfiles/BUILD.tools` to point to \"runfiles-deprecated\"\r\n- add a new `java_library` to `tools/java/runfiles/BUILD.tools` that uses the sources from `//src/tools/runfiles/java/com/google/devtools/build/runfiles:java-srcs`.",
"This [workaround](https://github.com/bazelbuild/bazel/issues/5803#issuecomment-411388225) is not good enough: it warns against the alias rule, not against the rule that depends on the alias, i.e. Bazel will warn against `@bazel_tools//tools/runfiles:java-runfiles`, not against the rule that depends on `@bazel_tools//tools/runfiles:java-runfiles` (as we would like to)."
] | [
"Clever!"
] | "2018-08-08T13:07:30Z" | [
"type: process"
] | move the Java runfiles library to `@bazel_tools//tools/java/runfiles` | ### Description of the problem / feature request:
Every language's runfiles library is under `@bazel_tools//tools/<language>/runfiles`, Java being the only exception with `@bazel_tools//tools/runfiles:java-runfiles`.
### Feature requests: what underlying problem are you trying to solve with this feature?
Consistency with other languages.
### What's the output of `bazel info release`?
```
$ bazel info release
release 0.16.0
```
### Any other information, logs, or outputs that you want to share?
https://github.com/bazelbuild/bazel/issues/5802 is not a blocker, but an annoyance, because we can't just add a `deprecation` attribute to `@bazel_tools//tools/runfiles:java-runfiles` telling users which target to use instead. | [
"src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD",
"src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD.tools",
"src/tools/runfiles/java/com/google/devtools/build/runfiles/Runfiles.java",
"tools/BUILD",
"tools/runfiles/BUILD.tools"
] | [
"src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD",
"src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD.tools",
"src/tools/runfiles/java/com/google/devtools/build/runfiles/Runfiles.java",
"tools/BUILD",
"tools/java/BUILD",
"tools/java/runfiles/BUILD",
"tools/java/runfiles/BUILD.tools",
"tools/runfiles/BUILD.tools"
] | [
"src/test/py/bazel/testdata/runfiles_test/bar/BUILD.mock",
"src/test/py/bazel/testdata/runfiles_test/foo/BUILD.mock"
] | diff --git a/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD b/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD
index 00f44a07d688e7..c988e826580808 100644
--- a/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD
+++ b/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD
@@ -29,7 +29,6 @@ filegroup(
java_library(
name = "runfiles",
srcs = [":java-srcs"],
- visibility = ["//src/tools/runfiles:__pkg__"],
)
java_test(
diff --git a/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD.tools b/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD.tools
index 5337b2b0d58fad..2f90f252ad242b 100644
--- a/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD.tools
+++ b/src/tools/runfiles/java/com/google/devtools/build/runfiles/BUILD.tools
@@ -1,5 +1,6 @@
package(default_visibility = ["//visibility:private"])
+# TODO(laszlocsomor): move the sources to //tools/java/runfiles
filegroup(
name = "java-srcs",
srcs = [
@@ -8,8 +9,15 @@ filegroup(
],
)
+# TODO(laszlocsomor): after https://github.com/bazelbuild/bazel/issues/5802 is fixed, add a
+# `deprecation` attribute to @bazel_tools//tools/runfiles:java-runfiles, advising users to depend on
+# @bazel_tools//tools/java/runfiles instead. After a reasonable time (1-2 Bazel releases containing
+# the deprecation warning) remove @bazel_tools//tools/runfiles:java-runfiles.
java_library(
name = "runfiles",
srcs = [":java-srcs"],
- visibility = ["//tools/runfiles:__pkg__"],
+ visibility = [
+ "//tools/runfiles:__pkg__",
+ "//tools/java/runfiles:__pkg__",
+ ],
)
diff --git a/src/tools/runfiles/java/com/google/devtools/build/runfiles/Runfiles.java b/src/tools/runfiles/java/com/google/devtools/build/runfiles/Runfiles.java
index 3c9eef3a6bb4fe..718b67948d8d7c 100644
--- a/src/tools/runfiles/java/com/google/devtools/build/runfiles/Runfiles.java
+++ b/src/tools/runfiles/java/com/google/devtools/build/runfiles/Runfiles.java
@@ -35,7 +35,7 @@
* java_binary(
* name = "my_binary",
* ...
- * deps = ["@bazel_tools//tools/runfiles:java-runfiles"],
+ * deps = ["@bazel_tools//tools/java/runfiles"],
* )
* </pre>
*
diff --git a/tools/BUILD b/tools/BUILD
index 619257122f86d4..14aa2925e7f96b 100644
--- a/tools/BUILD
+++ b/tools/BUILD
@@ -19,6 +19,7 @@ filegroup(
"//tools/build_defs/repo:srcs",
"//tools/build_rules:srcs",
"//tools/coverage:srcs",
+ "//tools/java:srcs",
"//tools/jdk:srcs",
"//tools/launcher:srcs",
"//tools/def_parser:srcs",
@@ -57,6 +58,7 @@ filegroup(
"//tools/cpp:srcs",
"//tools/cpp/runfiles:embedded_tools",
"//tools/genrule:srcs",
+ "//tools/java:embedded_tools",
"//tools/j2objc:srcs",
"//tools/jdk:package-srcs",
"//tools/jdk:srcs",
diff --git a/tools/java/BUILD b/tools/java/BUILD
new file mode 100644
index 00000000000000..36b5f634475ab4
--- /dev/null
+++ b/tools/java/BUILD
@@ -0,0 +1,17 @@
+package(default_visibility = ["//visibility:private"])
+
+filegroup(
+ name = "srcs",
+ srcs = [
+ "BUILD",
+ "//tools/java/runfiles:srcs",
+ ],
+ visibility = ["//tools:__pkg__"],
+)
+
+filegroup(
+ name = "embedded_tools",
+ srcs = ["//tools/java/runfiles:embedded_tools"],
+ visibility = ["//tools:__pkg__"],
+)
+
diff --git a/tools/java/runfiles/BUILD b/tools/java/runfiles/BUILD
new file mode 100644
index 00000000000000..a0d2c018af6ec0
--- /dev/null
+++ b/tools/java/runfiles/BUILD
@@ -0,0 +1,16 @@
+package(default_visibility = ["//visibility:private"])
+
+filegroup(
+ name = "srcs",
+ srcs = [
+ "BUILD",
+ "BUILD.tools",
+ ],
+ visibility = ["//tools/java:__pkg__"],
+)
+
+filegroup(
+ name = "embedded_tools",
+ srcs = ["BUILD.tools"],
+ visibility = ["//tools/java:__pkg__"],
+)
diff --git a/tools/java/runfiles/BUILD.tools b/tools/java/runfiles/BUILD.tools
new file mode 100644
index 00000000000000..011a549ba3381e
--- /dev/null
+++ b/tools/java/runfiles/BUILD.tools
@@ -0,0 +1,6 @@
+alias(
+ name = "runfiles",
+ # TODO(laszlocsomor): move the sources to this package.
+ actual = "//src/tools/runfiles/java/com/google/devtools/build/runfiles",
+ visibility = ["//visibility:public"],
+)
diff --git a/tools/runfiles/BUILD.tools b/tools/runfiles/BUILD.tools
index d92852377bd766..6f107ea3e76174 100644
--- a/tools/runfiles/BUILD.tools
+++ b/tools/runfiles/BUILD.tools
@@ -1,6 +1,7 @@
package(default_visibility = ["//visibility:public"])
-alias(
+java_library(
name = "java-runfiles",
- actual = "//src/tools/runfiles/java/com/google/devtools/build/runfiles",
+ exports = ["//src/tools/runfiles/java/com/google/devtools/build/runfiles"],
+ deprecation = "Depend on @bazel_tools//tools/java/runfiles instead. This target goes away in Bazel release 0.18.0",
)
| diff --git a/src/test/py/bazel/testdata/runfiles_test/bar/BUILD.mock b/src/test/py/bazel/testdata/runfiles_test/bar/BUILD.mock
index 930884b45a9ef9..de3a5cf9d086bf 100644
--- a/src/test/py/bazel/testdata/runfiles_test/bar/BUILD.mock
+++ b/src/test/py/bazel/testdata/runfiles_test/bar/BUILD.mock
@@ -13,7 +13,7 @@ java_binary(
srcs = ["Bar.java"],
data = ["bar-java-data.txt"],
main_class = "Bar",
- deps = ["@bazel_tools//tools/runfiles:java-runfiles"],
+ deps = ["@bazel_tools//tools/java/runfiles"],
)
sh_binary(
diff --git a/src/test/py/bazel/testdata/runfiles_test/foo/BUILD.mock b/src/test/py/bazel/testdata/runfiles_test/foo/BUILD.mock
index 42c7d842412ec5..533a7d7243daa4 100644
--- a/src/test/py/bazel/testdata/runfiles_test/foo/BUILD.mock
+++ b/src/test/py/bazel/testdata/runfiles_test/foo/BUILD.mock
@@ -23,7 +23,7 @@ java_binary(
"//bar:bar-cc",
],
main_class = "Foo",
- deps = ["@bazel_tools//tools/runfiles:java-runfiles"],
+ deps = ["@bazel_tools//tools/java/runfiles"],
)
sh_binary(
| train | train | 2018-08-08T14:30:57 | "2018-08-08T12:28:01Z" | laszlocsomor | test |
bazelbuild/bazel/5807_6014 | bazelbuild/bazel | bazelbuild/bazel/5807 | bazelbuild/bazel/6014 | [
"timestamp(timedelta=101070.0, similarity=0.878287860173537)"
] | 3987300d6651cf0e6e91b395696afac6913a7d66 | de4edef403090fcba0638772097c967d11d80b35 | [
"@filipesilva I have made some progress on this recently.\r\nNow with Bazel built from HEAD, symlink tree will be available on Windows when you pass `--experimental_enable_runfiles`. \r\nCan you try if it helps with https://github.com/bazelbuild/bazel/issues/5926?",
"@filipesilva Just found a bug when dealing with long path, sending a fix now."
] | [
"`FILE_FLAG_BACKUP_SEMANTICS` is required when and only when opening a directory or junction. When opening a file symlink, you must not use `FILE_FLAG_BACKUP_SEMANTICS`. I suggest trying to open it with `FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT` in case this `CreateFileW` call fails.\r\n\r\nFurthermore, in order to minimize risk of filesystem races I suggest attempting to open the file without trying to call `GetFileAttributesW`. The benefit: if the path does not exist, `CreateFileW` fails and `GetLastError()` will return a corresponding error code, but if the path does exist, we have an open handle to it and no other process can delete or modify the file until we release this handle. (The OS will delay actual deletion until all handles are closed.)\r\n\r\nAnd in case you do need the attributes after opening the file, you can use `GetFileInformationByHandle`.",
"Good suggestions! Thanks!",
"In my experience, CreateFileW(..., FILE_ATTRIBUTE_NORMAL | ...) fails for directories (and junctions, which are also directories), therefore this failure may just mean that \"path\" refers to a directory.",
"Then I think we can call `GetFileAttributesW` first to check if the `path` refers to a reparse point or not. If it does, we can just use `FILE_FLAG_OPEN_REPARSE_POINT`, otherwise, we skip and return the original path. WDYT?",
"And we can tell from the attribute if the `path` is a directory or not, if it is, we set `FILE_FLAG_BACKUP_SEMANTICS`",
"Yes, I think calling GetFileAttributeW then CreateFileW (with FILE_ATTRIBUTE_NORMAL or FILE_FLAG_BACKUP_SEMANTICS, depending on the attributes) is as good as calling CreateFileW first with FILE_FLAG_BACKUP_SEMANTICS then with FILE_ATTRIBUTE_NORMAL -- both approaches achieve the same goal and both are susceptible to file system races (i.e. when the file is modified between the two function calls).",
"OK, it's done. But I think we don't need `FILE_ATTRIBUTE_NORMAL` for file symlink because in the document it says `This attribute is valid only if used alone.`\r\nhttps://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea"
] | "2018-08-28T14:12:31Z" | [
"type: feature request",
"P2",
"platform: windows",
"area-Windows",
"team-OSS"
] | Use symlinked runfiles on Windows when supported | ### Description of the problem / feature request:
On Windows Bazel sets `RUNFILES_MANIFEST_ONLY` to `1` and does not generate symlinks to runfiles. This does not change if the current user can create symlinks.
On recent Windows 10 versions it is possible to enable symlinks for all users:
> Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.
More details can be found in https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10/
The feature I am requesting is to generate symlink to runfiles on Windows when supported by the current user.
### Feature requests: what underlying problem are you trying to solve with this feature?
Creating rules with windows support is not trivial (https://github.com/bazelbuild/bazel/issues/3726#issuecomment-329504506).
Using symlinks on windows when available should make many existing rules work on Windows without having to resolve runfiles via the manifest, given the user has symlink support.
On systems Windows without symlink support enabled, looking up the runfiles would still be necessary.
Related to https://github.com/bazelbuild/bazel/issues/3726, https://github.com/bazelbuild/bazel/issues/3889, https://github.com/bazelbuild/bazel/issues/1212
/cc @alexeagle | [
"src/main/cpp/util/file_platform.h",
"src/main/cpp/util/file_windows.cc"
] | [
"src/main/cpp/util/file_platform.h",
"src/main/cpp/util/file_windows.cc"
] | [] | diff --git a/src/main/cpp/util/file_platform.h b/src/main/cpp/util/file_platform.h
index 76e94d175732ed..868d3c90f21d82 100644
--- a/src/main/cpp/util/file_platform.h
+++ b/src/main/cpp/util/file_platform.h
@@ -209,6 +209,16 @@ void ForEachDirectoryEntry(const std::string &path,
std::wstring GetCwdW();
bool MakeDirectoriesW(const std::wstring &path, unsigned int mode);
+// Resolve a symlink to its target.
+// If `path` is a symlink, result will contain the target it points to,
+// If `path` is a not a symlink, result will contain `path` itself.
+// If the resolving succeeds, this function returns true,
+// otherwise it returns false.
+bool ReadSymlinkW(const std::wstring& path, std::wstring* result);
+
+// Check if `path` is a directory.
+bool IsDirectoryW(const std::wstring& path);
+
// Interface to be implemented by ForEachDirectoryEntryW clients.
class DirectoryEntryConsumerW {
public:
diff --git a/src/main/cpp/util/file_windows.cc b/src/main/cpp/util/file_windows.cc
index d266f960c28ac0..ecc8c02026d4eb 100644
--- a/src/main/cpp/util/file_windows.cc
+++ b/src/main/cpp/util/file_windows.cc
@@ -46,7 +46,7 @@ using std::wstring;
// Returns true if `path` refers to a directory or (non-dangling) junction.
// `path` must be a normalized Windows path, with UNC prefix (and absolute) if
// necessary.
-static bool IsDirectoryW(const wstring& path);
+bool IsDirectoryW(const wstring& path);
// Returns true the file or junction at `path` is successfully deleted.
// Returns false otherwise, or if `path` doesn't exist or is a directory.
@@ -549,6 +549,100 @@ bool JunctionResolver::Resolve(const WCHAR* path, unique_ptr<WCHAR[]>* result) {
return Resolve(path, result, kMaximumJunctionDepth);
}
+class SymlinkResolver {
+ public:
+ SymlinkResolver();
+
+ // Resolves symlink to its actual path.
+ //
+ // Returns true if `path` is not a symlink and it exists.
+ // Returns true if `path` is a symlink and can be successfully resolved.
+ // Returns false otherwise.
+ //
+ // If `result` is not nullptr and the method returned true, then this will be
+ // reset to point to a new WCHAR buffer containing the resolved path.
+ // If `path` is a symlink, this will be the resolved path, otherwise
+ // it will be a copy of `path`.
+ bool Resolve(const WCHAR* path, std::unique_ptr<WCHAR[]>* result);
+
+ private:
+ // Symbolic Link Reparse Data Buffer is described at:
+ // https://msdn.microsoft.com/en-us/library/cc232006.aspx
+ typedef struct _ReparseSymbolicLinkData {
+ static const int kSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
+ ULONG ReparseTag;
+ USHORT ReparseDataLength;
+ USHORT Reserved;
+ USHORT SubstituteNameOffset;
+ USHORT SubstituteNameLength;
+ USHORT PrintNameOffset;
+ USHORT PrintNameLength;
+ ULONG Flags;
+ WCHAR PathBuffer[1];
+ } ReparseSymbolicLinkData;
+
+ uint8_t reparse_buffer_bytes_[ReparseSymbolicLinkData::kSize];
+ ReparseSymbolicLinkData* reparse_buffer_;
+};
+
+SymlinkResolver::SymlinkResolver()
+ : reparse_buffer_(
+ reinterpret_cast<ReparseSymbolicLinkData*>(reparse_buffer_bytes_)) {
+}
+
+bool SymlinkResolver::Resolve(const WCHAR* path, unique_ptr<WCHAR[]>* result) {
+ DWORD attributes = ::GetFileAttributesW(path);
+ if (attributes == INVALID_FILE_ATTRIBUTES) {
+ // `path` does not exist.
+ return false;
+ } else {
+ if ((attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
+ bool is_dir = attributes & FILE_ATTRIBUTE_DIRECTORY;
+ AutoHandle handle(CreateFileW(path,
+ FILE_READ_EA,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL,
+ OPEN_EXISTING,
+ (is_dir ? FILE_FLAG_BACKUP_SEMANTICS : 0)
+ | FILE_FLAG_OPEN_REPARSE_POINT,
+ NULL));
+ if (!handle.IsValid()) {
+ // Opening the symlink failed for whatever reason. For all intents and
+ // purposes we can treat this file as if it didn't exist.
+ return false;
+ }
+ // Read out the reparse point data.
+ DWORD bytes_returned;
+ BOOL ok = ::DeviceIoControl(
+ handle, FSCTL_GET_REPARSE_POINT, NULL, 0, reparse_buffer_,
+ MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &bytes_returned, NULL);
+ if (!ok) {
+ // Reading the symlink data failed. For all intents and purposes we can
+ // treat this file as if it didn't exist.
+ return false;
+ }
+ if (reparse_buffer_->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
+ if (result) {
+ size_t len = reparse_buffer_->SubstituteNameLength / sizeof(WCHAR);
+ result->reset(new WCHAR[len + 1]);
+ const WCHAR * substituteName = reparse_buffer_->PathBuffer
+ + (reparse_buffer_->SubstituteNameOffset / sizeof(WCHAR));
+ wcsncpy_s(result->get(), len + 1, substituteName, len);
+ result->get()[len] = UNICODE_NULL;
+ }
+ return true;
+ }
+ }
+ }
+ // `path` is a normal file or directory.
+ if (result) {
+ size_t len = wcslen(path) + 1;
+ result->reset(new WCHAR[len]);
+ memcpy(result->get(), path, len * sizeof(WCHAR));
+ }
+ return true;
+}
+
bool ReadDirectorySymlink(const string& name, string* result) {
wstring wname;
string error;
@@ -566,6 +660,23 @@ bool ReadDirectorySymlink(const string& name, string* result) {
return true;
}
+bool ReadSymlinkW(const wstring& name, wstring* result) {
+ wstring wname;
+ string error;
+ if (!AsAbsoluteWindowsPath(name, &wname, &error)) {
+ BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
+ << "ReadSymlinkW(" << name
+ << "): AsAbsoluteWindowsPath failed: " << error;
+ return false;
+ }
+ unique_ptr<WCHAR[]> result_ptr;
+ if (!SymlinkResolver().Resolve(wname.c_str(), &result_ptr)) {
+ return false;
+ }
+ *result = RemoveUncPrefixMaybe(result_ptr.get());
+ return true;
+}
+
bool PathExists(const string& path) {
if (path.empty()) {
return false;
@@ -776,7 +887,7 @@ bool CanAccessDirectory(const std::string& path) {
return true;
}
-static bool IsDirectoryW(const wstring& path) {
+bool IsDirectoryW(const wstring& path) {
DWORD attrs = ::GetFileAttributesW(path.c_str());
return (attrs != INVALID_FILE_ATTRIBUTES) &&
(attrs & FILE_ATTRIBUTE_DIRECTORY) &&
| null | train | train | 2018-08-29T03:49:14 | "2018-08-08T16:44:27Z" | filipesilva | test |
bazelbuild/bazel/5807_6024 | bazelbuild/bazel | bazelbuild/bazel/5807 | bazelbuild/bazel/6024 | [
"timestamp(timedelta=2227.0, similarity=0.8835729751180569)"
] | 206c19bf4cf8e9a3bc33289fe071700fcac1e2c6 | eb1695979c7b0c69a783138790e18a8f625bbeb5 | [
"@filipesilva I have made some progress on this recently.\r\nNow with Bazel built from HEAD, symlink tree will be available on Windows when you pass `--experimental_enable_runfiles`. \r\nCan you try if it helps with https://github.com/bazelbuild/bazel/issues/5926?",
"@filipesilva Just found a bug when dealing with long path, sending a fix now."
] | [
"Have you thought of using a `typedef`? I think that'd be more type-safe and more readable than a macro.",
"Have you thought of using an unnamed namespace? That restricts visibility and the binary will not export these symbols.\r\n\r\n(See https://google.github.io/styleguide/cppguide.html#Unnamed_Namespaces_and_Static_Variables)",
"What's the reason for using `explicit`?",
"The error message is confusing, \"INPUT RUNFILES\" can be understood as \"a list of input runfiles\". What's the intended meaning? Could you clarify the message?",
"I think the argument type does not need to be a const reference. Can you think of a more efficient approach?",
"What does the rest of the loop do when `use_metadata` is false?",
"What's the reason to store an entry when `target` is empty?",
"Is this call necessary? Doesn't `ifstream`'s destructor close the file?",
"String comparison should ignore casing.",
"This call fails if the directory is not empty. Is that expected?",
"Why can we ignore it?",
"Have you considered using a foreach-loop?",
"`CreateFileW` returns `INVALID_HANDLE_VALUE` on error. Please compare `h` to that instead of to `0`.",
"type-safety: use `FALSE` `FALSE` (BOOL) instead of `false` (bool).",
"Do you need to do this before every test, or would it suffice to export these envvars just once?",
"Why is there one more symlink on Windows?",
"You are calling `readlink $i` multiple times. Could you cache its result?",
"why is there one more symlink on Windows?",
"same here about `readlink $i`",
"Good idea. Replaced it with typedef and moved it into the class definition.",
"Good to know that, thanks!",
"Done",
"I copied from the Linux version build-runfiles.cc, but I think it's unnecessary, so removed.",
"If `use_metadata` is false, it means every line in the manifest is a runfile entry, then the loop will read each of them and add them in the manifest map. If `use_metadata` is true, it will skip all lines with even line number, because they are metadata lines.\r\nSee https://github.com/bazelbuild/bazel/blob/master/src/main/tools/build-runfiles.cc#L144",
"Bazel sometimes need to create empty files under the runfiles tree. For example, for python binary, `__init__.py` is needed under every directory. Storing an entry with an empty `target` indicates we need to create such a file when creating the runfiles tree.",
"Indeed, removed.",
"`AsAbsoluteWindowsPath` will convert the path to a normalized path, than means both of them are already in lower case.",
"Here we are deleting a symlink, so it won't fail even the target directory is not empty.",
"Because if the directory is not empty, it means it contains some symlinks already pointing to the correct targets (we just called `ScanTreeAndPrune`). Then this directory shouldn't be removed in the first place. It's better to check if the directory is empty before deleting it, but there's not simple kernel API for that.",
"Good idea! Done.",
"Done.",
"Done",
"Indeed, it's confusing. Updated.",
"Right, once is enough.",
"Because for shell binary, we build both `bin` and `bin.exe`, but on Linux we only build `bin`",
"Yes, done.",
"Answered in above comment.",
"Done.",
"Thanks. Please add this as a code comment.",
"Thanks! Could you add this explanation to the code?",
"Thanks! The convention in manpages is to put mandatory arguments in angle brackets, e.g. `<manifest_file>`. I think doing that here would increase readability.",
"The name `use_metadata` confuses me, it suggests that the function should use (or ignore) the metadata. WDYT? If you agree, can you think of a better name?",
"Could you add this as a comment?",
"Could you add this to the code as a comment?",
"Thanks, please add it as a comment here too.",
"Indeed, `ignore_metadata` is better.",
"Just realized `use_metadata` is also the flag name and used some other places in Java code. Let me instead add a comment here to clarify.",
"Done.",
"Done",
"Done!",
"Done",
"Done"
] | "2018-08-29T16:14:45Z" | [
"type: feature request",
"P2",
"platform: windows",
"area-Windows",
"team-OSS"
] | Use symlinked runfiles on Windows when supported | ### Description of the problem / feature request:
On Windows Bazel sets `RUNFILES_MANIFEST_ONLY` to `1` and does not generate symlinks to runfiles. This does not change if the current user can create symlinks.
On recent Windows 10 versions it is possible to enable symlinks for all users:
> Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.
More details can be found in https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10/
The feature I am requesting is to generate symlink to runfiles on Windows when supported by the current user.
### Feature requests: what underlying problem are you trying to solve with this feature?
Creating rules with windows support is not trivial (https://github.com/bazelbuild/bazel/issues/3726#issuecomment-329504506).
Using symlinks on windows when available should make many existing rules work on Windows without having to resolve runfiles via the manifest, given the user has symlink support.
On systems Windows without symlink support enabled, looking up the runfiles would still be necessary.
Related to https://github.com/bazelbuild/bazel/issues/3726, https://github.com/bazelbuild/bazel/issues/3889, https://github.com/bazelbuild/bazel/issues/1212
/cc @alexeagle | [
"src/main/cpp/util/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java",
"src/main/tools/BUILD",
"src/main/tools/build-runfiles-windows.cc"
] | [
"src/main/cpp/util/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java",
"src/main/tools/BUILD",
"src/main/tools/build-runfiles-windows.cc"
] | [
"src/test/py/bazel/runfiles_test.py",
"src/test/shell/integration/BUILD",
"src/test/shell/integration/runfiles_test.sh"
] | diff --git a/src/main/cpp/util/BUILD b/src/main/cpp/util/BUILD
index 9df4e558d8f472..bc799aba338af7 100644
--- a/src/main/cpp/util/BUILD
+++ b/src/main/cpp/util/BUILD
@@ -55,6 +55,7 @@ cc_library(
visibility = [
":ijar",
"//src/test/cpp/util:__pkg__",
+ "//src/main/tools:__pkg__",
"//src/tools/launcher:__subpackages__",
"//src/tools/singlejar:__pkg__",
"//third_party/def_parser:__pkg__",
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
index 7590d6aa696d28..2b58187dd7005d 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
@@ -1167,10 +1167,6 @@ public void reportInvalidOptions(EventHandler reporter) {
fragment.reportInvalidOptions(reporter, this.buildOptions);
}
- if (OS.getCurrent() == OS.WINDOWS && runfilesEnabled()) {
- reporter.handle(Event.error("building runfiles is not supported on Windows"));
- }
-
if (options.outputDirectoryName != null) {
reporter.handle(Event.error(
"The internal '--output directory name' option cannot be used on the command line"));
diff --git a/src/main/tools/BUILD b/src/main/tools/BUILD
index e67d67baaa6953..8362c0c0b6dd22 100644
--- a/src/main/tools/BUILD
+++ b/src/main/tools/BUILD
@@ -48,6 +48,7 @@ cc_binary(
"//src/conditions:windows": ["build-runfiles-windows.cc"],
"//conditions:default": ["build-runfiles.cc"],
}),
+ deps = ["//src/main/cpp/util:filesystem"],
)
cc_binary(
diff --git a/src/main/tools/build-runfiles-windows.cc b/src/main/tools/build-runfiles-windows.cc
index ea4eed189aab26..db01284e0c2635 100644
--- a/src/main/tools/build-runfiles-windows.cc
+++ b/src/main/tools/build-runfiles-windows.cc
@@ -12,16 +12,399 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+#include <windows.h>
#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <string.h>
+#include <unordered_map>
-int main(int argc, char** argv) {
- // TODO(bazel-team): decide whether we need build-runfiles at all on Windows.
- // Implement this program if so; make sure we don't run it on Windows if not.
- std::cout << "ERROR: build-runfiles is not (yet?) implemented on Windows."
- << std::endl
- << "Called with args:" << std::endl;
- for (int i = 0; i < argc; ++i) {
- std::cout << "argv[" << i << "]=(" << argv[i] << ")" << std::endl;
+#include "src/main/cpp/util/path_platform.h"
+#include "src/main/cpp/util/file_platform.h"
+#include "src/main/cpp/util/strings.h"
+
+using std::ifstream;
+using std::unordered_map;
+using std::string;
+using std::wstring;
+using std::stringstream;
+
+#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
+#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 0x2
+#endif
+
+#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
+#define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
+#endif
+
+namespace {
+
+const wchar_t *manifest_filename;
+const wchar_t *runfiles_base_dir;
+
+string GetLastErrorString() {
+ DWORD last_error = GetLastError();
+ if (last_error == 0) {
+ return string();
+ }
+
+ char* message_buffer;
+ size_t size = FormatMessageA(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPSTR)&message_buffer, 0, NULL);
+
+ stringstream result;
+ result << "(error: " << last_error << "): " << message_buffer;
+ LocalFree(message_buffer);
+ return result.str();
+}
+
+void die(const wchar_t* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ fputws(L"build-runfiles error: ", stderr);
+ vfwprintf(stderr, format, ap);
+ va_end(ap);
+ fputwc(L'\n', stderr);
+ fputws(L"manifest file name: ", stderr);
+ fputws(manifest_filename, stderr);
+ fputwc(L'\n', stderr);
+ fputws(L"runfiles base directory: ", stderr);
+ fputws(runfiles_base_dir, stderr);
+ fputwc(L'\n', stderr);
+ exit(1);
+}
+
+wstring AsAbsoluteWindowsPath(const wchar_t* path) {
+ wstring wpath;
+ string error;
+ if (!blaze_util::AsAbsoluteWindowsPath(path, &wpath, &error)) {
+ die(L"Couldn't convert %s to absolute Windows path: %hs", path,
+ error.c_str());
+ }
+ return wpath;
+}
+
+bool DoesDirectoryPathExist(const wchar_t* path) {
+ DWORD dwAttrib = GetFileAttributesW(AsAbsoluteWindowsPath(path).c_str());
+
+ return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
+ (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
+}
+
+wstring GetParentDirFromPath(const wstring& path) {
+ return path.substr(0, path.find_last_of(L"\\/"));
+}
+
+inline void Trim(wstring& str){
+ str.erase(0, str.find_first_not_of(' '));
+ str.erase(str.find_last_not_of(' ') + 1);
+}
+
+} // namespace
+
+class RunfilesCreator {
+ typedef std::unordered_map<std::wstring, std::wstring> ManifestFileMap;
+
+ public:
+ RunfilesCreator(const wstring &manifest_path,
+ const wstring &runfiles_output_base)
+ : manifest_path_(manifest_path),
+ runfiles_output_base_(runfiles_output_base) {
+ SetupOutputBase();
+ if (!SetCurrentDirectoryW(runfiles_output_base_.c_str())) {
+ die(L"SetCurrentDirectoryW failed (%s): %hs",
+ runfiles_output_base_.c_str(), GetLastErrorString().c_str());
+ }
+ }
+
+ void ReadManifest(bool allow_relative, bool ignore_metadata) {
+ ifstream manifest_file(
+ AsAbsoluteWindowsPath(manifest_path_.c_str()).c_str());
+
+ if (!manifest_file) {
+ die(L"Couldn't open MANIFEST file: %s", manifest_path_.c_str());
+ }
+
+ string line;
+ int lineno = 0;
+ while (getline(manifest_file, line)) {
+ lineno++;
+ // Skip metadata lines. They are used solely for
+ // dependency checking.
+ if (ignore_metadata && lineno % 2 == 0) {
+ continue;
+ }
+
+ size_t space_pos = line.find_first_of(' ');
+ wstring wline = blaze_util::CstringToWstring(line);
+ wstring link, target;
+ if (space_pos == string::npos) {
+ link = wline;
+ target = wstring();
+ } else {
+ link = wline.substr(0, space_pos);
+ target = wline.substr(space_pos + 1);
+ }
+
+ // Removing leading and trailing spaces
+ Trim(link);
+ Trim(target);
+
+
+ // We sometimes need to create empty files under the runfiles tree.
+ // For example, for python binary, __init__.py is needed under every directory.
+ // Storing an entry with an empty target indicates we need to create such a
+ // file when creating the runfiles tree.
+ if (!allow_relative && !target.empty()
+ && !blaze_util::IsAbsolute(target)) {
+ die(L"Target cannot be relative path: %hs", line.c_str());
+ }
+
+ link = AsAbsoluteWindowsPath(link.c_str());
+
+ manifest_file_map.insert(make_pair(link, target));
+ }
+ }
+
+ void CreateRunfiles() {
+ bool symlink_needs_privilege =
+ DoesCreatingSymlinkNeedAdminPrivilege(runfiles_output_base_);
+ ScanTreeAndPrune(runfiles_output_base_);
+ CreateFiles(symlink_needs_privilege);
+ CopyManifestFile();
}
- return 1;
+
+ private:
+ void SetupOutputBase() {
+ if (!DoesDirectoryPathExist(runfiles_output_base_.c_str())) {
+ MakeDirectoriesOrDie(runfiles_output_base_);
+ }
+ }
+
+ void MakeDirectoriesOrDie(const wstring& path) {
+ if (!blaze_util::MakeDirectoriesW(path, 0755)) {
+ die(L"MakeDirectoriesW failed (%s): %hs",
+ path.c_str(), GetLastErrorString().c_str());
+ }
+ }
+
+ void RemoveDirectoryOrDie(const wstring& path) {
+ if (!RemoveDirectoryW(path.c_str())) {
+ die(L"RemoveDirectoryW failed (%s): %hs", GetLastErrorString().c_str());
+ }
+ }
+
+ void DeleteFileOrDie(const wstring& path) {
+ SetFileAttributesW(path.c_str(),
+ GetFileAttributesW(path.c_str()) & ~FILE_ATTRIBUTE_READONLY);
+ if (!DeleteFileW(path.c_str())) {
+ die(L"DeleteFileW failed (%s): %hs",
+ path.c_str(), GetLastErrorString().c_str());
+ }
+ }
+
+ bool DoesCreatingSymlinkNeedAdminPrivilege(const wstring& runfiles_base_dir) {
+ wstring dummy_link = runfiles_base_dir + L"\\dummy_link";
+ wstring dummy_target = runfiles_base_dir + L"\\dummy_target";
+
+ // Try creating symlink without admin privilege.
+ if (CreateSymbolicLinkW(dummy_link.c_str(), dummy_target.c_str(),
+ SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
+ DeleteFileOrDie(dummy_link);
+ return false;
+ }
+
+ // Try creating symlink with admin privilege
+ if (CreateSymbolicLinkW(dummy_link.c_str(), dummy_target.c_str(), 0)) {
+ DeleteFileOrDie(dummy_link);
+ return true;
+ }
+
+ // If we couldn't create symlink, print out an error message and exit.
+ if (GetLastError() == ERROR_PRIVILEGE_NOT_HELD) {
+ die(L"CreateSymbolicLinkW failed:\n%hs\n",
+ "Bazel needs to create symlink for building runfiles tree.\n"
+ "Creating symlink on Windows requires either of the following:\n"
+ " 1. Program is running with elevated privileges (Admin rights).\n"
+ " 2. The system version is Windows 10 Creators Update (1703) or later and "
+ "developer mode is enabled.",
+ GetLastErrorString().c_str());
+ } else {
+ die(L"CreateSymbolicLinkW failed: %hs", GetLastErrorString().c_str());
+ }
+
+ return true;
+ }
+
+ // This function scan the current directory, remove all files/symlinks/directories that
+ // are not presented in manifest file.
+ // If a symlink already exists and points to the correct target, this function erases
+ // its entry from manifest_file_map, so that we won't recreate it.
+ void ScanTreeAndPrune(const wstring& path) {
+ static const wstring kDot(L".");
+ static const wstring kDotDot(L"..");
+
+ WIN32_FIND_DATAW metadata;
+ HANDLE handle = ::FindFirstFileW((path + L"\\*").c_str(), &metadata);
+ if (handle == INVALID_HANDLE_VALUE) {
+ return; // directory does not exist or is empty
+ }
+
+ do {
+ if (kDot != metadata.cFileName && kDotDot != metadata.cFileName) {
+ wstring subpath = path + L"\\" + metadata.cFileName;
+ bool is_dir =
+ (metadata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
+ bool is_symlink =
+ (metadata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
+ if (is_symlink) {
+ wstring target;
+ if (!blaze_util::ReadSymlinkW(subpath, &target)) {
+ die(L"ReadSymlinkW failed (%s): %hs",
+ subpath.c_str(), GetLastErrorString().c_str());
+ };
+
+ subpath = AsAbsoluteWindowsPath(subpath.c_str());
+ target = AsAbsoluteWindowsPath(target.c_str());
+ ManifestFileMap::iterator expected_target =
+ manifest_file_map.find(subpath);
+
+ if (expected_target == manifest_file_map.end()
+ || expected_target->second.empty()
+ // Both paths are normalized paths in lower case, we can compare them directly.
+ || target != AsAbsoluteWindowsPath(expected_target->second.c_str())
+ || blaze_util::IsDirectoryW(target) != is_dir) {
+ if (is_dir) {
+ RemoveDirectoryOrDie(subpath);
+ } else {
+ DeleteFileOrDie(subpath);
+ }
+ } else {
+ manifest_file_map.erase(expected_target);
+ }
+ } else {
+ if (is_dir) {
+ ScanTreeAndPrune(subpath);
+ // If the directory is empty, then we remove the directory.
+ // Otherwise RemoveDirectory will fail with ERROR_DIR_NOT_EMPTY,
+ // which we can just ignore.
+ // Because if the directory is not empty, it means it contains some symlinks
+ // already pointing to the correct targets (we just called ScanTreeAndPrune).
+ // Then this directory shouldn't be removed in the first place.
+ if (!RemoveDirectoryW(subpath.c_str())
+ && GetLastError() != ERROR_DIR_NOT_EMPTY) {
+ die(L"RemoveDirectoryW failed (%s): %hs",
+ subpath.c_str(), GetLastErrorString().c_str());
+ }
+ } else {
+ DeleteFileOrDie(subpath);
+ }
+ }
+ }
+ } while (::FindNextFileW(handle, &metadata));
+ ::FindClose(handle);
+ }
+
+ void CreateFiles(bool creating_symlink_needs_admin_privilege) {
+ DWORD privilege_flag = creating_symlink_needs_admin_privilege
+ ? 0
+ : SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
+
+ for (const auto &it : manifest_file_map) {
+ // Ensure the parent directory exists
+ wstring parent_dir = GetParentDirFromPath(it.first);
+ if (!DoesDirectoryPathExist(parent_dir.c_str())) {
+ MakeDirectoriesOrDie(parent_dir);
+ }
+
+ if (it.second.empty()) {
+ // Create an empty file
+ HANDLE h = CreateFileW(it.first.c_str(), // name of the file
+ GENERIC_WRITE, // open for writing
+ 0, // sharing mode, none in this case
+ 0, // use default security descriptor
+ CREATE_ALWAYS, // overwrite if exists
+ FILE_ATTRIBUTE_NORMAL,
+ 0);
+ if (h != INVALID_HANDLE_VALUE) {
+ CloseHandle(h);
+ } else {
+ die(L"CreateFileW failed (%s): %hs",
+ it.first.c_str(), GetLastErrorString().c_str());
+ }
+ } else {
+ DWORD create_dir = 0;
+ if (blaze_util::IsDirectoryW(it.second.c_str())) {
+ create_dir = SYMBOLIC_LINK_FLAG_DIRECTORY;
+ }
+ if (!CreateSymbolicLinkW(it.first.c_str(),
+ it.second.c_str(),
+ privilege_flag | create_dir)) {
+ die(L"CreateSymbolicLinkW failed (%s -> %s): %hs",
+ it.first.c_str(), it.second.c_str(),
+ GetLastErrorString().c_str());
+ }
+ }
+ }
+ }
+
+ void CopyManifestFile() {
+ wstring new_manifest_file = runfiles_output_base_ + L"\\MANIFEST";
+ if (!CopyFileW(manifest_path_.c_str(),
+ new_manifest_file.c_str(),
+ /*bFailIfExists=*/ FALSE
+ )) {
+ die(L"CopyFileW failed (%s -> %s): %hs",
+ manifest_path_.c_str(), new_manifest_file.c_str(),
+ GetLastErrorString().c_str());
+ }
+ }
+
+ private:
+ wstring manifest_path_;
+ wstring runfiles_output_base_;
+ ManifestFileMap manifest_file_map;
+};
+
+int wmain(int argc, wchar_t** argv) {
+ argc--; argv++;
+ bool allow_relative = false;
+ bool ignore_metadata = false;
+
+ while (argc >= 1) {
+ if (wcscmp(argv[0], L"--allow_relative") == 0) {
+ allow_relative = true;
+ argc--; argv++;
+ } else if (wcscmp(argv[0], L"--use_metadata") == 0) {
+ // If --use_metadata is passed, it means manifest file contains metadata lines,
+ // which we should ignore when reading manifest file.
+ ignore_metadata = true;
+ argc--; argv++;
+ } else {
+ break;
+ }
+ }
+
+ if (argc != 2) {
+ fprintf(stderr, "usage: [--allow_relative] [--use_metadata] "
+ "<manifest_file> <runfiles_base_dir>\n");
+ return 1;
+ }
+
+ manifest_filename = argv[0];
+ runfiles_base_dir = argv[1];
+
+ wstring manifest_absolute_path = AsAbsoluteWindowsPath(manifest_filename);
+ wstring output_base_absolute_path = AsAbsoluteWindowsPath(runfiles_base_dir);
+
+ RunfilesCreator runfiles_creator(manifest_absolute_path,
+ output_base_absolute_path);
+ runfiles_creator.ReadManifest(allow_relative, ignore_metadata);
+ runfiles_creator.CreateRunfiles();
+
+ return 0;
}
| diff --git a/src/test/py/bazel/runfiles_test.py b/src/test/py/bazel/runfiles_test.py
index 50506f63918e8a..36aba0d7678642 100644
--- a/src/test/py/bazel/runfiles_test.py
+++ b/src/test/py/bazel/runfiles_test.py
@@ -21,16 +21,6 @@
class RunfilesTest(test_base.TestBase):
- def testAttemptToBuildRunfilesOnWindows(self):
- if not self.IsWindows():
- self.skipTest("only applicable to Windows")
- self.ScratchFile("WORKSPACE")
- exit_code, _, stderr = self.RunBazel(
- ["build", "--experimental_enable_runfiles"])
- self.assertNotEqual(exit_code, 0)
- self.assertIn("building runfiles is not supported on Windows",
- "\n".join(stderr))
-
def _AssertRunfilesLibraryInBazelToolsRepo(self, family, lang_name):
for s, t, exe in [("WORKSPACE.mock", "WORKSPACE",
False), ("foo/BUILD.mock", "foo/BUILD",
diff --git a/src/test/shell/integration/BUILD b/src/test/shell/integration/BUILD
index 5501058918bb29..efdde9ec93af03 100644
--- a/src/test/shell/integration/BUILD
+++ b/src/test/shell/integration/BUILD
@@ -29,11 +29,12 @@ sh_test(
name = "runfiles_test",
size = "medium",
srcs = ["runfiles_test.sh"],
- data = [":test-deps"],
+ data = [
+ ":test-deps",
+ "@bazel_tools//tools/bash/runfiles",
+ ],
tags = [
"local",
- # no_windows: this test exercises the symlink-based runfiles tree.
- "no_windows",
],
)
diff --git a/src/test/shell/integration/runfiles_test.sh b/src/test/shell/integration/runfiles_test.sh
index cb2e88627e0438..fd85be9849fd82 100755
--- a/src/test/shell/integration/runfiles_test.sh
+++ b/src/test/shell/integration/runfiles_test.sh
@@ -16,18 +16,59 @@
#
# An end-to-end test that Bazel produces runfiles trees as expected.
-# Load the test setup defined in the parent directory
-CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-source "${CURRENT_DIR}/../integration_test_setup.sh" \
+# --- begin runfiles.bash initialization ---
+# Copy-pasted from Bazel's Bash runfiles library (tools/bash/runfiles/runfiles.bash).
+set -euo pipefail
+if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ if [[ -f "$0.runfiles_manifest" ]]; then
+ export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
+ elif [[ -f "$0.runfiles/MANIFEST" ]]; then
+ export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
+ elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
+ export RUNFILES_DIR="$0.runfiles"
+ fi
+fi
+if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
+ source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
+elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
+ "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)"
+else
+ echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"
+ exit 1
+fi
+# --- end runfiles.bash initialization ---
+
+source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
|| { echo "integration_test_setup.sh not found!" >&2; exit 1; }
+case "$(uname -s | tr [:upper:] [:lower:])" in
+msys*|mingw*|cygwin*)
+ declare -r is_windows=true
+ ;;
+*)
+ declare -r is_windows=false
+ ;;
+esac
+
+if "$is_windows"; then
+ export MSYS_NO_PATHCONV=1
+ export MSYS2_ARG_CONV_EXCL="*"
+ export EXT=".exe"
+ export EXTRA_BUILD_FLAGS="--experimental_enable_runfiles --build_python_zip=0"
+else
+ export EXT=""
+ export EXTRA_BUILD_FLAGS=""
+fi
+
#### SETUP #############################################################
set -e
-function set_up() {
- mkdir -p pkg
- cd pkg
+function create_pkg() {
+ local -r pkg=$1
+ mkdir -p $pkg
+ cd $pkg
mkdir -p a/b c/d e/f/g x/y
touch py.py a/b/no_module.py c/d/one_module.py c/__init__.py e/f/g/ignored.py x/y/z.sh
@@ -40,7 +81,9 @@ function set_up() {
#### TESTS #############################################################
function test_hidden() {
- cat > pkg/BUILD << EOF
+ local -r pkg=$FUNCNAME
+ create_pkg $pkg
+ cat > $pkg/BUILD << EOF
py_binary(name = "py",
srcs = [ "py.py" ],
data = [ "e/f",
@@ -49,19 +92,21 @@ genrule(name = "hidden",
outs = [ "e/f/g/hidden.py" ],
cmd = "touch \$@")
EOF
- bazel build pkg:py >&$TEST_log 2>&1 || fail "build failed"
+ bazel build $pkg:py $EXTRA_BUILD_FLAGS >&$TEST_log 2>&1 || fail "build failed"
# we get a warning that hidden.py is inaccessible
- expect_log_once "pkg/e/f/g/hidden.py obscured by pkg/e/f "
+ expect_log_once "${pkg}/e/f/g/hidden.py obscured by ${pkg}/e/f "
}
function test_foo_runfiles() {
+ local -r pkg=$FUNCNAME
+ create_pkg $pkg
cat > BUILD << EOF
py_library(name = "root",
srcs = ["__init__.py"],
visibility = ["//visibility:public"])
EOF
-cat > pkg/BUILD << EOF
+cat > $pkg/BUILD << EOF
sh_binary(name = "foo",
srcs = [ "x/y/z.sh" ],
data = [ ":py",
@@ -74,9 +119,10 @@ py_binary(name = "py",
"e/f/g/ignored.py" ],
deps = ["//:root"])
EOF
- bazel build pkg:foo >&$TEST_log || fail "build failed"
+ bazel build $pkg:foo $EXTRA_BUILD_FLAGS >&$TEST_log || fail "build failed"
+ workspace_root=$PWD
- cd ${PRODUCT_NAME}-bin/pkg/foo.runfiles
+ cd ${PRODUCT_NAME}-bin/$pkg/foo${EXT}.runfiles
# workaround until we use assert/fail macros in the tests below
touch $TEST_TMPDIR/__fail
@@ -88,10 +134,10 @@ EOF
cd ${WORKSPACE_NAME}
# these are real directories
- test \! -L pkg
- test -d pkg
+ test \! -L $pkg
+ test -d $pkg
- cd pkg
+ cd $pkg
test \! -L a
test -d a
test \! -L a/b
@@ -133,17 +179,110 @@ EOF
# that accounts for everything
cd ../..
- assert_equals 9 $(find ${WORKSPACE_NAME} -type l | wc -l)
- assert_equals 4 $(find ${WORKSPACE_NAME} -type f | wc -l)
- assert_equals 9 $(find ${WORKSPACE_NAME} -type d | wc -l)
- assert_equals 22 $(find ${WORKSPACE_NAME} | wc -l)
- assert_equals 13 $(wc -l < MANIFEST)
+ # For shell binary, we build both `bin` and `bin.exe`, but on Linux we only build `bin`
+ # That's why we have one more symlink on Windows.
+ if "$is_windows"; then
+ assert_equals 10 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 4 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 9 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 23 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 14 $(wc -l < MANIFEST)
+ else
+ assert_equals 9 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 4 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 9 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 22 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 13 $(wc -l < MANIFEST)
+ fi
for i in $(find ${WORKSPACE_NAME} \! -type d); do
- if readlink "$i" > /dev/null; then
- echo "$i $(readlink "$i")" >> ${TEST_TMPDIR}/MANIFEST2
+ target="$(readlink "$i" || true)"
+ if [[ -z "$target" ]]; then
+ echo "$i " >> ${TEST_TMPDIR}/MANIFEST2
else
+ if "$is_windows"; then
+ echo "$i $(cygpath -m $target)" >> ${TEST_TMPDIR}/MANIFEST2
+ else
+ echo "$i $target" >> ${TEST_TMPDIR}/MANIFEST2
+ fi
+ fi
+ done
+ sort MANIFEST > ${TEST_TMPDIR}/MANIFEST_sorted
+ sort ${TEST_TMPDIR}/MANIFEST2 > ${TEST_TMPDIR}/MANIFEST2_sorted
+ diff -u ${TEST_TMPDIR}/MANIFEST_sorted ${TEST_TMPDIR}/MANIFEST2_sorted
+
+ # Rebuild the same target with a new dependency.
+ cd "$workspace_root"
+cat > $pkg/BUILD << EOF
+sh_binary(name = "foo",
+ srcs = [ "x/y/z.sh" ],
+ data = [ "e/f" ])
+EOF
+ bazel build $pkg:foo $EXTRA_BUILD_FLAGS >&$TEST_log || fail "build failed"
+
+ cd ${PRODUCT_NAME}-bin/$pkg/foo${EXT}.runfiles
+
+ # workaround until we use assert/fail macros in the tests below
+ touch $TEST_TMPDIR/__fail
+
+ # output manifest exists and is non-empty
+ test -f MANIFEST
+ test -s MANIFEST
+
+ cd ${WORKSPACE_NAME}
+
+ # these are real directories
+ test \! -L $pkg
+ test -d $pkg
+
+ # these directory should not exist anymore
+ test \! -e a
+ test \! -e c
+
+ cd $pkg
+ test \! -L e
+ test -d e
+ test \! -L x
+ test -d x
+ test \! -L x/y
+ test -d x/y
+
+ # these are symlinks to the source tree
+ test -L foo
+ test -L x/y/z.sh
+ test -L e/f
+ test -d e/f
+
+ # that accounts for everything
+ cd ../..
+ # For shell binary, we build both `bin` and `bin.exe`, but on Linux we only build `bin`
+ # That's why we have one more symlink on Windows.
+ if "$is_windows"; then
+ assert_equals 4 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 0 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 5 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 9 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 4 $(wc -l < MANIFEST)
+ else
+ assert_equals 3 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 0 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 5 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 8 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 3 $(wc -l < MANIFEST)
+ fi
+
+ rm -f ${TEST_TMPDIR}/MANIFEST
+ rm -f ${TEST_TMPDIR}/MANIFEST2
+ for i in $(find ${WORKSPACE_NAME} \! -type d); do
+ target="$(readlink "$i" || true)"
+ if [[ -z "$target" ]]; then
echo "$i " >> ${TEST_TMPDIR}/MANIFEST2
+ else
+ if "$is_windows"; then
+ echo "$i $(cygpath -m $target)" >> ${TEST_TMPDIR}/MANIFEST2
+ else
+ echo "$i $target" >> ${TEST_TMPDIR}/MANIFEST2
+ fi
fi
done
sort MANIFEST > ${TEST_TMPDIR}/MANIFEST_sorted
@@ -166,15 +305,15 @@ EOF
cat > thing.cc <<EOF
int main() { return 0; }
EOF
- bazel build //:thing &> $TEST_log || fail "Build failed"
- [[ -d ${PRODUCT_NAME}-bin/thing.runfiles/foo ]] || fail "foo not found"
+ bazel build //:thing $EXTRA_BUILD_FLAGS &> $TEST_log || fail "Build failed"
+ [[ -d ${PRODUCT_NAME}-bin/thing${EXT}.runfiles/foo ]] || fail "foo not found"
cat > WORKSPACE <<EOF
workspace(name = "bar")
EOF
- bazel build //:thing &> $TEST_log || fail "Build failed"
- [[ -d ${PRODUCT_NAME}-bin/thing.runfiles/bar ]] || fail "bar not found"
- [[ ! -d ${PRODUCT_NAME}-bin/thing.runfiles/foo ]] \
+ bazel build //:thing $EXTRA_BUILD_FLAGS &> $TEST_log || fail "Build failed"
+ [[ -d ${PRODUCT_NAME}-bin/thing${EXT}.runfiles/bar ]] || fail "bar not found"
+ [[ ! -d ${PRODUCT_NAME}-bin/thing${EXT}.runfiles/foo ]] \
|| fail "Old foo still found"
}
| val | train | 2018-08-29T18:09:19 | "2018-08-08T16:44:27Z" | filipesilva | test |
bazelbuild/bazel/5810_6636 | bazelbuild/bazel | bazelbuild/bazel/5810 | bazelbuild/bazel/6636 | [
"timestamp(timedelta=2799.0, similarity=0.9213884834542884)"
] | c543992dea17f88190f1cda9980491ca858f10a0 | 262c4e1debac828601e38c0f67f2ff0b281892a3 | [
"Revamped in https://github.com/bazelbuild/bazel/commit/92b14d3f5ada6c857ba9a3cefbfcf7affaf16450"
] | [
"how about \"This tutorial does not require experience with Bazel or Android app development.\"",
"hmm, this seems to contradict the Android Studio being in Prerequisites?",
"\"Initialize the project's workspace\"?",
"this reassurance feels a bit odd, since presumably people are here because they want to work with android code",
"\"and has a WORKSPACE file ...\"",
"\"the app\" -> \"your project\"?",
"hmm how about \"The `WORKSPACE` file contains the references to external dependencies that are required to build the project (it can also be empty if your project is self-contains).\"",
"\"Integrate with the Android SDK\"? (though \"Integrating with the Android SDK\" sounds better, but I think you're trying to keep the parallelism with verbs)",
"\"This will use the Android SDK at the path specified by the ANDROID_HOME environment variable ...\"",
"\", for example:\"",
"it might be good to say why one might want to explicitly specify these attributes on the rule",
"i'm pretty sure that the package name would more accurately be \"the path to the BUILD file relative to the WORKSPACE\"",
"\"Note that Bazel's package hierarchy is conceptually different from the Java package hierarchy of your Android App ...\"?",
"\"For the simple Android app in this tutorial, we'll make all the source files in `src/main/java` a single Bazel package\"",
"\"instructions\" -> \"declarations\"?",
"consider putting the app's manifest one level up in `main`",
"\"you'll first use the android_library rule to tell Bazel to build an Android library module\" (i.e., maintaining the distinction between declaration and instruction)",
"\"Locate\" sounds better",
"\"stores\" sounds too fancy. \"puts\"?",
"I recommend omitting the `$` prompt indicator (for all platforms, for sake of consistency).\r\nAFAIK it's not customary on Windows and may be confusing and considered part of the command.",
"In the Command Prompt, `setx` affects subsequent sessions but not the current one. `set` affects the current session only.\r\nTheir semantics are also different:\r\n- `setx` understands quoting, so `setx FOO \"some value\"` is appropriate and stores the value without quotes\r\n- `set` does not understand quoting, so `set FOO=some value` is the right approach; `set FOO=\"some value\"` would include the quotes in the value\r\n\r\nIn Powershell, the command you specified affects subsequent sessions but not the current one.\r\nTo set an envvar for the current session, you have to run `$env:FOO=\"some value\"`.",
"I recommend adding an example for Windows too. The key thing to call out is that `path` must use mixed-style ( see `cygpath --mixed`) paths, i.e. Windows path with forward slashes, e.g. `c:/path/to/sdk`.",
"`$WORKSPACE` does not make sense on Windows. I recommend some other notation, e.g. `<workspace>/bazel-out`.",
"done.",
"removed the line. I'll add it back when we have other tutorials on Android Studio and testing. ",
"done.",
"done.",
"done.",
"done.",
"I broke it the current paragraph up into two lines so it reads crispier.",
"done.",
"done.",
"done.",
"done.",
"done.",
"done.",
"done.",
"done.",
"done. https://github.com/bazelbuild/examples/pull/79",
"done.",
"done.",
"done.",
"done, removed all `$` prompts.",
"thank you for the clear explanation! I split the table to two: one to set it for the current session, and another to set it persistently.",
"done. added a Windows example.",
"I removed the prefix, and added a note about where these directories can be found."
] | "2018-11-08T21:51:28Z" | [
"type: feature request",
"P2",
"team-Android"
] | Refresh Android build tutorial on docs.bazel.build | Link: https://docs.bazel.build/versions/master/tutorial/android-app.html
Ideas:
- [ ] Remove references to OS specific commands. e.g. `touch`, `export`, `WORKSPACE` environment variables.
- [ ] Update versions
- [ ] Improve the flow of the tutorial. It asks the user to add snippets or create files that already exists in the examples repository.
- [ ] More screenshots. The tutorial looks very dense. | [
"site/docs/tutorial/android-app.md"
] | [
"site/docs/tutorial/android-app.md"
] | [] | diff --git a/site/docs/tutorial/android-app.md b/site/docs/tutorial/android-app.md
index 20db3e2ac81f78..20d6baef3126f5 100644
--- a/site/docs/tutorial/android-app.md
+++ b/site/docs/tutorial/android-app.md
@@ -3,140 +3,151 @@ layout: documentation
title: Build Tutorial - Android
---
-Introduction to Bazel: Building an Android App
-==========
+# Introduction to Bazel: Building an Android App
-In this tutorial, you will learn how to build a simple Android app. You'll do
-the following:
+In this tutorial, you will learn how to build a simple Android app using Bazel.
-* [Set up your environment](#set-up-your-environment)
- * [Install Bazel](#install-bazel)
- * [Install Android Studio](#install-android-studio)
- * [Get the sample project](#get-the-sample-project)
-* [Set up a workspace](#set-up-a-workspace)
- * [Create a WORKSPACE file](#create-a-workspace-file)
- * [Update the WORKSPACE file](#update-the-workspace-file)
-* [Review the source files](#review-the-source-files)
-* [Create a BUILD file](#create-a-build-file)
- * [Add an android_library rule](#add-an-android_library-rule)
- * [Add an android_binary rule](#add_an-android_binary-rule)
-* [Build the app](#build-the-app)
-* [Find the build outputs](#find-the-build-outputs)
-* [Run the app](#run-the-app)
-* [Review your work](#review-your-work)
+Bazel supports building Android apps using the [Android
+rules](https://docs.bazel.build/versions/master/be/android.html).
-## Set up your environment
+This tutorial is intended for Windows, macOS and Linux users and does not
+require experience with Bazel or Android app development. You do not need to
+write any Android code in this tutorial.
-To get started, install Bazel and Android Studio, and get the sample project.
+## Prerequisites
-### Install Bazel
+You will need to install the following software:
-Follow the [installation instructions](../install.md) to install Bazel and
-its dependencies.
+* Bazel. To install, follow the [installation instructions](../install.md).
+* Android Studio. To install, follow the steps to [download Android
+ Studio](https://developer.android.com/sdk/index.html).
+* (Optional) Git. We will use `git` to download the Android app project.
-### Install Android Studio
+## Getting started
-Download and install Android Studio as described in [Install Android Studio](https://developer.android.com/sdk/index.html).
+We will be using a basic Android app project in [Bazel's examples
+repository](https://github.com/bazelbuild/examples).
-The installer does not automatically set the `ANDROID_HOME` variable.
-Set it to the location of the Android SDK, which defaults to `$HOME/Android/Sdk/`
-.
+This app has a single button that prints a greeting when clicked.
-For example:
+<img src="/assets/android_tutorial_app.png" alt="screenshot of tutorial app"
+width="700">
-`export ANDROID_HOME=$HOME/Android/Sdk/`
+Clone the repository with `git` (or [download the ZIP file
+directly](https://github.com/bazelbuild/examples/archive/master.zip)):
-For convenience, add the above statement to your `~/.bashrc` file.
+``` bash
+git clone [email protected]:bazelbuild/examples.git bazel-examples
+cd bazel-examples/android/tutorial
+```
-### Get the sample project
+For the rest of the tutorial, you will be executing commands in this directory.
-You also need to get the sample project for the tutorial from GitHub. The repo
-has two branches: `source-only` and `master`. The `source-only` branch contains
-the source files for the project only. You'll use the files in this branch in
-this tutorial. The `master` branch contains both the source files and completed
-Bazel `WORKSPACE` and `BUILD` files. You can use the files in this branch to
-check your work when you've completed the tutorial steps.
+## Review the source files
-Enter the following at the command line to get the files in the `source-only`
-branch:
+Let's take a look at the source files for the app.
-```bash
-cd $HOME
-git clone -b source-only https://github.com/bazelbuild/examples
+```
+.
+├── README.md
+└── src
+ └── main
+ ├── AndroidManifest.xml
+ └── java
+ └── com
+ └── example
+ └── bazel
+ ├── AndroidManifest.xml
+ ├── Greeter.java
+ ├── MainActivity.java
+ └── res
+ ├── layout
+ │ └── activity_main.xml
+ └── values
+ ├── colors.xml
+ └── strings.xml
```
-The `git clone` command creates a directory named `$HOME/examples/`. This
-directory contains several sample projects for Bazel. The project files for this
-tutorial are in `$HOME/examples/tutorial/android`.
+The key files and directories are:
-## Set up a workspace
+| Name | Location |
+| Android manifest files | `src/main/AndroidManifest.xml` and `src/main/java/com/example/bazel/AndroidManifest.xml` |
+| Android source files | `src/main/java/com/example/bazel/MainActivity.java` and `Greeter.java` |
+| Resource file directory | `src/main/java/com/example/bazel/res/` |
-A [workspace](../build-ref.html#workspaces) is a directory that contains the
-source files for one or more software projects, as well as a `WORKSPACE` file
-and `BUILD` files that contain the instructions that Bazel uses to build
-the software. The workspace may also contain symbolic links to output
-directories.
+## Initialize the project's workspace
-A workspace directory can be located anywhere on your filesystem and is denoted
-by the presence of the `WORKSPACE` file at its root. In this tutorial, your
-workspace directory is `$HOME/examples/tutorial/`, which contains the sample
-project files you cloned from the GitHub repo in the previous step.
+A [workspace](../build-ref.html#workspace) is a directory that contains the
+source files for one or more software projects, and has a `WORKSPACE` file in
+the top level of the directory.
-Note that Bazel itself doesn't make any requirements about how you organize
-source files in your workspace. The sample source files in this tutorial are
-organized according to conventions for the target platform.
+The `WORKSPACE` file may be empty or it may contain references to [external
+dependencies](../external.html) required to build your project.
-For your convenience, set the `$WORKSPACE` environment variable now to refer to
-your workspace directory. At the command line, enter:
+First, run the following command to create an empty `WORKSPACE` file:
-```bash
-export WORKSPACE=$HOME/examples/tutorial
-```
+| Linux, macOS | `touch WORKSPACE` |
+| Windows (Command Prompt) | `type nul > WORKSPACE` |
+| Windows (PowerShell) | `New-Item WORKSPACE -ItemType file` |
-### Create a WORKSPACE file
+### Running Bazel
-Every workspace must have a text file named `WORKSPACE` located in the top-level
-workspace directory. This file may be empty or it may contain references
-to [external dependencies](../external.html) required to build the
-software.
+You can now check if Bazel is running correctly with the command:
-For now, you'll create an empty `WORKSPACE` file, which simply serves to
-identify the workspace directory. In later steps, you'll update the file to add
-external dependency information.
+```bash
+bazel info workspace
+```
-Enter the following at the command line:
+If Bazel prints the path of the current directory, you're good to go! If the
+`WORKSPACE` file does not exist, you may see an error message like:
-```bash
-touch $WORKSPACE/WORKSPACE
```
-This creates the empty `WORKSPACE` file.
+ERROR: The 'info' command is only supported from within a workspace.
+```
-### Update the WORKSPACE file
+## Integrate with the Android SDK
-Bazel needs to run the Android SDK
-[build tools](https://developer.android.com/tools/revisions/build-tools.html)
-and uses the SDK libraries to build the app. This means that you need to add
-some information to your `WORKSPACE` file so that Bazel knows where to find
-them. Note that this step is not required when you build for other platforms.
-For example, Bazel automatically detects the location of Java, C++ and
-Objective-C compilers from settings in your environment.
+Bazel needs to run the Android SDK [build
+tools](https://developer.android.com/tools/revisions/build-tools.html) to build
+the app. This means that you need to add some information to your `WORKSPACE`
+file so that Bazel knows where to find them.
-Add the following lines to your `WORKSPACE` file:
+Add the following line to your `WORKSPACE` file:
```python
-android_sdk_repository(
- name = "androidsdk"
-)
+android_sdk_repository(name = "androidsdk")
```
-This will use the Android SDK referenced by the `ANDROID_HOME` environment
-variable, and automatically detect the highest API level and the latest version
-of build tools installed within that location.
+This will use the Android SDK at the path referenced by the `ANDROID_HOME`
+environment variable, and automatically detect the highest API level and the
+latest version of build tools installed within that location.
+
+You can set the `ANDROID_HOME` variable to the location of the Android SDK. Find
+the path to the installed SDK using Android Studio's [SDK
+Manager](https://developer.android.com/studio/intro/update#sdk-manager).
+
+For example, as the default SDK path is in your home directory for Linux and
+macOS, and `LOCALAPPDATA` for Windows, you can use the following commands to set
+the `ANDROID_HOME` variable:
+
+| Linux, macOS | `export ANDROID_HOME=$HOME/Android/Sdk/` |
+| Windows (Command Prompt) | `set ANDROID_HOME=%LOCALAPPDATA%\Android\Sdk` |
+| Windows (PowerShell) | `$env:ANDROID_HOME="$env:LOCALAPPDATA\Android\Sdk"` |
-Alternatively, you can explicitly specify the location of the Android
-SDK, the API level, and the version of build tools to use by including the
-`path`,`api_level`, and `build_tools_version` attributes. You can specify any
-subset of these attributes:
+Note that the commands above will set the variable for the current shell session
+only. To make it permanent for future sessions, run the following:
+
+| Linux, macOS | `echo "export ANDROID_HOME=$HOME/Android/Sdk/" >> ~/.bashrc` |
+| Windows (Command Prompt) | `setx ANDROID_HOME "%LOCALAPPDATA%\Android\Sdk"` |
+| Windows (PowerShell) | `[System.Environment]::SetEnvironmentVariable('ANDROID_HOME', "$env:LOCALAPPDATA\Android\Sdk", [System.EnvironmentVariableTarget]::User)` |
+
+Alternatively, you can explicitly specify the absolute path of the Android SDK,
+the API level, and the version of build tools to use by including the `path`,
+`api_level`, and `build_tools_version` attributes. If `api_level` and
+`build_tools_version` are not specified, the `android_sdk_repository` rule will
+use the respective latest version available in the SDK. You can specify any
+combination of these attributes, as long as they are present in the SDK, for
+example:
```python
android_sdk_repository(
@@ -147,245 +158,217 @@ android_sdk_repository(
)
```
-**Optional:** This is not required by this tutorial, but if you want to compile
-native code into your Android app, you also need to download the
-[Android NDK](https://developer.android.com/ndk/downloads/index.html) and
-tell Bazel where to find it by adding the following rule to your `WORKSPACE`
-file:
+On Windows, note that the `path` attribute must use the mixed-style path, that
+is, a Windows path with forward slashes:
```python
-android_ndk_repository(
- name = "androidndk"
+android_sdk_repository(
+ name = "androidsdk",
+ path = "c:/path/to/Android/sdk",
)
```
-`api_level` is the version of the Android API the SDK and the NDK target
-(for example, 23 for Android 6.0 and 25 for Android 7.1). If not explicitly
-set, `api_level` will default to the highest available API level for
-`android_sdk_repository` and `android_ndk_repository`. It's not necessary to
-set the API levels to the same value for the SDK and NDK.
-[This web page](https://developer.android.com/ndk/guides/stable_apis.html)
-contains a map from Android releases to NDK-supported API levels.
-
-Similar to `android_sdk_repository`, the path to the Android NDK is inferred
-from the `ANDROID_NDK_HOME` environment variable by default. The path can also
-be explicitly specified with a `path` attribute on `android_ndk_repository`.
-
-## Review the source files
-
-Let's take a look at the source files for the app. These are located in
-`$WORKSPACE/android/`.
-
-The key files and directories are:
-
-<table class="table table-condensed table-striped">
-<thead>
-<tr>
-<td>Name</td>
-<td>Location</td>
-</tr>
-</thead>
-<tbody>
-<tr>
-<td>Manifest file</td>
-<td><code>src/main/java/com/google/bazel/example/android/AndroidManifest.xml</code></td>
-</tr>
-<tr>
-<td>Activity source file</td>
-<td><code>src/main/java/com/google/bazel/example/android/activities/MainActivity.java</code></td>
-</tr>
-<tr>
-<td>Resource file directory</td>
-<td><code>src/main/java/com/google/bazel/example/android/res/</code></td>
-</tr>
-</tbody>
-</table>
-
-Note that you're just looking at these files now to become familiar with the
-structure of the app. You don't have to edit any of the source files to complete
-this tutorial.
+> **Optional:** This is not required by this tutorial, but if you want to compile
+> native code into your Android app, you also need to download the [Android
+> NDK](https://developer.android.com/ndk/downloads/index.html) and tell Bazel
+> where to find it by adding the following line to your `WORKSPACE` file:
+>
+> ```python
+> android_ndk_repository(name = "androidndk")
+> ```
+>
+> Similar to `android_sdk_repository`, the path to the Android NDK is inferred
+> from the `ANDROID_NDK_HOME` environment variable by default. The path can also
+> be explicitly specified with a `path` attribute on `android_ndk_repository`.
+>
+> For more information, read [Using the Android Native Development Kit with
+> Bazel](https://docs.bazel.build/versions/master/android-ndk.html).
+
+`api_level` is the version of the Android API that the SDK (and the NDK) will
+target (for example, 23 for Android 6.0 and 25 for Android 7.1). If not
+explicitly set, `api_level` will default to the highest available API level for
+`android_sdk_repository` and `android_ndk_repository`.
+
+It's not necessary to set the API levels to the same value for the SDK and NDK.
+[This page](https://developer.android.com/ndk/guides/stable_apis.html) contains
+a map from Android releases to NDK-supported API levels.
## Create a BUILD file
-A [`BUILD` file](../build-ref.html#BUILD_files) is a text file that describes
-the relationship between a set of build outputs -- for example, compiled
-software libraries or executables -- and their dependencies. These dependencies
-may be source files in your workspace or other build outputs. `BUILD` files are
-written in the Bazel *build language*.
+A [`BUILD` file](../build-ref.html#BUILD_files) describes the relationship
+between a set of build outputs, like compiled Android resources from `aapt` or
+class files from `javac`, and their dependencies. These dependencies may be
+source files (Java, C++) in your workspace or other build outputs. `BUILD` files
+are written in a language called **Starlark**.
`BUILD` files are part of a concept in Bazel known as the *package hierarchy*.
The package hierarchy is a logical structure that overlays the directory
structure in your workspace. Each [package](../build-ref.html#packages) is a
directory (and its subdirectories) that contains a related set of source files
and a `BUILD` file. The package also includes any subdirectories, excluding
-those that contain their own `BUILD` file. The *package name* is the name of the
-directory where the `BUILD` file is located.
-
-Note that this package hierarchy is distinct from, but coexists with, the Java
-package hierarchy for your Android app.
+those that contain their own `BUILD` file. The *package name* is the path to the
+`BUILD` file relative to the `WORKSPACE`.
-For the simple Android app in this tutorial, we'll consider all the source files
-in `$WORKSPACE/android/` to comprise a single Bazel package. A more complex
-project may have many nested packages.
+Note that Bazel's package hierarchy is conceptually different from the Java
+package hierarchy of your Android App directory where the `BUILD` file is
+located. , although the directories may be organized identically.
-At a command-line prompt, open your new `BUILD` file for editing:
-
-```bash
-vi $WORKSPACE/android/BUILD
-```
+For the simple Android app in this tutorial, we'll make all the source files in
+`src/main/` to comprise a single Bazel package. A more complex project may have
+many nested packages.
### Add an android_library rule
-A `BUILD` file contains several different types of instructions for Bazel. The
+A `BUILD` file contains several different types of declarations for Bazel. The
most important type is the [build rule](../build-ref.html#funcs), which tells
Bazel how to build an intermediate or final software output from a set of source
files or other dependencies.
Bazel provides two build rules, `android_library` and `android_binary`, that you
can use to build an Android app. For this tutorial, you'll first use the
-[`android_library`](../be/android.html#android_library) rule to tell
-Bazel how to build an
-[Android library module](http://developer.android.com/tools/projects/index.html#LibraryProjects)
+[`android_library`](../be/android.html#android_library) rule to tell Bazel to
+build an [Android library
+module](http://developer.android.com/tools/projects/index.html#LibraryProjects)
from the app source code and resource files. Then you'll use the
`android_binary` rule to tell it how to build the Android application package.
-Add the following to your `BUILD` file:
+Create a new `BUILD` file in the `src/main/java/com/example/bazel` directory,
+and declare a new `android_library` target:
+
+`src/main/java/com/example/bazel/BUILD`:
```python
+package(
+ default_visibility = ["//src:__subpackages__"],
+)
+
android_library(
- name = "activities",
- srcs = glob(["src/main/java/com/google/bazel/example/android/activities/*.java"]),
- custom_package = "com.google.bazel.example.android.activities",
- manifest = "src/main/java/com/google/bazel/example/android/activities/AndroidManifest.xml",
- resource_files = glob(["src/main/java/com/google/bazel/example/android/activities/res/**"]),
+ name = "greeter_activity",
+ srcs = [
+ "Greeter.java",
+ "MainActivity.java",
+ ],
+ manifest = "AndroidManifest.xml",
+ resource_files = glob(["res/**"]),
)
```
-As you can see, the `android_library` build rule contains a set of attributes
-that specify the information that Bazel needs to build a library module from the
-source files. Note also that the name of the rule is `activities`. You'll
-reference the rule using this name as a dependency in the `android_binary` rule.
+The `android_library` build rule contains a set of attributes that specify the
+information that Bazel needs to build a library module from the source files.
+Note also that the name of the rule is `greeter_activity`. You'll reference the
+rule using this name as a dependency in the `android_binary` rule.
### Add an android_binary rule
The [`android_binary`](../be/android.html#android_binary) rule builds
the Android application package (`.apk` file) for your app.
-Add the following to your build file:
+Create a new `BUILD` file in the `src/main/` directory,
+and declare a new `android_binary` target:
+
+`src/main/BUILD`:
```python
android_binary(
- name = "android",
- custom_package = "com.google.bazel.example.android",
- manifest = "src/main/java/com/google/bazel/example/android/AndroidManifest.xml",
- resource_files = glob(["src/main/java/com/google/bazel/example/android/res/**"]),
- deps = [":activities"],
+ name = "app",
+ manifest = "AndroidManifest.xml",
+ deps = ["//src/main/java/com/example/bazel:greeter_activity"],
)
```
-Here, the `deps` attribute references the output of the `activities` rule you
-added to the `BUILD` file above. This means that, when Bazel builds the output
-of this rule, it checks first to see if the output of the `activities` library
-rule has been built and is up-to-date. If not, it builds it and then uses that
-output to build the application package file.
+Here, the `deps` attribute references the output of the `greeter_activity` rule
+you added to the `BUILD` file above. This means that, when Bazel builds the
+output of this rule, it checks first to see if the output of the
+`greeter_activity` library rule has been built and is up-to-date. If not, it
+builds it and then uses that output to build the application package file.
-Now, save and close the file. You can compare your `BUILD` file to the
-[completed example](https://github.com/bazelbuild/examples/blob/master/tutorial/android/BUILD)
-in the `master` branch of the GitHub repo.
+Now, save and close the file.
## Build the app
-You use the
-[`bazel`](../user-manual.html) command-line tool to run builds, execute
-unit tests and perform other operations in Bazel. This tool is located in the
-`output` subdirectory of the location where you installed Bazel. During
-[installation](../install.md), you probably added this location to your
-path.
-
-Before you build the sample app, make sure that your current working directory
-is inside your Bazel workspace:
+Let's try building the app! Run the following command to build the
+`android_binary` target:
```bash
-cd $WORKSPACE
+bazel build //src/main:app
```
-Now, enter the following to build the sample app:
-
-```bash
-bazel build //android:android
-```
+The [`build`](../user-manual.html#build) subcommand instructs Bazel to build the
+target that follows. The target is specified as the name of a build rule inside
+a `BUILD` file, with along with the package path relative to your workspace
+directory. For this example, the target is `app` and the package path is
+`//src/main/`.
-The [`build`](../user-manual.html#build) subcommand instructs Bazel to
-build the target that follows. The target is specified as the name of a build
-rule inside a `BUILD` file, with along with the package path relative to
-your workspace directory. Note that you can sometimes omit the package path
-or target name, depending on your current working directory at the command
-line and the name of the target. See [Labels](../build-ref.html#labels) in the
-*Bazel Concepts and Terminology* page for more information about target labels
-and paths.
+Note that you can sometimes omit the package path or target name, depending on
+your current working directory at the command line and the name of the target.
+See [Labels](../build-ref.html#labels) in the *Bazel Concepts and Terminology*
+page for more information about target labels and paths.
-Bazel now launches and builds the sample app. During the build process, its
-output will appear similar to the following:
+Bazel will start to build the sample app. During the build process, its output
+will appear similar to the following:
```bash
+INFO: Analysed target //src/main:app (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
-Target //android:android up-to-date:
- bazel-bin/android/android_deploy.jar
- bazel-bin/android/android_unsigned.apk
- bazel-bin/android/android.apk
-INFO: Elapsed time: 7.237s, Critical Path: 5.81s
+Target //src/main:app up-to-date:
+ bazel-bin/src/main/app_deploy.jar
+ bazel-bin/src/main/app_unsigned.apk
+ bazel-bin/src/main/app.apk
```
-## Find the build outputs
+## Locate the build outputs
-Bazel stores the outputs of both intermediate and final build operations in
-a set of per-user, per-workspace output directories. These directories are
-symlinked from the following locations:
+Bazel puts the outputs of both intermediate and final build operations in a set
+of per-user, per-workspace output directories. These directories are symlinked
+from the following locations at the top-level of the project directory, where
+the `WORKSPACE` is:
-* `$WORKSPACE/bazel-bin`, which stores binary executables and other runnable
- build outputs
-* `$WORKSPACE/bazel-genfiles`, which stores intermediary source files that are
- generated by Bazel rules
-* `$WORKSPACE/bazel-out`, which stores other types of build outputs
+* `bazel-bin`, which stores binary executables and other runnable build outputs
+* `bazel-genfiles`, which stores intermediary source files that are generated by
+ Bazel rules
+* `bazel-out`, which stores other types of build outputs
Bazel stores the Android `.apk` file generated using the `android_binary` rule
-in the `bazel-bin/android/` directory, where the subdirectory name `android` is
+in the `bazel-bin/src/main` directory, where the subdirectory name `src/main` is
derived from the name of the Bazel package.
-At a command prompt, list the contents of this directory and find the
-`android.apk` file:
+At a command prompt, list the contents of this directory and find the `app.apk`
+file:
-```bash
-ls $WORKSPACE/bazel-bin/android
-```
+| Linux, macOS | `ls bazel-bin/src/main` |
+| Windows (Command Prompt) | `dir bazel-bin\src\main` |
+| Windows (PowerShell) | `ls bazel-bin\src\main` |
-## Run the app
-**NOTE:** The app launches standalone but requires a backend server in order to
-produce output. See the README file in the sample project directory to find out
-how to build the backend server.
+## Run the app
You can now deploy the app to a connected Android device or emulator from the
-command line using the
-[`bazel mobile-install`](../user-manual.html#mobile-install)
-command. This command uses the Android Debug Bridge (`adb`) to communicate with
-the device. You must set up your device to use `adb` following the instructions
-in
-[Android Debug Bridge](http://developer.android.com/tools/help/adb.html) before
-deployment. You can also choose to install the app on the Android emulator
-included in Android Studio. Make sure the emulator is running before executing
-the command below.
+command line using the [`bazel
+mobile-install`](../user-manual.html#mobile-install) command. This command uses
+the Android Debug Bridge (`adb`) to communicate with the device. You must set up
+your device to use `adb` following the instructions in [Android Debug
+Bridge](http://developer.android.com/tools/help/adb.html) before deployment. You
+can also choose to install the app on the Android emulator included in Android
+Studio. Make sure the emulator is running before executing the command below.
Enter the following:
```bash
-bazel mobile-install //android:android
+bazel mobile-install //src/main:app
```
+Next, find and launch the "Bazel Tutorial App". You should see this screen:
+
+<img src="/assets/android_tutorial_before.png" alt="screenshot of tutorial app" width="500">
+
+**Congrats! You have just installed your first Bazel-built Android app.**
+
Note that the `mobile-install` subcommand also supports the
-[`--incremental`](../user-manual.html#mobile-install)
-flag that can be used to deploy only those parts of the app that have changed
-since the last deployment.
+[`--incremental`](../user-manual.html#mobile-install) flag that can be used to
+deploy only those parts of the app that have changed since the last deployment.
+
+It also supports the `--start_app` flag to start the app immediately upon
+installing it.
## Review your work
@@ -398,15 +381,18 @@ you:
for the app and a `WORKSPACE` file that identifies the top level of the
workspace directory
* Updated the `WORKSPACE` file to contain references to the required
- external dependencies
+ external dependencies, like the Android SDK
* Created a `BUILD` file
* Ran Bazel to build the app
* Deployed and ran the app on an Android emulator and device
-The built app is located in the `$WORKSPACE/bazel-bin` directory.
+## Further reading
+
+You now know the basics of building an Android project with Bazel. Here are some
+other pages to check out:
+
+* More information on [mobile-install](mobile-install.md)
+* Testing your app with [Android instrumentation tests](android-instrumentation-test.md)
+* Integrating C and C++ code into your Android app with the [NDK](android-ndk.md)
-Note that completed `WORKSPACE` and `BUILD` files for this tutorial are located
-in the
-[master branch](https://github.com/bazelbuild/examples/tree/master/tutorial)
-of the GitHub repo. You can compare your work to the completed files for
-additional help or troubleshooting.
+Happy building!
| null | train | train | 2018-11-08T22:45:14 | "2018-08-08T18:24:45Z" | jin | test |
bazelbuild/bazel/5821_9156 | bazelbuild/bazel | bazelbuild/bazel/5821 | bazelbuild/bazel/9156 | [
"timestamp(timedelta=0.0, similarity=0.8801452286846743)"
] | 406915b1ff80ee42455f35ff5dbfde1ddbce3dfc | ea6a7895b60d86a94aeb08a6561a933f408fcca9 | [
"@iirina,\nhave we removed the blockers from this?\nWe still haven't been able to move rules_scala to the new one AFAIR and\nunfortunately due to the strict-deps false negative we're also stuck with a\nrather old rules_scala version\n\nOn Thu, Aug 9, 2018 at 1:32 AM c-parsons <[email protected]> wrote:\n\n> This is a tracking issue for offering a migration solution for\n> --incompatible_disallow_legacy_javainfo\n>\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/bazelbuild/bazel/issues/5821>, or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/ABUIF8onFHTeQvFHV5_D19wEkgVhoAEpks5uO2bmgaJpZM4V0xLv>\n> .\n>\n",
"Any context on the blockers here? (Is there another github issue?)",
"I got this error message:\r\n> create_provider is deprecated and cannot be used when --incompatible_disallow_legacy_javainfo is set. Please migrate to the JavaInfo constructor.\r\n\r\nDocumentation is not great (https://docs.bazel.build/versions/master/skylark/lib/java_common.html#create_provider doesn't even say it's deprecated) and it's not clear how to migrate the existing code.\r\n\r\n(cc @lberki)",
"@iirina Can you help `rules_scala` and `rules_kotlin` migrate?",
"@laurentlb yes. @ittaiz What can I do to help `rules_scala`?",
"I use the deprecated create_provider API as follows:\r\n\r\n```\r\nnew_providers.append(\r\n java_common.create_provider(\r\n use_ijar = False,\r\n compile_time_jars = provider.compile_jars,\r\n runtime_jars = provider.runtime_output_jars,\r\n transitive_compile_time_jars = compile_time_jars,\r\n transitive_runtime_jars = runtime_jars,\r\n ),\r\n )\r\n```\r\n\r\nin order to remove specific jars from the compile and runtime classpath. I do not believe I can implement the same functionality with the JavaInfo constructor. If it's possible, please tell me how so that I can port my code before the deprecated create_provider is removed from Bazel. Thanks.\r\n",
"Can you say a bit more why you need to remove specific jars? Maybe it will\nhelp think what you can do\nOn Fri, 25 Jan 2019 at 21:14 Robert Brown <[email protected]> wrote:\n\n> I use the deprecated create_provider API as follows:\n>\n> new_providers.append(\n> java_common.create_provider(\n> use_ijar = False,\n> compile_time_jars = provider.compile_jars,\n> runtime_jars = provider.runtime_output_jars,\n> transitive_compile_time_jars = compile_time_jars,\n> transitive_runtime_jars = runtime_jars,\n> ),\n> )\n>\n> in order to remove specific jars from the compile and runtime classpath. I\n> do not believe I can implement the same functionality with the JavaInfo\n> constructor. If it's possible, please tell me how so that I can port my\n> code before the deprecated create_provider is removed from Bazel. Thanks.\n>\n> —\n> You are receiving this because you were mentioned.\n>\n>\n> Reply to this email directly, view it on GitHub\n> <https://github.com/bazelbuild/bazel/issues/5821#issuecomment-457690483>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/ABUIFwJRigGu2m6aO1-PQEevHBWv0nNzks5vG1eRgaJpZM4V0xLv>\n> .\n>\n",
"Java developers expect to be able to override the library dependencies of the libraries their code depends upon. For instance, suppose my code depends on two libraries, lib1 and lib2. The lib1 target has a dependency on guava22 and the lib2 target depends on guava25. I want to use both in my application.\r\n\r\nMy Starlark code implements a rule called java_exclude_library that removes jars from the compilation and run-time Java classpaths. You use it like this:\r\n```\r\njava_exclude_library(\r\n name = \"lib1_without_guava\",\r\n excludes = [\r\n \"//third_party/com.google.guava/guava22\",\r\n ],\r\n deps = [\r\n \":lib1\",\r\n ],\r\n)\r\n```\r\nto create lib1_without_guava from java_library lib1. The lib1_without_guava target is identical to lib1, except that the jar for guava22 does not appear on its compilation and run-time classpath. My application depends on targets lib1_without_guava and lib2. All the code in my application ends up using guava25 at run time.\r\n",
"I added a comment to the issue explaining why I need a JavaInfo constructor\nthat allows control over classpath jars.\n\nOn Sat, Jan 26, 2019 at 3:59 PM Ittai Zeidman <[email protected]>\nwrote:\n\n> Can you say a bit more why you need to remove specific jars? Maybe it will\n> help think what you can do\n> On Fri, 25 Jan 2019 at 21:14 Robert Brown <[email protected]>\n> wrote:\n>\n> > I use the deprecated create_provider API as follows:\n> >\n> > new_providers.append(\n> > java_common.create_provider(\n> > use_ijar = False,\n> > compile_time_jars = provider.compile_jars,\n> > runtime_jars = provider.runtime_output_jars,\n> > transitive_compile_time_jars = compile_time_jars,\n> > transitive_runtime_jars = runtime_jars,\n> > ),\n> > )\n> >\n> > in order to remove specific jars from the compile and runtime classpath.\n> I\n> > do not believe I can implement the same functionality with the JavaInfo\n> > constructor. If it's possible, please tell me how so that I can port my\n> > code before the deprecated create_provider is removed from Bazel. Thanks.\n> >\n> > —\n> > You are receiving this because you were mentioned.\n> >\n> >\n> > Reply to this email directly, view it on GitHub\n> > <https://github.com/bazelbuild/bazel/issues/5821#issuecomment-457690483\n> >,\n> > or mute the thread\n> > <\n> https://github.com/notifications/unsubscribe-auth/ABUIFwJRigGu2m6aO1-PQEevHBWv0nNzks5vG1eRgaJpZM4V0xLv\n> >\n> > .\n> >\n>\n> —\n> You are receiving this because you commented.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/bazelbuild/bazel/issues/5821#issuecomment-457865518>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AABqsUwdYr11YsbJKpNQSbwh24N7HKIaks5vHMGrgaJpZM4V0xLv>\n> .\n>\n",
"👍🏽\nI think maybe the discussion on the specific (and interesting) use case\nshould continue on a separate issue but I’ll leave that decision to @iirina\nand @lberki\nOn Mon, 28 Jan 2019 at 18:16 Robert Brown <[email protected]> wrote:\n\n> I added a comment to the issue explaining why I need a JavaInfo constructor\n> that allows control over classpath jars.\n>\n> On Sat, Jan 26, 2019 at 3:59 PM Ittai Zeidman <[email protected]>\n> wrote:\n>\n> > Can you say a bit more why you need to remove specific jars? Maybe it\n> will\n> > help think what you can do\n> > On Fri, 25 Jan 2019 at 21:14 Robert Brown <[email protected]>\n> > wrote:\n> >\n> > > I use the deprecated create_provider API as follows:\n> > >\n> > > new_providers.append(\n> > > java_common.create_provider(\n> > > use_ijar = False,\n> > > compile_time_jars = provider.compile_jars,\n> > > runtime_jars = provider.runtime_output_jars,\n> > > transitive_compile_time_jars = compile_time_jars,\n> > > transitive_runtime_jars = runtime_jars,\n> > > ),\n> > > )\n> > >\n> > > in order to remove specific jars from the compile and runtime\n> classpath.\n> > I\n> > > do not believe I can implement the same functionality with the JavaInfo\n> > > constructor. If it's possible, please tell me how so that I can port my\n> > > code before the deprecated create_provider is removed from Bazel.\n> Thanks.\n> > >\n> > > —\n> > > You are receiving this because you were mentioned.\n> > >\n> > >\n> > > Reply to this email directly, view it on GitHub\n> > > <\n> https://github.com/bazelbuild/bazel/issues/5821#issuecomment-457690483\n> > >,\n> > > or mute the thread\n> > > <\n> >\n> https://github.com/notifications/unsubscribe-auth/ABUIFwJRigGu2m6aO1-PQEevHBWv0nNzks5vG1eRgaJpZM4V0xLv\n> > >\n> > > .\n> > >\n> >\n> > —\n> > You are receiving this because you commented.\n> > Reply to this email directly, view it on GitHub\n> > <https://github.com/bazelbuild/bazel/issues/5821#issuecomment-457865518\n> >,\n> > or mute the thread\n> > <\n> https://github.com/notifications/unsubscribe-auth/AABqsUwdYr11YsbJKpNQSbwh24N7HKIaks5vHMGrgaJpZM4V0xLv\n> >\n> > .\n> >\n>\n> —\n> You are receiving this because you were mentioned.\n>\n>\n> Reply to this email directly, view it on GitHub\n> <https://github.com/bazelbuild/bazel/issues/5821#issuecomment-458195838>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/ABUIF0vDWtHoEvQKhu3NUp5ya3uuHjgjks5vHyJggaJpZM4V0xLv>\n> .\n>\n",
"Here is a link to the ts_java_exclude_library Starlark rule that uses java_common.create_provider.\r\nI do not believe this rule can be implemented once the create_provider API is removed.\r\n\r\nhttps://github.com/twosigma/bazel-rules/blob/master/ts_java_exclude.bzl\r\n",
"@brown Thanks for letting me know. Can you explain briefly what the rule is trying to accomplish, especially the method `_create_exclude_providers`? I'm trying to understand your use case and come up with a solution.\r\n\r\n",
"You can control what ends-up on the runtime classpath using [JavaInfo(neverlink = ...)](https://docs.bazel.build/versions/master/skylark/lib/JavaInfo.html#JavaInfo). I'm not sure why you need to control the compilation classpath as well.",
"I don't think the neverlink parameter to JavaInfo helps.\r\n\r\nThe goal is to create a Java library from other Java libraries, but with some transitive dependencies removed from the run-time class path.\r\n\r\nLet say one group develops Java library1, which has many transitive dependencies including a java_import of Guava version 19. \r\n\r\nA second group develops Java library2, which has many transitive dependencies including a java_import of Guava version 20.\r\n\r\nI want to create a Java binary that depends on both library1 and library2, but if my Java code depends on both libraries, then both versions of Guava will be on my application's class path, which can cause problems.\r\n\r\nI can use the ts_java_exclude_library rule to make a new library that combines both library1 and library2, but excludes Guava 19:\r\n\r\n ts_java_exclude_library(\r\n name = \"libraries_without_guava19\",\r\n excludes = [ \"//ext/public/google/guava/19/0:jars\" ],\r\n deps = [\r\n \":library1\",\r\n \":library2\",\r\n ],\r\n )\r\n\r\nAbove, the excluded target is the java_import of Guava 19 jar files that library1 transitively depends on.\r\n\r\nMy Java binary depends on libraries_without_guava19. It includes library1 and its dependencies, which have been compiled with Guava 19. It also includes library2 and its dependencies, which have been compiled with Guava 20. Both library1 and library2 use Guava 20 when my binary runs, because Guava 19 has been excluded from the class path.\r\n",
"The _create_exclude_providers function iterates through a list of Java Providers. For each Provider it creates a new one that's identical to the original, except when specific jar files occur in the original's run-time or compile-time class paths. In that case the new Provider lacks the jars in its class paths.\r\n\r\nThe code may not need to remove jars from the compile-time class path.\r\n",
"This wasn't flipped in time for 0.25. Changing label to 0.26. ",
"> The goal is to create a Java library from other Java libraries, but with some transitive dependencies removed from the run-time class path.\r\n\r\nThis is what `neverlink` is supposed to do, and you can use it on any kind of java rule targets. Assuming the guava targets defined via java_import(name = 'guava19',...) and java_import(name = 'guava20',...), you can set `neverlink = true` on guava19 and it won't end up on the runtime classpath. Can you think of disadvantages of always setting a java_import/java_library as neverlink in your project? I'm more inclined towards a solution with higher abstraction rather than cherry picking classpath jars.",
"@ittaiz What's the status on the scala rules? Is there anything I can help with to migrate to the JavaInfo constructor?",
"I too would be happier with a API that does not involve directly modifying Java class paths, but I currently don't have any good ideas for implementing an exclude feature without the ability to manipulate class path lists.\r\n\r\nTwo Sigma has a large monorepo containing thousands of external Java libraries, most of which have been imported from Maven. The Maven dependencies between packages are programmatically converted into dependencies between Bazel java_import libraries. With these dependencies a Two Sigma library can depend on an external Java package and all of that package's run time needs appear on an application's Java class path. If some external libraries have neverlink set to True, then libraries and/or binaries that depend on them will have to use runtime_deps to add back required run time dependencies. Managing runtime_deps lists with hundreds of entries would be a nightmare.\r\n\r\nLet's say I took your suggestion and set neverlink to True for the java_import of library guava19. That could be used to remove guava19 from my application's or library's Java class path. But what about all the other binaries and libraries in my monorepo that prefer to use guava19? I have to track down those Bazel targets and add guava19 to the runtime_deps of binaries and/or libraries.\r\n\r\nThe deprecated JavaInfo constructor is the only Bazel API that allows a rule to remove a dependency from the Java class path once it has been added by a transitive dependency. In the Two Sigma monorepo there are hundreds of instances where a jar is excluded from a Java class path. Google doesn't encounter this problem primarily because of its one version policy for external library dependencies. In a company with a monorepo containing several versions of many external libraries, the ability to depend on an internal library but selectively exclude some of its transitive external dependencies is valuable.\r\n",
"What is the migration status for this issue?",
"@dslomov am I just 5 minutes late on every issue? :)",
"@iirina @ittaiz do you have any context here? I'm unsure of what remains to be done for rules scala",
"Friendly ping @ittaiz :)",
"@brown The flag needs to be flipped in Bazel 1.0. I put together some snippets to help you migrate your use case and still be able to exclude some jars. Please let me know how I can help further.\r\n\r\n\r\n```\r\n# after computing runtime_jars and compile_time_jars\r\n\r\ntransitive_compile_providers = [JavaInfo(\r\n output_jar = compile_time_jar,\r\n compile_jar = compile_time_jar,\r\n neverlink = True,\r\n)\r\nfor compile_time_jar in compile_time_jars]\r\n\r\ntransitive_runtime_providers = [JavaInfo(\r\n output_jar = runtime_jar,\r\n compile_jar = runtime_jar,\r\n)\r\nfor runtime_jar in runtime_jars]\r\n\r\ncompile_providers = [JavaInfo(\r\n output_jar = compile_jar,\r\n compile_jar = compile_jar,\r\n neverlink = True,\r\n)\r\nfor compile_jar in provider.compile_jars]\r\n\r\nruntime_providers = [JavaInfo(\r\n output_jar = runtime_jar,\r\n compile_jar = runtime_jar,\r\n deps = transitive_runtime_providers,\r\n)\r\nfor runtime_jar in provider.runtime_output_jars]\r\n\r\nnew_providers.append(java_common.merge(compile_providers + runtime_providers)\r\n```",
"Is there migration tooling available/possible? How bad is the breakage?",
"@dslomov No, the migration is different from use case to use case. \r\n\r\nI migrated the internal projects and also `rules_scala` in https://github.com/bazelbuild/rules_scala/pull/781. There is an open PR for `rules_kotlin` in https://github.com/bazelbuild/rules_kotlin/pull/197, and one internal open change for migrating intellij. \r\nOther than that, `rules_jvm_external` have to upgrade their `rules_scala` and `rules_kotlin` versions (cc @jin). No other breakages on our CI, but I don't know if projects that are not on BazelCI have migrated.",
"Thanks very much for the snippet of code. It seems to work well.\nI will patch the library rule. Thanks again!\n\n\nOn Mon, Aug 5, 2019 at 10:40 AM Irina Iancu <[email protected]>\nwrote:\n\n> @brown <https://github.com/brown> The flag needs to be flipped in Bazel\n> 1.0. I put together some snippets to help you migrate your use case and\n> still be able to exclude some jars. Please let me know how I can help\n> further.\n>\n> # after computing runtime_jars and compile_time_jars\n>\n> transitive_compile_providers = [JavaInfo(\n> output_jar = compile_time_jar,\n> compile_jar = compile_time_jar,\n> neverlink = True,\n> )\n> for compile_time_jar in compile_time_jars]\n>\n> transitive_runtime_providers = [JavaInfo(\n> output_jar = runtime_jar,\n> compile_jar = runtime_jar,\n> )\n> for runtime_jar in runtime_jars]\n>\n> compile_providers = [JavaInfo(\n> output_jar = compile_jar,\n> compile_jar = compile_jar,\n> neverlink = True,\n> )\n> for compile_jar in provider.compile_jars]\n>\n> runtime_providers = [JavaInfo(\n> output_jar = runtime_jar,\n> compile_jar = runtime_jar,\n> deps = transitive_runtime_providers,\n> )\n> for runtime_jar in provider.runtime_output_jars]\n>\n> new_providers.append(java_common.merge(compile_providers + runtime_providers)\n>\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/bazelbuild/bazel/issues/5821?email_source=notifications&email_token=AAAGVMO5U7QV5EVP3IR3V5TQDA3VJA5CNFSM4FOTCLX2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD3SA3BY#issuecomment-518262151>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AAAGVMOUKW3FOVV4ZLVKETTQDA3VJANCNFSM4FOTCLXQ>\n> .\n>\n",
"@brown That's great to hear, thanks for trying it out!"
] | [] | "2019-08-13T07:34:30Z" | [
"P2",
"team-Rules-Java",
"incompatible-change"
] | incompatible_disallow_legacy_javainfo: Remove legacy (deprecated) JavaInfo constructors | This is a tracking issue for offering a migration solution for
`--incompatible_disallow_legacy_javainfo`
| [
"src/main/java/com/google/devtools/build/lib/packages/StarlarkSemanticsOptions.java",
"src/main/java/com/google/devtools/build/lib/syntax/StarlarkSemantics.java"
] | [
"src/main/java/com/google/devtools/build/lib/packages/StarlarkSemanticsOptions.java",
"src/main/java/com/google/devtools/build/lib/syntax/StarlarkSemantics.java"
] | [
"src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoSkylarkApiTest.java",
"src/test/shell/bazel/bazel_java_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/packages/StarlarkSemanticsOptions.java b/src/main/java/com/google/devtools/build/lib/packages/StarlarkSemanticsOptions.java
index 8f8fe4dcb2b852..a7c881250024c4 100644
--- a/src/main/java/com/google/devtools/build/lib/packages/StarlarkSemanticsOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/packages/StarlarkSemanticsOptions.java
@@ -361,7 +361,7 @@ public class StarlarkSemanticsOptions extends OptionsBase implements Serializabl
@Option(
name = "incompatible_disallow_legacy_javainfo",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.STARLARK_SEMANTICS,
effectTags = {OptionEffectTag.BUILD_FILE_SEMANTICS},
metadataTags = {
diff --git a/src/main/java/com/google/devtools/build/lib/syntax/StarlarkSemantics.java b/src/main/java/com/google/devtools/build/lib/syntax/StarlarkSemantics.java
index bf55bdf3087e98..cbd85b8acc1c13 100644
--- a/src/main/java/com/google/devtools/build/lib/syntax/StarlarkSemantics.java
+++ b/src/main/java/com/google/devtools/build/lib/syntax/StarlarkSemantics.java
@@ -269,7 +269,7 @@ public static Builder builderWithDefaults() {
.incompatibleDisallowDictPlus(true)
.incompatibleDisallowEmptyGlob(false)
.incompatibleDisallowLegacyJavaProvider(false)
- .incompatibleDisallowLegacyJavaInfo(false)
+ .incompatibleDisallowLegacyJavaInfo(true)
.incompatibleDisallowOldStyleArgsAdd(true)
.incompatibleDisallowRuleExecutionPlatformConstraintsAllowed(true)
.incompatibleDisallowStructProviderSyntax(false)
| diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoSkylarkApiTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoSkylarkApiTest.java
index acf7976ee2d227..7ac2224737ff97 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoSkylarkApiTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaInfoSkylarkApiTest.java
@@ -693,32 +693,6 @@ public void buildHelperCreateJavaInfoWithJdeps_javaRuleOutputJarsProvider() thro
assertThat(ruleOutputs.getJdeps().prettyPrint()).isEqualTo("foo/my_jdeps.pb");
}
- @Test
- public void testMixMatchNewAndLegacyArgsIsError() throws Exception {
- ImmutableList.Builder<String> lines = ImmutableList.builder();
- lines.add(
- "result = provider()",
- "def _impl(ctx):",
- " output_jar = ctx.actions.declare_file('output_jar')",
- " source_jar = ctx.actions.declare_file('source_jar')",
- " javaInfo = JavaInfo(",
- " output_jar = output_jar, ",
- " source_jar = source_jar,",
- " source_jars = [source_jar],",
- " )",
- " return [result(property = javaInfo)]",
- "my_rule = rule(",
- " implementation = _impl,",
- ")");
- scratch.file("foo/extension.bzl", lines.build().toArray(new String[] {}));
- checkError(
- "foo",
- "my_skylark_rule",
- "Cannot use deprecated arguments at the same time",
- "load(':extension.bzl', 'my_rule')",
- "my_rule(name = 'my_skylark_rule')");
- }
-
@Test
public void testIncompatibleDisallowLegacyJavaInfo() throws Exception {
setSkylarkSemanticsOptions("--incompatible_disallow_legacy_javainfo");
@@ -740,7 +714,7 @@ public void testIncompatibleDisallowLegacyJavaInfo() throws Exception {
checkError(
"foo",
"my_skylark_rule",
- "Cannot use deprecated argument when --incompatible_disallow_legacy_javainfo is set. ",
+ "Cannot use deprecated argument when --incompatible_disallow_legacy_javainfo is set",
"load(':extension.bzl', 'my_rule')",
"my_rule(name = 'my_skylark_rule')");
}
diff --git a/src/test/shell/bazel/bazel_java_test.sh b/src/test/shell/bazel/bazel_java_test.sh
index e42556c7a92166..d2af85c4f71959 100755
--- a/src/test/shell/bazel/bazel_java_test.sh
+++ b/src/test/shell/bazel/bazel_java_test.sh
@@ -1424,7 +1424,7 @@ def _impl(ctx):
host_javabase = ctx.attr._host_javabase[java_common.JavaRuntimeInfo],
)
- imported_provider = JavaInfo(output_jar = imported_jar, use_ijar=False);
+ imported_provider = JavaInfo(output_jar = imported_jar, compile_jar = imported_jar);
final_provider = java_common.merge([compilation_provider, imported_provider])
@@ -1453,81 +1453,6 @@ EOF
expect_log "<generated file java/com/google/sandwich/libb.jar>"
}
-
-
-function test_java_info_constructor_with_ijar_unset_actions() {
- mkdir -p java/com/google/foo
- touch java/com/google/foo/{BUILD,my_rule.bzl}
- cat > java/com/google/foo/BUILD << EOF
-load(":my_rule.bzl", "my_rule")
-my_rule(
- name = 'my_skylark_rule',
- output_jar = 'my_skylark_rule_lib.jar',
- source_jars = ['my_skylark_rule_src.jar']
- )
-EOF
-
- cat > java/com/google/foo/my_rule.bzl << EOF
-result = provider()
-def _impl(ctx):
- javaInfo = JavaInfo(
- output_jar = ctx.file.output_jar,
- source_jars = ctx.files.source_jars,
- use_ijar = True,
- java_toolchain = ctx.attr._java_toolchain[java_common.JavaToolchainInfo]
- )
- return [result(property = javaInfo)]
-
-my_rule = rule(
- implementation = _impl,
- attrs = {
- 'output_jar' : attr.label(allow_single_file=True),
- 'source_jars' : attr.label_list(allow_files=['.jar']),
- "_java_toolchain": attr.label(default = Label("@bazel_tools//tools/jdk:remote_toolchain"))
- }
-)
-EOF
-
- bazel build java/com/google/foo:my_skylark_rule >& "$TEST_log" && fail "Unexpected success"
- expect_log "The value of use_ijar is True. Make sure the ctx.actions argument is valid."
-}
-
-function test_java_info_constructor_with_ijar_unset_java_toolchain() {
- mkdir -p java/com/google/foo
- touch java/com/google/foo/{BUILD,my_rule.bzl}
- cat > java/com/google/foo/BUILD << EOF
-load(":my_rule.bzl", "my_rule")
-my_rule(
- name = 'my_skylark_rule',
- output_jar = 'my_skylark_rule_lib.jar',
- source_jars = ['my_skylark_rule_src.jar']
- )
-EOF
-
- cat > java/com/google/foo/my_rule.bzl << EOF
-result = provider()
-def _impl(ctx):
- javaInfo = JavaInfo(
- output_jar = ctx.file.output_jar,
- source_jars = ctx.files.source_jars,
- use_ijar = True,
- actions = ctx.actions
- )
- return [result(property = javaInfo)]
-
-my_rule = rule(
- implementation = _impl,
- attrs = {
- 'output_jar' : attr.label(allow_single_file=True),
- 'source_jars' : attr.label_list(allow_files=['.jar'])
- }
-)
-EOF
-
- bazel build java/com/google/foo:my_skylark_rule >& "$TEST_log" && fail "Unexpected success"
- expect_log "The value of use_ijar is True. Make sure the java_toolchain argument is valid."
-}
-
function test_java_info_constructor_e2e() {
mkdir -p java/com/google/foo
touch java/com/google/foo/{BUILD,my_rule.bzl}
| train | train | 2019-08-13T01:05:06 | "2018-08-08T22:32:03Z" | c-parsons | test |
bazelbuild/bazel/5863_5864 | bazelbuild/bazel | bazelbuild/bazel/5863 | bazelbuild/bazel/5864 | [
"timestamp(timedelta=0.0, similarity=0.909201512789194)"
] | 468f177334d4375f762e1dcdb13c51feeed11dfb | f432c10c1cdeb62e78179c04888ddd32db4ba999 | [] | [] | "2018-08-11T11:50:55Z" | [
"team-Rules-Java",
"untriaged"
] | java_import_external rule is partly broken | On most recent Bazel master (d0a3c5eb67320906e4b937df5434f0e673cb6dce), combining `neverlink = True` and `generated_linkable_rule_name = "foo"` attributes seems to be broken:
```
def external_plugin_deps():
java_import_external(
name = "javamelody-core",
jar_sha256 = "eb2806497676da54e257840626b64e8e53121fe2f3599457f7748e381918b2c1",
jar_urls = [
"https://github.com/davido/javamelody/releases/download/javamelody-core-1.73.2/javamelody-core-1.73.2.jar",
],
licenses = ["notice"],
neverlink = True,
generated_linkable_rule_name = "linkable-javamelody-core",
)
```
The failure is:
```
$ bazel build plugins/javamelody:javamelody
DEBUG: /home/davido/.cache/bazel/_bazel_davido/5c01f4f713b675540b8b424c5c647f63/external/bazel_skylib/lib/versions.bzl:98:7:
Current Bazel is not a release version, cannot check for compatibility.
DEBUG: /home/davido/.cache/bazel/_bazel_davido/5c01f4f713b675540b8b424c5c647f63/external/bazel_skylib/lib/versions.bzl:99:7: Make sure that you are running at least Bazel 0.14.0.
INFO: Build options have changed, discarding analysis cache.
ERROR: /home/davido/projects/gerrit2/plugins/javamelody/BUILD:10:1: no such package '@javamelody-core//': Traceback (most recent call last):
File "/home/davido/.cache/bazel/_bazel_davido/5c01f4f713b675540b8b424c5c647f63/external/bazel_tools/tools/build_defs/repo/jvm.bzl", line 92
lines.extend(_serialize_given_rule_import(nam...))
File "/home/davido/.cache/bazel/_bazel_davido/5c01f4f713b675540b8b424c5c647f63/external/bazel_tools/tools/build_defs/repo/jvm.bzl", line 92, in lines.extend
_serialize_given_rule_import(name = repository_ctx.attr.gener..., <7 more arguments>)
unexpected keyword 'additonal_rule_attrs' in call to _serialize_given_rule_import(rule_name, import_attr, name, path, srcpath, attrs, props, additional_rule_attrs) and referenced by '//plugins/javamelody:javamelody__plugin'
ERROR: Analysis of target '//plugins/javamelody:javamelody' failed; build aborted: no such package '@javamelody-core//': Traceback (most recent call last):
File "/home/davido/.cache/bazel/_bazel_davido/5c01f4f713b675540b8b424c5c647f63/external/bazel_tools/tools/build_defs/repo/jvm.bzl", line 92
lines.extend(_serialize_given_rule_import(nam...))
File "/home/davido/.cache/bazel/_bazel_davido/5c01f4f713b675540b8b424c5c647f63/external/bazel_tools/tools/build_defs/repo/jvm.bzl", line 92, in lines.extend
_serialize_given_rule_import(name = repository_ctx.attr.gener..., <7 more arguments>)
unexpected keyword 'additonal_rule_attrs' in call to _serialize_given_rule_import(rule_name, import_attr, name, path, srcpath, attrs, props, additional_rule_attrs)
INFO: Elapsed time: 0.379s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (16 packages loaded)
```
Workaround is to use `extra_build_file_content` attribute instead:
```
java_import_external(
name = "javamelody-core",
jar_sha256 = "eb2806497676da54e257840626b64e8e53121fe2f3599457f7748e381918b2c1",
jar_urls = [
"https://github.com/davido/javamelody/releases/download/javamelody-core-1.73.2/javamelody-core-1.73.2.jar",
],
licenses = ["notice"],
neverlink = True,
# This should just work
#generated_linkable_rule_name = "linkable-javamelody-core",
extra_build_file_content = "\n".join([
"java_import(",
" name = \"linkable-javamelody-core\",",
" jars = [\"javamelody-core-1.73.2.jar\"],",
")",
]),
)
```
Related discussion on the mailing list: [1].
[1] https://groups.google.com/d/topic/bazel-discuss/PvssQ709iGw/discussion | [
"tools/build_defs/repo/jvm.bzl"
] | [
"tools/build_defs/repo/jvm.bzl"
] | [] | diff --git a/tools/build_defs/repo/jvm.bzl b/tools/build_defs/repo/jvm.bzl
index 1538ea1b7e892d..dfa17f4692b176 100644
--- a/tools/build_defs/repo/jvm.bzl
+++ b/tools/build_defs/repo/jvm.bzl
@@ -91,7 +91,7 @@ def _jvm_import_external(repository_ctx):
repository_ctx.attr.generated_linkable_rule_name):
lines.extend(_serialize_given_rule_import(
name = repository_ctx.attr.generated_linkable_rule_name,
- additonal_rule_attrs = repository_ctx.attr.additional_rule_attrs,
+ additional_rule_attrs = repository_ctx.attr.additional_rule_attrs,
attrs = repository_ctx.attr,
import_attr = repository_ctx.attr.rule_metadata["import_attr"],
path = path,
| null | val | train | 2018-08-11T08:38:44 | "2018-08-11T10:53:48Z" | davido | test |
bazelbuild/bazel/5914_5969 | bazelbuild/bazel | bazelbuild/bazel/5914 | bazelbuild/bazel/5969 | [
"timestamp(timedelta=1.0, similarity=0.8811939021390516)"
] | 56fd4fe5a955d99f7467003fd399228ea87270ac | 31a70e20a3ec2c749d87a18dd3655023eb0588c7 | [
"Suggestion: enforce that Identifiers are either\r\n * `lower_snake_case`,\r\n * `UPPER_SNAKE_CASE`, or\r\n * `UpperCamelCaseWithSuffixInfo`"
] | [
"Someone told me the message could be improved:\r\n\r\n> I think this is confusing, made me think of \"information about a suffix\", not of the literal suffix \"Info\".\r\n> How about \"UpperCamelCase and end in \\\"Info\\\" (for providers; example: FooBarInfo)\" ?"
] | "2018-08-23T13:16:37Z" | [
"type: bug",
"P2"
] | Skylint should allow UpperCamelCase identifiers for provider aliases | Currently identifiers are only allowed to be `lower_snake_case` or `UPPER_SNAKE_CASE` in most cases, and also allowed to be `UpperCamelCase` if they are being [declared as a provider](https://github.com/bazelbuild/bazel/blob/901cc6c7474e2a6cc8c3812d156177f44dcb76ed/src/tools/skylark/java/com/google/devtools/skylark/skylint/NamingConventionsChecker.java#L37). This does not allow provider aliases to also be `UpperCamelCase`.
This issue came up in [this PR](https://github.com/angular/angular/pull/25256) to the angular repository. Skylint fails on [line 25](https://github.com/angular/angular/pull/25256/commits/763787afb27e8204b27b81a4e3c6c3dc6b0050b3#diff-c698d0f2da7b832a7e85568294e6653eR25) of `rules_typescript.bzl` with the following error.
```
./packages/bazel/src/rules_typescript.bzl:25:1-25:12: identifier 'TsConfigInfo' should be lower_snake_case (for variables) or UPPER_SNAKE_CASE (for constants) [name-with-wrong-case]
```
Possible solutions:
1. Always allow identifiers to be `UpperCamelCase`
2. Allow identifiers to be `UpperCamelCase` if the right side of the assignment also appears to be `UpperCamelCase`-ish.
| [
"site/docs/skylark/skylint.md",
"src/tools/skylark/java/com/google/devtools/skylark/skylint/NamingConventionsChecker.java",
"src/tools/skylark/javatests/com/google/devtools/skylark/skylint/NamingConventionsCheckerTest.java"
] | [
"site/docs/skylark/skylint.md",
"src/tools/skylark/java/com/google/devtools/skylark/skylint/NamingConventionsChecker.java",
"src/tools/skylark/javatests/com/google/devtools/skylark/skylint/NamingConventionsCheckerTest.java"
] | [] | diff --git a/site/docs/skylark/skylint.md b/site/docs/skylark/skylint.md
index 686ad5cd752cf9..14a282bf901e1c 100644
--- a/site/docs/skylark/skylint.md
+++ b/site/docs/skylark/skylint.md
@@ -188,9 +188,8 @@ In detail, the rules are the following:
* **Constants** that are **immutable**. The variable must not be rebound
and also its deep contents must not be changed.
* Use **`UpperCamelCase`** for:
- * **Providers**. Currently, the analyzer only allows assignments of the
- form `FooBarInfo = provider(...)`. In addition provider names have to
- end in the **suffix `Info`**.
+ * **Providers**. In addition, provider names have to end in the
+ **suffix `Info`**.
* **Never** use:
* **Builtin names** like `print`, `True`. Rebinding these is too
confusing.
diff --git a/src/tools/skylark/java/com/google/devtools/skylark/skylint/NamingConventionsChecker.java b/src/tools/skylark/java/com/google/devtools/skylark/skylint/NamingConventionsChecker.java
index cca66fc09668b8..3531d21cd24d0d 100644
--- a/src/tools/skylark/java/com/google/devtools/skylark/skylint/NamingConventionsChecker.java
+++ b/src/tools/skylark/java/com/google/devtools/skylark/skylint/NamingConventionsChecker.java
@@ -85,15 +85,16 @@ public void visit(AssignmentStatement node) {
super.visit(node);
}
- private void checkSnakeCase(String name, Location location) {
- if (!isSnakeCase(name)) {
+ private void checkIdentifier(String name, Location location) {
+ if (!isSnakeCase(name) && !(isUpperCamelCase(name) && name.endsWith("Info"))) {
issues.add(
Issue.create(
NAME_WITH_WRONG_CASE_CATEGORY,
"identifier '"
+ name
+ "' should be lower_snake_case (for variables)"
- + " or UPPER_SNAKE_CASE (for constants)",
+ + " or UPPER_SNAKE_CASE (for constants)"
+ + " or UpperCamelCase and end in \"Info\" (for providers; example: FizzBuzzInfo)",
location));
}
}
@@ -175,7 +176,7 @@ void declare(String name, ASTNode node) {
if (nameInfo.kind == Kind.PARAMETER || nameInfo.kind == Kind.FUNCTION) {
checkLowerSnakeCase(nameInfo.name, node.getLocation());
} else {
- checkSnakeCase(nameInfo.name, node.getLocation());
+ checkIdentifier(nameInfo.name, node.getLocation());
}
}
diff --git a/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/NamingConventionsCheckerTest.java b/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/NamingConventionsCheckerTest.java
index 325e7adc07688a..cec3a81965d54c 100644
--- a/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/NamingConventionsCheckerTest.java
+++ b/src/tools/skylark/javatests/com/google/devtools/skylark/skylint/NamingConventionsCheckerTest.java
@@ -40,13 +40,22 @@ public void testBadLetterCase() throws Exception {
String errorMessage =
findIssues(
"badGlobalVariableName = 0",
+ "BadProviderWithoutInfoSuffix = _BadProviderWithoutInfoSuffix",
"def BAD_FUNCTION_NAME(BadParameterName):",
" badLocalVariableName = 1")
.toString();
Truth.assertThat(errorMessage)
.contains(
"'badGlobalVariableName' should be lower_snake_case (for variables)"
- + " or UPPER_SNAKE_CASE (for constants) [name-with-wrong-case]");
+ + " or UPPER_SNAKE_CASE (for constants)"
+ + " or UpperCamelCase and end in \"Info\" (for providers; example: FizzBuzzInfo)"
+ + " [name-with-wrong-case]");
+ Truth.assertThat(errorMessage)
+ .contains(
+ "'BadProviderWithoutInfoSuffix' should be lower_snake_case (for variables)"
+ + " or UPPER_SNAKE_CASE (for constants)"
+ + " or UpperCamelCase and end in \"Info\" (for providers; example: FizzBuzzInfo)"
+ + " [name-with-wrong-case]");
Truth.assertThat(errorMessage)
.contains("'BAD_FUNCTION_NAME' should be lower_snake_case [name-with-wrong-case]");
Truth.assertThat(errorMessage)
@@ -54,7 +63,9 @@ public void testBadLetterCase() throws Exception {
Truth.assertThat(errorMessage)
.contains(
"'badLocalVariableName' should be lower_snake_case (for variables)"
- + " or UPPER_SNAKE_CASE (for constants) [name-with-wrong-case]");
+ + " or UPPER_SNAKE_CASE (for constants)"
+ + " or UpperCamelCase and end in \"Info\" (for providers; example: FizzBuzzInfo)"
+ + " [name-with-wrong-case]");
}
@Test
@@ -99,6 +110,7 @@ public void testNoIssues() throws Exception {
Truth.assertThat(
findIssues(
"GOOD_GLOBAL_VARIABLE_NAME = 0",
+ "GoodAliasedProviderInfo = _GoodAliasedProviderInfo",
"def good_function_name(good_parameter_name):",
" GOOD_LOCAL_CONSTANT_NAME = 1"))
.isEmpty();
| null | train | train | 2018-09-05T19:56:52 | "2018-08-16T17:51:37Z" | JaredNeil | test |
bazelbuild/bazel/5943_5999 | bazelbuild/bazel | bazelbuild/bazel/5943 | bazelbuild/bazel/5999 | [
"timestamp(timedelta=0.0, similarity=0.8711573184192934)"
] | 8d84a630c59047fd3953f5b6f444e4a75c324db2 | fcd15a73b59c5515687a27edef2e68bb0b58f468 | [
"We love contributions @Profpatsch :-)",
"> We love contributions @Profpatsch :-)\r\n\r\nI will open a pull request, do you have any preference on what the `perl` interpreter should replaced with? I think we can assume command line arguments will only use ASCII characters, is that correct?",
"I don't but @aehlig might",
"> perl -ne 'print uc'\n> \n> [...] As far as I understand this uppercases letters. It also introduces a hard dependency on perl to do bash completion. \n\nOh, wow. We're using perl, just to convert a string to upper case letters; and not even\nany string, as far as I can see this string is just used for commands and options---and those\nare, for sure, 7-bit clean prinable ASCII.\n\nIn the spirit of not introducing additional dependencies, I vote for the `tr a-z A-Z`\nsolution, as the script currently depends on `tr(1)` anyway.\n\n-- \nKlaus Aehlig\nGoogle Germany GmbH, Erika-Mann-Str. 33, 80636 Muenchen\nRegistergericht und -nummer: Hamburg, HRB 86891\nSitz der Gesellschaft: Hamburg\nGeschaeftsfuehrer: Paul Terence Manicle, Halimah DeLaine Prado\n"
] | [] | "2018-08-27T11:47:33Z" | [
"untriaged",
"team-Bazel"
] | bash completion requires perl | ### Description of the problem / feature request:
The bash completion uses a very small perl invocation in two places:
```
perl -ne 'print uc'
```
https://github.com/bazelbuild/bazel/blob/master/scripts/bazel-complete-template.bash#L151-L170
As far as I understand this uppercases letters. It also introduces a hard dependency on perl to do bash completion.
### Feature requests: what underlying problem are you trying to solve with this feature?
I’d like to get rid of the perl dependency, since it’s only used to uppercase letters.
There is multiple ways to uppercase letters, according to this stackoverflow question:
https://unix.stackexchange.com/questions/51983/how-to-uppercase-the-command-line-argument
You can use `awk`s `toupper`, which handles unicode correctly. `awk` is already used in the `zsh` completions and it has a considerably lower footprint than perl (2MB vs 50MB).
In this case it looks like it’s only used on bazel option names; if we can assume options will only use `[a-z]`, there is a `coreutils` solution: `tr a-z A-Z`.
An additional datapoint: this is the only place `perl` is used in the `scripts/` folder.
Update: A peer noted quite correctly, that Darwin `awk` might not have support for `toupper`, that would have to be investigated. | [
"scripts/bazel-complete-template.bash"
] | [
"scripts/bazel-complete-template.bash"
] | [] | diff --git a/scripts/bazel-complete-template.bash b/scripts/bazel-complete-template.bash
index d3f89bb6f86544..531e3296d85e6c 100644
--- a/scripts/bazel-complete-template.bash
+++ b/scripts/bazel-complete-template.bash
@@ -154,7 +154,8 @@ _bazel__package_path() {
_bazel__options_for() {
local options
if [[ "${BAZEL_COMMAND_LIST}" =~ ^(.* )?$1( .*)?$ ]]; then
- local option_name=$(echo $1 | perl -ne 'print uc' | tr "-" "_")
+ # assumes option names only use ASCII characters
+ local option_name=$(echo $1 | tr a-z A-Z | tr "-" "_")
eval "echo \${BAZEL_COMMAND_${option_name}_FLAGS}" | tr " " "\n"
fi
}
@@ -164,7 +165,8 @@ _bazel__options_for() {
_bazel__expansion_for() {
local options
if [[ "${BAZEL_COMMAND_LIST}" =~ ^(.* )?$1( .*)?$ ]]; then
- local option_name=$(echo $1 | perl -ne 'print uc' | tr "-" "_")
+ # assumes option names only use ASCII characters
+ local option_name=$(echo $1 | tr a-z A-Z | tr "-" "_")
eval "echo \${BAZEL_COMMAND_${option_name}_ARGUMENT}"
fi
}
| null | train | train | 2018-08-27T12:08:45 | "2018-08-21T11:32:32Z" | Profpatsch | test |
bazelbuild/bazel/5952_5953 | bazelbuild/bazel | bazelbuild/bazel/5952 | bazelbuild/bazel/5953 | [
"timestamp(timedelta=0.0, similarity=0.9003379059109604)"
] | c5a2f81ce8fc1dee4bcfa92cf3059a9c50bf2d85 | b274a9dc3a3812f6b4e1dc69909e523f1592bee4 | [
"I'm about to submit a pull request which fixes this issue.",
"Here's the pull request: https://github.com/bazelbuild/bazel/pull/5953"
] | [
"I think the changes in this file are no longer necessary and can be reverted?",
"I think we don't want to clear the pipeline but actually fail if there's anything in there.\r\nIt would be a bug in our code if the pipeline were not empty.",
"Good point, I'll revert this back since the exception handler should cover the race condition universally.",
"Okay, I've updated the two `acquire*Channel()` methods to check if the pipeline is not empty and fail the promise if so. The pipeline could be in a strange state if there are any handlers on a newly acquired channel, so you're right that failing probably makes sense there."
] | "2018-08-21T21:41:11Z" | [
"untriaged"
] | Race condition in HttpBlobStore.releaseUploadChannel | ### Description of the problem / feature request:
Builds can fail with `java.lang.RuntimeException: Unrecoverable error while evaluating node 'ActionLookupData{...}' ...
Caused by: java.util.NoSuchElementException: io.netty.handler.codec.http.HttpRequestEncoder` when using the HttpBlobStore to cache builds.
It appears a race condition can occur in HttpBlobStore.releaseUploadChannel() when ChannelHandlerContext is closed by HttpUploadHandler.channelRead0 (when not keeping connection alive). Because ChannelHandlerContext.close runs asynchronously and closes all pipelines in reverse order (before the channel is marked as closed), HttpBlobStore.releaseUploadChannel() can be executed while channel is still open and handlers are being removed, causing an exception to be thrown by the ch.pipeline().remove(X) calls.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
The issue is a race condition, so it is difficult to reproduce. Use a local HTTP cache that does not keep connections alive and `bazel clean` before starting a new build.
### What operating system are you running Bazel on?
Ubuntu 16.04
### What's the output of `bazel info release`?
release 0.16.0
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
N/A
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
https://github.com/bazelbuild/bazel.git
b942140053981c4da5b2101d5f3a608ac25e7829
3e0024b5771539e6dd860c93cd65a603a0986506
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
```
java.lang.RuntimeException: Unrecoverable error while evaluating node 'ActionLookupData{actionLookupKey=//foo-service:play-routes BuildConfigurationValue.Key[...] false, actionIndex=0}' (requested by nodes 'File:[[<execution_root>]bazel-out/k8-fastbuild/bin]foo-service/play/routes/play_routes')
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:482)
at com.google.devtools.build.lib.concurrent.AbstractQueueVisitor$WrappedRunnable.run(AbstractQueueVisitor.java:335)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.util.NoSuchElementException: io.netty.handler.codec.http.HttpRequestEncoder
at io.netty.channel.DefaultChannelPipeline.getContextOrDie(DefaultChannelPipeline.java:1107)
at io.netty.channel.DefaultChannelPipeline.remove(DefaultChannelPipeline.java:449)
at com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.releaseUploadChannel(HttpBlobStore.java:252)
at com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.put(HttpBlobStore.java:468)
at com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.put(HttpBlobStore.java:426)
at com.google.devtools.build.lib.remote.SimpleBlobStoreActionCache.uploadStream(SimpleBlobStoreActionCache.java:183)
at com.google.devtools.build.lib.remote.SimpleBlobStoreActionCache.upload(SimpleBlobStoreActionCache.java:148)
at com.google.devtools.build.lib.remote.SimpleBlobStoreActionCache.upload(SimpleBlobStoreActionCache.java:126)
at com.google.devtools.build.lib.remote.RemoteSpawnCache$1.store(RemoteSpawnCache.java:186)
at com.google.devtools.build.lib.exec.AbstractSpawnStrategy.exec(AbstractSpawnStrategy.java:109)
at com.google.devtools.build.lib.exec.AbstractSpawnStrategy.exec(AbstractSpawnStrategy.java:75)
at com.google.devtools.build.lib.exec.SpawnActionContextMaps$ProxySpawnActionContext.exec(SpawnActionContextMaps.java:362)
at com.google.devtools.build.lib.analysis.actions.SpawnAction.internalExecute(SpawnAction.java:287)
at com.google.devtools.build.lib.analysis.actions.SpawnAction.execute(SpawnAction.java:294)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.executeActionTask(SkyframeActionExecutor.java:992)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.prepareScheduleExecuteAndCompleteAction(SkyframeActionExecutor.java:924)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.access$900(SkyframeActionExecutor.java:119)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.call(SkyframeActionExecutor.java:768)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor$ActionRunner.call(SkyframeActionExecutor.java:723)
at java.base/java.util.concurrent.FutureTask.run(Unknown Source)
at com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.executeAction(SkyframeActionExecutor.java:461)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.checkCacheAndExecuteIfNeeded(ActionExecutionFunction.java:512)
at com.google.devtools.build.lib.skyframe.ActionExecutionFunction.compute(ActionExecutionFunction.java:227)
at com.google.devtools.build.skyframe.AbstractParallelEvaluator$Evaluate.run(AbstractParallelEvaluator.java:405)
FAILED: Build did NOT complete successfully``` | [
"src/main/java/com/google/devtools/build/lib/remote/blobstore/http/HttpBlobStore.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/blobstore/http/HttpBlobStore.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/blobstore/http/HttpBlobStore.java b/src/main/java/com/google/devtools/build/lib/remote/blobstore/http/HttpBlobStore.java
index ca9a8ebff47012..a3d363616b8108 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/blobstore/http/HttpBlobStore.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/blobstore/http/HttpBlobStore.java
@@ -65,6 +65,7 @@
import java.net.SocketAddress;
import java.net.URI;
import java.util.List;
+import java.util.NoSuchElementException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -99,7 +100,6 @@
* <p>The implementation currently does not support transfer encoding chunked.
*/
public final class HttpBlobStore implements SimpleBlobStore {
-
private static final Pattern INVALID_TOKEN_ERROR =
Pattern.compile("\\s*error\\s*=\\s*\"?invalid_token\"?");
@@ -107,6 +107,7 @@ public final class HttpBlobStore implements SimpleBlobStore {
private final ChannelPool channelPool;
private final URI uri;
private final int timeoutMillis;
+ private final boolean useTls;
private final Object closeLock = new Object();
@@ -159,7 +160,7 @@ private HttpBlobStore(
URI uri, int timeoutMillis, int remoteMaxConnections, @Nullable final Credentials creds,
@Nullable SocketAddress socketAddress)
throws Exception {
- boolean useTls = uri.getScheme().equals("https");
+ useTls = uri.getScheme().equals("https");
if (uri.getPort() == -1) {
int port = useTls ? 443 : 80;
uri =
@@ -237,6 +238,12 @@ private Channel acquireUploadChannel() throws InterruptedException {
try {
Channel ch = channelAcquired.getNow();
ChannelPipeline p = ch.pipeline();
+
+ if (!isChannelPipelineEmpty(p)) {
+ channelReady.setFailure(new IllegalStateException("Channel pipeline is not empty."));
+ return;
+ }
+
p.addLast(new HttpResponseDecoder());
// The 10KiB limit was chosen at random. We only expect HTTP servers to respond with
// an error message in the body and that should always be less than 10KiB.
@@ -264,11 +271,18 @@ private Channel acquireUploadChannel() throws InterruptedException {
@SuppressWarnings("FutureReturnValueIgnored")
private void releaseUploadChannel(Channel ch) {
if (ch.isOpen()) {
- ch.pipeline().remove(HttpResponseDecoder.class);
- ch.pipeline().remove(HttpObjectAggregator.class);
- ch.pipeline().remove(HttpRequestEncoder.class);
- ch.pipeline().remove(ChunkedWriteHandler.class);
- ch.pipeline().remove(HttpUploadHandler.class);
+ try {
+ ch.pipeline().remove(HttpResponseDecoder.class);
+ ch.pipeline().remove(HttpObjectAggregator.class);
+ ch.pipeline().remove(HttpRequestEncoder.class);
+ ch.pipeline().remove(ChunkedWriteHandler.class);
+ ch.pipeline().remove(HttpUploadHandler.class);
+ } catch (NoSuchElementException e) {
+ // If the channel is in the process of closing but not yet closed, some handlers could have
+ // been removed and would cause NoSuchElement exceptions to be thrown. Because handlers are
+ // removed in reverse-order, if we get a NoSuchElement exception, the following handlers
+ // should have been removed.
+ }
}
channelPool.release(ch);
}
@@ -288,6 +302,12 @@ private Future<Channel> acquireDownloadChannel() {
try {
Channel ch = channelAcquired.getNow();
ChannelPipeline p = ch.pipeline();
+
+ if (!isChannelPipelineEmpty(p)) {
+ channelReady.setFailure(new IllegalStateException("Channel pipeline is not empty."));
+ return;
+ }
+
ch.pipeline()
.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
p.addLast(new HttpClientCodec());
@@ -309,13 +329,24 @@ private void releaseDownloadChannel(Channel ch) {
if (ch.isOpen()) {
// The channel might have been closed due to an error, in which case its pipeline
// has already been cleared. Closed channels can't be reused.
- ch.pipeline().remove(ReadTimeoutHandler.class);
- ch.pipeline().remove(HttpClientCodec.class);
- ch.pipeline().remove(HttpDownloadHandler.class);
+ try {
+ ch.pipeline().remove(ReadTimeoutHandler.class);
+ ch.pipeline().remove(HttpClientCodec.class);
+ ch.pipeline().remove(HttpDownloadHandler.class);
+ } catch (NoSuchElementException e) {
+ // If the channel is in the process of closing but not yet closed, some handlers could have
+ // been removed and would cause NoSuchElement exceptions to be thrown. Because handlers are
+ // removed in reverse-order, if we get a NoSuchElement exception, the following handlers
+ // should have been removed.
+ }
}
channelPool.release(ch);
}
+ private boolean isChannelPipelineEmpty(ChannelPipeline pipeline) {
+ return (pipeline.first() == null) || (useTls && pipeline.firstContext().name() == "ssl-handler" && pipeline.first() == pipeline.last());
+ }
+
@Override
public boolean containsKey(String key) {
throw new UnsupportedOperationException("HTTP Caching does not use this method.");
| null | train | train | 2018-08-21T23:12:24 | "2018-08-21T21:38:04Z" | geoffmaddox | test |
bazelbuild/bazel/6019_6024 | bazelbuild/bazel | bazelbuild/bazel/6019 | bazelbuild/bazel/6024 | [
"timestamp(timedelta=102305.0, similarity=0.9405752619525384)"
] | 206c19bf4cf8e9a3bc33289fe071700fcac1e2c6 | eb1695979c7b0c69a783138790e18a8f625bbeb5 | [
"We already have an issue here: https://github.com/bazelbuild/bazel/issues/5807\r\nClosing this one due to duplication."
] | [
"Have you thought of using a `typedef`? I think that'd be more type-safe and more readable than a macro.",
"Have you thought of using an unnamed namespace? That restricts visibility and the binary will not export these symbols.\r\n\r\n(See https://google.github.io/styleguide/cppguide.html#Unnamed_Namespaces_and_Static_Variables)",
"What's the reason for using `explicit`?",
"The error message is confusing, \"INPUT RUNFILES\" can be understood as \"a list of input runfiles\". What's the intended meaning? Could you clarify the message?",
"I think the argument type does not need to be a const reference. Can you think of a more efficient approach?",
"What does the rest of the loop do when `use_metadata` is false?",
"What's the reason to store an entry when `target` is empty?",
"Is this call necessary? Doesn't `ifstream`'s destructor close the file?",
"String comparison should ignore casing.",
"This call fails if the directory is not empty. Is that expected?",
"Why can we ignore it?",
"Have you considered using a foreach-loop?",
"`CreateFileW` returns `INVALID_HANDLE_VALUE` on error. Please compare `h` to that instead of to `0`.",
"type-safety: use `FALSE` `FALSE` (BOOL) instead of `false` (bool).",
"Do you need to do this before every test, or would it suffice to export these envvars just once?",
"Why is there one more symlink on Windows?",
"You are calling `readlink $i` multiple times. Could you cache its result?",
"why is there one more symlink on Windows?",
"same here about `readlink $i`",
"Good idea. Replaced it with typedef and moved it into the class definition.",
"Good to know that, thanks!",
"Done",
"I copied from the Linux version build-runfiles.cc, but I think it's unnecessary, so removed.",
"If `use_metadata` is false, it means every line in the manifest is a runfile entry, then the loop will read each of them and add them in the manifest map. If `use_metadata` is true, it will skip all lines with even line number, because they are metadata lines.\r\nSee https://github.com/bazelbuild/bazel/blob/master/src/main/tools/build-runfiles.cc#L144",
"Bazel sometimes need to create empty files under the runfiles tree. For example, for python binary, `__init__.py` is needed under every directory. Storing an entry with an empty `target` indicates we need to create such a file when creating the runfiles tree.",
"Indeed, removed.",
"`AsAbsoluteWindowsPath` will convert the path to a normalized path, than means both of them are already in lower case.",
"Here we are deleting a symlink, so it won't fail even the target directory is not empty.",
"Because if the directory is not empty, it means it contains some symlinks already pointing to the correct targets (we just called `ScanTreeAndPrune`). Then this directory shouldn't be removed in the first place. It's better to check if the directory is empty before deleting it, but there's not simple kernel API for that.",
"Good idea! Done.",
"Done.",
"Done",
"Indeed, it's confusing. Updated.",
"Right, once is enough.",
"Because for shell binary, we build both `bin` and `bin.exe`, but on Linux we only build `bin`",
"Yes, done.",
"Answered in above comment.",
"Done.",
"Thanks. Please add this as a code comment.",
"Thanks! Could you add this explanation to the code?",
"Thanks! The convention in manpages is to put mandatory arguments in angle brackets, e.g. `<manifest_file>`. I think doing that here would increase readability.",
"The name `use_metadata` confuses me, it suggests that the function should use (or ignore) the metadata. WDYT? If you agree, can you think of a better name?",
"Could you add this as a comment?",
"Could you add this to the code as a comment?",
"Thanks, please add it as a comment here too.",
"Indeed, `ignore_metadata` is better.",
"Just realized `use_metadata` is also the flag name and used some other places in Java code. Let me instead add a comment here to clarify.",
"Done.",
"Done",
"Done!",
"Done",
"Done"
] | "2018-08-29T16:14:45Z" | [
"type: feature request",
"P2",
"platform: windows",
"area-Windows",
"team-OSS"
] | Implement build-runfiles on Windows | On Windows, runfiles tree is disabled because creating symlink needs admin right or Windows 10 Creator Update (or later) and developer is enabled. But Bazel should be able to build runfiles tree if users can ensure one of those requirements.
Enabling runfiles tree on Windows would help resolve https://github.com/bazelbuild/bazel/issues/5926
/cc @laszlocsomor @dslomov | [
"src/main/cpp/util/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java",
"src/main/tools/BUILD",
"src/main/tools/build-runfiles-windows.cc"
] | [
"src/main/cpp/util/BUILD",
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java",
"src/main/tools/BUILD",
"src/main/tools/build-runfiles-windows.cc"
] | [
"src/test/py/bazel/runfiles_test.py",
"src/test/shell/integration/BUILD",
"src/test/shell/integration/runfiles_test.sh"
] | diff --git a/src/main/cpp/util/BUILD b/src/main/cpp/util/BUILD
index 9df4e558d8f472..bc799aba338af7 100644
--- a/src/main/cpp/util/BUILD
+++ b/src/main/cpp/util/BUILD
@@ -55,6 +55,7 @@ cc_library(
visibility = [
":ijar",
"//src/test/cpp/util:__pkg__",
+ "//src/main/tools:__pkg__",
"//src/tools/launcher:__subpackages__",
"//src/tools/singlejar:__pkg__",
"//third_party/def_parser:__pkg__",
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
index 7590d6aa696d28..2b58187dd7005d 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
@@ -1167,10 +1167,6 @@ public void reportInvalidOptions(EventHandler reporter) {
fragment.reportInvalidOptions(reporter, this.buildOptions);
}
- if (OS.getCurrent() == OS.WINDOWS && runfilesEnabled()) {
- reporter.handle(Event.error("building runfiles is not supported on Windows"));
- }
-
if (options.outputDirectoryName != null) {
reporter.handle(Event.error(
"The internal '--output directory name' option cannot be used on the command line"));
diff --git a/src/main/tools/BUILD b/src/main/tools/BUILD
index e67d67baaa6953..8362c0c0b6dd22 100644
--- a/src/main/tools/BUILD
+++ b/src/main/tools/BUILD
@@ -48,6 +48,7 @@ cc_binary(
"//src/conditions:windows": ["build-runfiles-windows.cc"],
"//conditions:default": ["build-runfiles.cc"],
}),
+ deps = ["//src/main/cpp/util:filesystem"],
)
cc_binary(
diff --git a/src/main/tools/build-runfiles-windows.cc b/src/main/tools/build-runfiles-windows.cc
index ea4eed189aab26..db01284e0c2635 100644
--- a/src/main/tools/build-runfiles-windows.cc
+++ b/src/main/tools/build-runfiles-windows.cc
@@ -12,16 +12,399 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+#include <windows.h>
#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <string.h>
+#include <unordered_map>
-int main(int argc, char** argv) {
- // TODO(bazel-team): decide whether we need build-runfiles at all on Windows.
- // Implement this program if so; make sure we don't run it on Windows if not.
- std::cout << "ERROR: build-runfiles is not (yet?) implemented on Windows."
- << std::endl
- << "Called with args:" << std::endl;
- for (int i = 0; i < argc; ++i) {
- std::cout << "argv[" << i << "]=(" << argv[i] << ")" << std::endl;
+#include "src/main/cpp/util/path_platform.h"
+#include "src/main/cpp/util/file_platform.h"
+#include "src/main/cpp/util/strings.h"
+
+using std::ifstream;
+using std::unordered_map;
+using std::string;
+using std::wstring;
+using std::stringstream;
+
+#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
+#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 0x2
+#endif
+
+#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
+#define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
+#endif
+
+namespace {
+
+const wchar_t *manifest_filename;
+const wchar_t *runfiles_base_dir;
+
+string GetLastErrorString() {
+ DWORD last_error = GetLastError();
+ if (last_error == 0) {
+ return string();
+ }
+
+ char* message_buffer;
+ size_t size = FormatMessageA(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPSTR)&message_buffer, 0, NULL);
+
+ stringstream result;
+ result << "(error: " << last_error << "): " << message_buffer;
+ LocalFree(message_buffer);
+ return result.str();
+}
+
+void die(const wchar_t* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ fputws(L"build-runfiles error: ", stderr);
+ vfwprintf(stderr, format, ap);
+ va_end(ap);
+ fputwc(L'\n', stderr);
+ fputws(L"manifest file name: ", stderr);
+ fputws(manifest_filename, stderr);
+ fputwc(L'\n', stderr);
+ fputws(L"runfiles base directory: ", stderr);
+ fputws(runfiles_base_dir, stderr);
+ fputwc(L'\n', stderr);
+ exit(1);
+}
+
+wstring AsAbsoluteWindowsPath(const wchar_t* path) {
+ wstring wpath;
+ string error;
+ if (!blaze_util::AsAbsoluteWindowsPath(path, &wpath, &error)) {
+ die(L"Couldn't convert %s to absolute Windows path: %hs", path,
+ error.c_str());
+ }
+ return wpath;
+}
+
+bool DoesDirectoryPathExist(const wchar_t* path) {
+ DWORD dwAttrib = GetFileAttributesW(AsAbsoluteWindowsPath(path).c_str());
+
+ return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
+ (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
+}
+
+wstring GetParentDirFromPath(const wstring& path) {
+ return path.substr(0, path.find_last_of(L"\\/"));
+}
+
+inline void Trim(wstring& str){
+ str.erase(0, str.find_first_not_of(' '));
+ str.erase(str.find_last_not_of(' ') + 1);
+}
+
+} // namespace
+
+class RunfilesCreator {
+ typedef std::unordered_map<std::wstring, std::wstring> ManifestFileMap;
+
+ public:
+ RunfilesCreator(const wstring &manifest_path,
+ const wstring &runfiles_output_base)
+ : manifest_path_(manifest_path),
+ runfiles_output_base_(runfiles_output_base) {
+ SetupOutputBase();
+ if (!SetCurrentDirectoryW(runfiles_output_base_.c_str())) {
+ die(L"SetCurrentDirectoryW failed (%s): %hs",
+ runfiles_output_base_.c_str(), GetLastErrorString().c_str());
+ }
+ }
+
+ void ReadManifest(bool allow_relative, bool ignore_metadata) {
+ ifstream manifest_file(
+ AsAbsoluteWindowsPath(manifest_path_.c_str()).c_str());
+
+ if (!manifest_file) {
+ die(L"Couldn't open MANIFEST file: %s", manifest_path_.c_str());
+ }
+
+ string line;
+ int lineno = 0;
+ while (getline(manifest_file, line)) {
+ lineno++;
+ // Skip metadata lines. They are used solely for
+ // dependency checking.
+ if (ignore_metadata && lineno % 2 == 0) {
+ continue;
+ }
+
+ size_t space_pos = line.find_first_of(' ');
+ wstring wline = blaze_util::CstringToWstring(line);
+ wstring link, target;
+ if (space_pos == string::npos) {
+ link = wline;
+ target = wstring();
+ } else {
+ link = wline.substr(0, space_pos);
+ target = wline.substr(space_pos + 1);
+ }
+
+ // Removing leading and trailing spaces
+ Trim(link);
+ Trim(target);
+
+
+ // We sometimes need to create empty files under the runfiles tree.
+ // For example, for python binary, __init__.py is needed under every directory.
+ // Storing an entry with an empty target indicates we need to create such a
+ // file when creating the runfiles tree.
+ if (!allow_relative && !target.empty()
+ && !blaze_util::IsAbsolute(target)) {
+ die(L"Target cannot be relative path: %hs", line.c_str());
+ }
+
+ link = AsAbsoluteWindowsPath(link.c_str());
+
+ manifest_file_map.insert(make_pair(link, target));
+ }
+ }
+
+ void CreateRunfiles() {
+ bool symlink_needs_privilege =
+ DoesCreatingSymlinkNeedAdminPrivilege(runfiles_output_base_);
+ ScanTreeAndPrune(runfiles_output_base_);
+ CreateFiles(symlink_needs_privilege);
+ CopyManifestFile();
}
- return 1;
+
+ private:
+ void SetupOutputBase() {
+ if (!DoesDirectoryPathExist(runfiles_output_base_.c_str())) {
+ MakeDirectoriesOrDie(runfiles_output_base_);
+ }
+ }
+
+ void MakeDirectoriesOrDie(const wstring& path) {
+ if (!blaze_util::MakeDirectoriesW(path, 0755)) {
+ die(L"MakeDirectoriesW failed (%s): %hs",
+ path.c_str(), GetLastErrorString().c_str());
+ }
+ }
+
+ void RemoveDirectoryOrDie(const wstring& path) {
+ if (!RemoveDirectoryW(path.c_str())) {
+ die(L"RemoveDirectoryW failed (%s): %hs", GetLastErrorString().c_str());
+ }
+ }
+
+ void DeleteFileOrDie(const wstring& path) {
+ SetFileAttributesW(path.c_str(),
+ GetFileAttributesW(path.c_str()) & ~FILE_ATTRIBUTE_READONLY);
+ if (!DeleteFileW(path.c_str())) {
+ die(L"DeleteFileW failed (%s): %hs",
+ path.c_str(), GetLastErrorString().c_str());
+ }
+ }
+
+ bool DoesCreatingSymlinkNeedAdminPrivilege(const wstring& runfiles_base_dir) {
+ wstring dummy_link = runfiles_base_dir + L"\\dummy_link";
+ wstring dummy_target = runfiles_base_dir + L"\\dummy_target";
+
+ // Try creating symlink without admin privilege.
+ if (CreateSymbolicLinkW(dummy_link.c_str(), dummy_target.c_str(),
+ SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
+ DeleteFileOrDie(dummy_link);
+ return false;
+ }
+
+ // Try creating symlink with admin privilege
+ if (CreateSymbolicLinkW(dummy_link.c_str(), dummy_target.c_str(), 0)) {
+ DeleteFileOrDie(dummy_link);
+ return true;
+ }
+
+ // If we couldn't create symlink, print out an error message and exit.
+ if (GetLastError() == ERROR_PRIVILEGE_NOT_HELD) {
+ die(L"CreateSymbolicLinkW failed:\n%hs\n",
+ "Bazel needs to create symlink for building runfiles tree.\n"
+ "Creating symlink on Windows requires either of the following:\n"
+ " 1. Program is running with elevated privileges (Admin rights).\n"
+ " 2. The system version is Windows 10 Creators Update (1703) or later and "
+ "developer mode is enabled.",
+ GetLastErrorString().c_str());
+ } else {
+ die(L"CreateSymbolicLinkW failed: %hs", GetLastErrorString().c_str());
+ }
+
+ return true;
+ }
+
+ // This function scan the current directory, remove all files/symlinks/directories that
+ // are not presented in manifest file.
+ // If a symlink already exists and points to the correct target, this function erases
+ // its entry from manifest_file_map, so that we won't recreate it.
+ void ScanTreeAndPrune(const wstring& path) {
+ static const wstring kDot(L".");
+ static const wstring kDotDot(L"..");
+
+ WIN32_FIND_DATAW metadata;
+ HANDLE handle = ::FindFirstFileW((path + L"\\*").c_str(), &metadata);
+ if (handle == INVALID_HANDLE_VALUE) {
+ return; // directory does not exist or is empty
+ }
+
+ do {
+ if (kDot != metadata.cFileName && kDotDot != metadata.cFileName) {
+ wstring subpath = path + L"\\" + metadata.cFileName;
+ bool is_dir =
+ (metadata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
+ bool is_symlink =
+ (metadata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
+ if (is_symlink) {
+ wstring target;
+ if (!blaze_util::ReadSymlinkW(subpath, &target)) {
+ die(L"ReadSymlinkW failed (%s): %hs",
+ subpath.c_str(), GetLastErrorString().c_str());
+ };
+
+ subpath = AsAbsoluteWindowsPath(subpath.c_str());
+ target = AsAbsoluteWindowsPath(target.c_str());
+ ManifestFileMap::iterator expected_target =
+ manifest_file_map.find(subpath);
+
+ if (expected_target == manifest_file_map.end()
+ || expected_target->second.empty()
+ // Both paths are normalized paths in lower case, we can compare them directly.
+ || target != AsAbsoluteWindowsPath(expected_target->second.c_str())
+ || blaze_util::IsDirectoryW(target) != is_dir) {
+ if (is_dir) {
+ RemoveDirectoryOrDie(subpath);
+ } else {
+ DeleteFileOrDie(subpath);
+ }
+ } else {
+ manifest_file_map.erase(expected_target);
+ }
+ } else {
+ if (is_dir) {
+ ScanTreeAndPrune(subpath);
+ // If the directory is empty, then we remove the directory.
+ // Otherwise RemoveDirectory will fail with ERROR_DIR_NOT_EMPTY,
+ // which we can just ignore.
+ // Because if the directory is not empty, it means it contains some symlinks
+ // already pointing to the correct targets (we just called ScanTreeAndPrune).
+ // Then this directory shouldn't be removed in the first place.
+ if (!RemoveDirectoryW(subpath.c_str())
+ && GetLastError() != ERROR_DIR_NOT_EMPTY) {
+ die(L"RemoveDirectoryW failed (%s): %hs",
+ subpath.c_str(), GetLastErrorString().c_str());
+ }
+ } else {
+ DeleteFileOrDie(subpath);
+ }
+ }
+ }
+ } while (::FindNextFileW(handle, &metadata));
+ ::FindClose(handle);
+ }
+
+ void CreateFiles(bool creating_symlink_needs_admin_privilege) {
+ DWORD privilege_flag = creating_symlink_needs_admin_privilege
+ ? 0
+ : SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
+
+ for (const auto &it : manifest_file_map) {
+ // Ensure the parent directory exists
+ wstring parent_dir = GetParentDirFromPath(it.first);
+ if (!DoesDirectoryPathExist(parent_dir.c_str())) {
+ MakeDirectoriesOrDie(parent_dir);
+ }
+
+ if (it.second.empty()) {
+ // Create an empty file
+ HANDLE h = CreateFileW(it.first.c_str(), // name of the file
+ GENERIC_WRITE, // open for writing
+ 0, // sharing mode, none in this case
+ 0, // use default security descriptor
+ CREATE_ALWAYS, // overwrite if exists
+ FILE_ATTRIBUTE_NORMAL,
+ 0);
+ if (h != INVALID_HANDLE_VALUE) {
+ CloseHandle(h);
+ } else {
+ die(L"CreateFileW failed (%s): %hs",
+ it.first.c_str(), GetLastErrorString().c_str());
+ }
+ } else {
+ DWORD create_dir = 0;
+ if (blaze_util::IsDirectoryW(it.second.c_str())) {
+ create_dir = SYMBOLIC_LINK_FLAG_DIRECTORY;
+ }
+ if (!CreateSymbolicLinkW(it.first.c_str(),
+ it.second.c_str(),
+ privilege_flag | create_dir)) {
+ die(L"CreateSymbolicLinkW failed (%s -> %s): %hs",
+ it.first.c_str(), it.second.c_str(),
+ GetLastErrorString().c_str());
+ }
+ }
+ }
+ }
+
+ void CopyManifestFile() {
+ wstring new_manifest_file = runfiles_output_base_ + L"\\MANIFEST";
+ if (!CopyFileW(manifest_path_.c_str(),
+ new_manifest_file.c_str(),
+ /*bFailIfExists=*/ FALSE
+ )) {
+ die(L"CopyFileW failed (%s -> %s): %hs",
+ manifest_path_.c_str(), new_manifest_file.c_str(),
+ GetLastErrorString().c_str());
+ }
+ }
+
+ private:
+ wstring manifest_path_;
+ wstring runfiles_output_base_;
+ ManifestFileMap manifest_file_map;
+};
+
+int wmain(int argc, wchar_t** argv) {
+ argc--; argv++;
+ bool allow_relative = false;
+ bool ignore_metadata = false;
+
+ while (argc >= 1) {
+ if (wcscmp(argv[0], L"--allow_relative") == 0) {
+ allow_relative = true;
+ argc--; argv++;
+ } else if (wcscmp(argv[0], L"--use_metadata") == 0) {
+ // If --use_metadata is passed, it means manifest file contains metadata lines,
+ // which we should ignore when reading manifest file.
+ ignore_metadata = true;
+ argc--; argv++;
+ } else {
+ break;
+ }
+ }
+
+ if (argc != 2) {
+ fprintf(stderr, "usage: [--allow_relative] [--use_metadata] "
+ "<manifest_file> <runfiles_base_dir>\n");
+ return 1;
+ }
+
+ manifest_filename = argv[0];
+ runfiles_base_dir = argv[1];
+
+ wstring manifest_absolute_path = AsAbsoluteWindowsPath(manifest_filename);
+ wstring output_base_absolute_path = AsAbsoluteWindowsPath(runfiles_base_dir);
+
+ RunfilesCreator runfiles_creator(manifest_absolute_path,
+ output_base_absolute_path);
+ runfiles_creator.ReadManifest(allow_relative, ignore_metadata);
+ runfiles_creator.CreateRunfiles();
+
+ return 0;
}
| diff --git a/src/test/py/bazel/runfiles_test.py b/src/test/py/bazel/runfiles_test.py
index 50506f63918e8a..36aba0d7678642 100644
--- a/src/test/py/bazel/runfiles_test.py
+++ b/src/test/py/bazel/runfiles_test.py
@@ -21,16 +21,6 @@
class RunfilesTest(test_base.TestBase):
- def testAttemptToBuildRunfilesOnWindows(self):
- if not self.IsWindows():
- self.skipTest("only applicable to Windows")
- self.ScratchFile("WORKSPACE")
- exit_code, _, stderr = self.RunBazel(
- ["build", "--experimental_enable_runfiles"])
- self.assertNotEqual(exit_code, 0)
- self.assertIn("building runfiles is not supported on Windows",
- "\n".join(stderr))
-
def _AssertRunfilesLibraryInBazelToolsRepo(self, family, lang_name):
for s, t, exe in [("WORKSPACE.mock", "WORKSPACE",
False), ("foo/BUILD.mock", "foo/BUILD",
diff --git a/src/test/shell/integration/BUILD b/src/test/shell/integration/BUILD
index 5501058918bb29..efdde9ec93af03 100644
--- a/src/test/shell/integration/BUILD
+++ b/src/test/shell/integration/BUILD
@@ -29,11 +29,12 @@ sh_test(
name = "runfiles_test",
size = "medium",
srcs = ["runfiles_test.sh"],
- data = [":test-deps"],
+ data = [
+ ":test-deps",
+ "@bazel_tools//tools/bash/runfiles",
+ ],
tags = [
"local",
- # no_windows: this test exercises the symlink-based runfiles tree.
- "no_windows",
],
)
diff --git a/src/test/shell/integration/runfiles_test.sh b/src/test/shell/integration/runfiles_test.sh
index cb2e88627e0438..fd85be9849fd82 100755
--- a/src/test/shell/integration/runfiles_test.sh
+++ b/src/test/shell/integration/runfiles_test.sh
@@ -16,18 +16,59 @@
#
# An end-to-end test that Bazel produces runfiles trees as expected.
-# Load the test setup defined in the parent directory
-CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-source "${CURRENT_DIR}/../integration_test_setup.sh" \
+# --- begin runfiles.bash initialization ---
+# Copy-pasted from Bazel's Bash runfiles library (tools/bash/runfiles/runfiles.bash).
+set -euo pipefail
+if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ if [[ -f "$0.runfiles_manifest" ]]; then
+ export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
+ elif [[ -f "$0.runfiles/MANIFEST" ]]; then
+ export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
+ elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
+ export RUNFILES_DIR="$0.runfiles"
+ fi
+fi
+if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
+ source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
+elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
+ "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)"
+else
+ echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"
+ exit 1
+fi
+# --- end runfiles.bash initialization ---
+
+source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
|| { echo "integration_test_setup.sh not found!" >&2; exit 1; }
+case "$(uname -s | tr [:upper:] [:lower:])" in
+msys*|mingw*|cygwin*)
+ declare -r is_windows=true
+ ;;
+*)
+ declare -r is_windows=false
+ ;;
+esac
+
+if "$is_windows"; then
+ export MSYS_NO_PATHCONV=1
+ export MSYS2_ARG_CONV_EXCL="*"
+ export EXT=".exe"
+ export EXTRA_BUILD_FLAGS="--experimental_enable_runfiles --build_python_zip=0"
+else
+ export EXT=""
+ export EXTRA_BUILD_FLAGS=""
+fi
+
#### SETUP #############################################################
set -e
-function set_up() {
- mkdir -p pkg
- cd pkg
+function create_pkg() {
+ local -r pkg=$1
+ mkdir -p $pkg
+ cd $pkg
mkdir -p a/b c/d e/f/g x/y
touch py.py a/b/no_module.py c/d/one_module.py c/__init__.py e/f/g/ignored.py x/y/z.sh
@@ -40,7 +81,9 @@ function set_up() {
#### TESTS #############################################################
function test_hidden() {
- cat > pkg/BUILD << EOF
+ local -r pkg=$FUNCNAME
+ create_pkg $pkg
+ cat > $pkg/BUILD << EOF
py_binary(name = "py",
srcs = [ "py.py" ],
data = [ "e/f",
@@ -49,19 +92,21 @@ genrule(name = "hidden",
outs = [ "e/f/g/hidden.py" ],
cmd = "touch \$@")
EOF
- bazel build pkg:py >&$TEST_log 2>&1 || fail "build failed"
+ bazel build $pkg:py $EXTRA_BUILD_FLAGS >&$TEST_log 2>&1 || fail "build failed"
# we get a warning that hidden.py is inaccessible
- expect_log_once "pkg/e/f/g/hidden.py obscured by pkg/e/f "
+ expect_log_once "${pkg}/e/f/g/hidden.py obscured by ${pkg}/e/f "
}
function test_foo_runfiles() {
+ local -r pkg=$FUNCNAME
+ create_pkg $pkg
cat > BUILD << EOF
py_library(name = "root",
srcs = ["__init__.py"],
visibility = ["//visibility:public"])
EOF
-cat > pkg/BUILD << EOF
+cat > $pkg/BUILD << EOF
sh_binary(name = "foo",
srcs = [ "x/y/z.sh" ],
data = [ ":py",
@@ -74,9 +119,10 @@ py_binary(name = "py",
"e/f/g/ignored.py" ],
deps = ["//:root"])
EOF
- bazel build pkg:foo >&$TEST_log || fail "build failed"
+ bazel build $pkg:foo $EXTRA_BUILD_FLAGS >&$TEST_log || fail "build failed"
+ workspace_root=$PWD
- cd ${PRODUCT_NAME}-bin/pkg/foo.runfiles
+ cd ${PRODUCT_NAME}-bin/$pkg/foo${EXT}.runfiles
# workaround until we use assert/fail macros in the tests below
touch $TEST_TMPDIR/__fail
@@ -88,10 +134,10 @@ EOF
cd ${WORKSPACE_NAME}
# these are real directories
- test \! -L pkg
- test -d pkg
+ test \! -L $pkg
+ test -d $pkg
- cd pkg
+ cd $pkg
test \! -L a
test -d a
test \! -L a/b
@@ -133,17 +179,110 @@ EOF
# that accounts for everything
cd ../..
- assert_equals 9 $(find ${WORKSPACE_NAME} -type l | wc -l)
- assert_equals 4 $(find ${WORKSPACE_NAME} -type f | wc -l)
- assert_equals 9 $(find ${WORKSPACE_NAME} -type d | wc -l)
- assert_equals 22 $(find ${WORKSPACE_NAME} | wc -l)
- assert_equals 13 $(wc -l < MANIFEST)
+ # For shell binary, we build both `bin` and `bin.exe`, but on Linux we only build `bin`
+ # That's why we have one more symlink on Windows.
+ if "$is_windows"; then
+ assert_equals 10 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 4 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 9 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 23 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 14 $(wc -l < MANIFEST)
+ else
+ assert_equals 9 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 4 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 9 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 22 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 13 $(wc -l < MANIFEST)
+ fi
for i in $(find ${WORKSPACE_NAME} \! -type d); do
- if readlink "$i" > /dev/null; then
- echo "$i $(readlink "$i")" >> ${TEST_TMPDIR}/MANIFEST2
+ target="$(readlink "$i" || true)"
+ if [[ -z "$target" ]]; then
+ echo "$i " >> ${TEST_TMPDIR}/MANIFEST2
else
+ if "$is_windows"; then
+ echo "$i $(cygpath -m $target)" >> ${TEST_TMPDIR}/MANIFEST2
+ else
+ echo "$i $target" >> ${TEST_TMPDIR}/MANIFEST2
+ fi
+ fi
+ done
+ sort MANIFEST > ${TEST_TMPDIR}/MANIFEST_sorted
+ sort ${TEST_TMPDIR}/MANIFEST2 > ${TEST_TMPDIR}/MANIFEST2_sorted
+ diff -u ${TEST_TMPDIR}/MANIFEST_sorted ${TEST_TMPDIR}/MANIFEST2_sorted
+
+ # Rebuild the same target with a new dependency.
+ cd "$workspace_root"
+cat > $pkg/BUILD << EOF
+sh_binary(name = "foo",
+ srcs = [ "x/y/z.sh" ],
+ data = [ "e/f" ])
+EOF
+ bazel build $pkg:foo $EXTRA_BUILD_FLAGS >&$TEST_log || fail "build failed"
+
+ cd ${PRODUCT_NAME}-bin/$pkg/foo${EXT}.runfiles
+
+ # workaround until we use assert/fail macros in the tests below
+ touch $TEST_TMPDIR/__fail
+
+ # output manifest exists and is non-empty
+ test -f MANIFEST
+ test -s MANIFEST
+
+ cd ${WORKSPACE_NAME}
+
+ # these are real directories
+ test \! -L $pkg
+ test -d $pkg
+
+ # these directory should not exist anymore
+ test \! -e a
+ test \! -e c
+
+ cd $pkg
+ test \! -L e
+ test -d e
+ test \! -L x
+ test -d x
+ test \! -L x/y
+ test -d x/y
+
+ # these are symlinks to the source tree
+ test -L foo
+ test -L x/y/z.sh
+ test -L e/f
+ test -d e/f
+
+ # that accounts for everything
+ cd ../..
+ # For shell binary, we build both `bin` and `bin.exe`, but on Linux we only build `bin`
+ # That's why we have one more symlink on Windows.
+ if "$is_windows"; then
+ assert_equals 4 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 0 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 5 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 9 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 4 $(wc -l < MANIFEST)
+ else
+ assert_equals 3 $(find ${WORKSPACE_NAME} -type l | wc -l)
+ assert_equals 0 $(find ${WORKSPACE_NAME} -type f | wc -l)
+ assert_equals 5 $(find ${WORKSPACE_NAME} -type d | wc -l)
+ assert_equals 8 $(find ${WORKSPACE_NAME} | wc -l)
+ assert_equals 3 $(wc -l < MANIFEST)
+ fi
+
+ rm -f ${TEST_TMPDIR}/MANIFEST
+ rm -f ${TEST_TMPDIR}/MANIFEST2
+ for i in $(find ${WORKSPACE_NAME} \! -type d); do
+ target="$(readlink "$i" || true)"
+ if [[ -z "$target" ]]; then
echo "$i " >> ${TEST_TMPDIR}/MANIFEST2
+ else
+ if "$is_windows"; then
+ echo "$i $(cygpath -m $target)" >> ${TEST_TMPDIR}/MANIFEST2
+ else
+ echo "$i $target" >> ${TEST_TMPDIR}/MANIFEST2
+ fi
fi
done
sort MANIFEST > ${TEST_TMPDIR}/MANIFEST_sorted
@@ -166,15 +305,15 @@ EOF
cat > thing.cc <<EOF
int main() { return 0; }
EOF
- bazel build //:thing &> $TEST_log || fail "Build failed"
- [[ -d ${PRODUCT_NAME}-bin/thing.runfiles/foo ]] || fail "foo not found"
+ bazel build //:thing $EXTRA_BUILD_FLAGS &> $TEST_log || fail "Build failed"
+ [[ -d ${PRODUCT_NAME}-bin/thing${EXT}.runfiles/foo ]] || fail "foo not found"
cat > WORKSPACE <<EOF
workspace(name = "bar")
EOF
- bazel build //:thing &> $TEST_log || fail "Build failed"
- [[ -d ${PRODUCT_NAME}-bin/thing.runfiles/bar ]] || fail "bar not found"
- [[ ! -d ${PRODUCT_NAME}-bin/thing.runfiles/foo ]] \
+ bazel build //:thing $EXTRA_BUILD_FLAGS &> $TEST_log || fail "Build failed"
+ [[ -d ${PRODUCT_NAME}-bin/thing${EXT}.runfiles/bar ]] || fail "bar not found"
+ [[ ! -d ${PRODUCT_NAME}-bin/thing${EXT}.runfiles/foo ]] \
|| fail "Old foo still found"
}
| test | train | 2018-08-29T18:09:19 | "2018-08-29T07:42:41Z" | meteorcloudy | test |
bazelbuild/bazel/6061_6068 | bazelbuild/bazel | bazelbuild/bazel/6061 | bazelbuild/bazel/6068 | [
"timestamp(timedelta=29963.0, similarity=0.9261200312519905)"
] | 411ab49f8317ac0ff60c833672422fdb0df358ea | c1c46dcefa3120b18f83416768e23e5c8c398411 | [
"Why am I assigned to this @laszlocsomor?",
"IIRC you updated Protobuf in the past. If so, you have domain expertise. Am I confusing it with gRPC though?",
"I have, so have other people. I currently have multiple P1s I am working on and don't have time to update protobuf anytime soon. There's a detailed description on how to update protobuf here: https://github.com/bazelbuild/bazel/tree/master/third_party/protobuf",
"Thanks for the info. Let me take a look.",
"If there's a cherrypick request, please add it to the release thread (https://github.com/bazelbuild/bazel/issues/5059)."
] | [
"please put `load()` statements at the top of the file"
] | "2018-09-04T08:49:23Z" | [
"P1",
"type: process"
] | Update Protobuf to 3.6.1 | ### Description of the problem / feature request:
Please update Bazel's Protocol Buffer version to 3.6.1
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
This is breaking Bazel at HEAD when built with Visual C++ 2017 on Windows.
See https://github.com/bazelbuild/bazel/issues/6053#issuecomment-418031872.
### What operating system are you running Bazel on?
Windows 10
/cc @meteorcloudy @jin | [
"WORKSPACE",
"src/main/protobuf/BUILD",
"third_party/protobuf/3.6.1/BUILD",
"third_party/protobuf/BUILD",
"third_party/protobuf/README.md"
] | [
"WORKSPACE",
"src/main/protobuf/BUILD",
"third_party/protobuf/3.6.1/BUILD",
"third_party/protobuf/3.6.1/compiler_config_setting.bzl",
"third_party/protobuf/BUILD",
"third_party/protobuf/README.md"
] | [
"src/test/shell/bazel/testdata/embedded_tools_srcs_deps",
"src/test/shell/testenv.sh"
] | diff --git a/WORKSPACE b/WORKSPACE
index 634894979f5bd7..cf6dd6c1a2bccb 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -69,20 +69,20 @@ bind(
new_local_repository(
name = "com_google_protobuf",
- build_file = "./third_party/protobuf/3.6.0/BUILD",
- path = "./third_party/protobuf/3.6.0/",
+ build_file = "./third_party/protobuf/3.6.1/BUILD",
+ path = "./third_party/protobuf/3.6.1/",
)
new_local_repository(
name = "com_google_protobuf_cc",
- build_file = "./third_party/protobuf/3.6.0/BUILD",
- path = "./third_party/protobuf/3.6.0/",
+ build_file = "./third_party/protobuf/3.6.1/BUILD",
+ path = "./third_party/protobuf/3.6.1/",
)
new_local_repository(
name = "com_google_protobuf_java",
- build_file = "./third_party/protobuf/3.6.0/com_google_protobuf_java.BUILD",
- path = "./third_party/protobuf/3.6.0/",
+ build_file = "./third_party/protobuf/3.6.1/com_google_protobuf_java.BUILD",
+ path = "./third_party/protobuf/3.6.1/",
)
new_local_repository(
diff --git a/src/main/protobuf/BUILD b/src/main/protobuf/BUILD
index f7037cea540034..e95881a31bd59e 100644
--- a/src/main/protobuf/BUILD
+++ b/src/main/protobuf/BUILD
@@ -2,7 +2,7 @@ package(default_visibility = ["//visibility:public"])
load("//tools/build_rules:genproto.bzl", "cc_grpc_library")
load("//tools/build_rules:utilities.bzl", "java_library_srcs")
-load("//third_party/protobuf/3.6.0:protobuf.bzl", "py_proto_library")
+load("//third_party/protobuf/3.6.1:protobuf.bzl", "py_proto_library")
load("//third_party/grpc:build_defs.bzl", "java_grpc_library")
exports_files(
diff --git a/third_party/protobuf/3.6.1/BUILD b/third_party/protobuf/3.6.1/BUILD
index f489d25bb18efb..740eead5e47a69 100644
--- a/third_party/protobuf/3.6.1/BUILD
+++ b/third_party/protobuf/3.6.1/BUILD
@@ -20,6 +20,7 @@ config_setting(
################################################################################
load(":protobuf.bzl", "py_proto_library")
+load(":compiler_config_setting.bzl", "create_compiler_config_setting")
filegroup(
name = "srcs",
@@ -60,6 +61,11 @@ filegroup(
visibility = ["//visibility:public"],
)
+create_compiler_config_setting(
+ name = "msvc",
+ value = "msvc-cl",
+)
+
################################################################################
# The below build rules are a copy of the upstream protobuf BUILD file without
# the "Java support" section, as advised by Step 3 in the "Updating protobuf"
@@ -91,11 +97,6 @@ COPTS = select({
],
})
-config_setting(
- name = "msvc",
- values = { "compiler": "msvc-cl" },
-)
-
config_setting(
name = "android",
values = {
diff --git a/third_party/protobuf/3.6.1/compiler_config_setting.bzl b/third_party/protobuf/3.6.1/compiler_config_setting.bzl
new file mode 100644
index 00000000000000..5e52a6524ffe5f
--- /dev/null
+++ b/third_party/protobuf/3.6.1/compiler_config_setting.bzl
@@ -0,0 +1,21 @@
+"""Creates config_setting that allows selecting based on 'compiler' value."""
+
+def create_compiler_config_setting(name, value):
+ # The "do_not_use_tools_cpp_compiler_present" attribute exists to
+ # distinguish between older versions of Bazel that do not support
+ # "@bazel_tools//tools/cpp:compiler" flag_value, and newer ones that do.
+ # In the future, the only way to select on the compiler will be through
+ # flag_values{"@bazel_tools//tools/cpp:compiler"} and the else branch can
+ # be removed.
+ if hasattr(cc_common, "do_not_use_tools_cpp_compiler_present"):
+ native.config_setting(
+ name = name,
+ flag_values = {
+ "@bazel_tools//tools/cpp:compiler": value,
+ },
+ )
+ else:
+ native.config_setting(
+ name = name,
+ values = {"compiler": value},
+ )
diff --git a/third_party/protobuf/BUILD b/third_party/protobuf/BUILD
index 0e90544f85b0c0..9a67e87ffdacff 100644
--- a/third_party/protobuf/BUILD
+++ b/third_party/protobuf/BUILD
@@ -4,14 +4,14 @@ licenses(["notice"])
load(":proto_alias.bzl", "proto_alias")
-PROTOBUF_VERSION = "3.6.0"
-_PROTOBUF_NEW_VERSION = "3.6.1"
+_OLD_PROTOBUF_VERSION = "3.6.0"
+PROTOBUF_VERSION = "3.6.1"
filegroup(
name = "srcs",
srcs = [
+ "//third_party/protobuf/" + _OLD_PROTOBUF_VERSION + ":srcs",
"//third_party/protobuf/" + PROTOBUF_VERSION + ":srcs",
- "//third_party/protobuf/" + _PROTOBUF_NEW_VERSION + ":srcs",
] + glob(["**"]), # glob everything to satisfy the compile.sh srcs test
visibility = ["//third_party:__pkg__"],
)
diff --git a/third_party/protobuf/README.md b/third_party/protobuf/README.md
index 10837db9db2cc7..e2a428a2afa9dd 100644
--- a/third_party/protobuf/README.md
+++ b/third_party/protobuf/README.md
@@ -38,4 +38,4 @@ the new version.
# Current protobuf version
-The current version of protobuf is [3.6.0](https://github.com/google/protobuf/releases/tag/v3.6.0).
+The current version of protobuf is [3.6.1](https://github.com/google/protobuf/releases/tag/v3.6.1).
| diff --git a/src/test/shell/bazel/testdata/embedded_tools_srcs_deps b/src/test/shell/bazel/testdata/embedded_tools_srcs_deps
index 5f373788af0ba7..07704af47d52ed 100644
--- a/src/test/shell/bazel/testdata/embedded_tools_srcs_deps
+++ b/src/test/shell/bazel/testdata/embedded_tools_srcs_deps
@@ -2,7 +2,6 @@
@com_google_protobuf//:protoc_lib
@com_google_protobuf//:protobuf
@com_google_protobuf//:protobuf_lite
-@com_google_protobuf//:js_embed
//tools/test:test_wrapper_bin
//third_party/ijar:zipper
//third_party/ijar:ijar
diff --git a/src/test/shell/testenv.sh b/src/test/shell/testenv.sh
index d5b7afc82d8c0e..b9f1b9dcbb65f0 100755
--- a/src/test/shell/testenv.sh
+++ b/src/test/shell/testenv.sh
@@ -115,7 +115,7 @@ if [ "${MACHINE_TYPE}" = 's390x' ]; then
fi
# Requires //third_party/protobuf:protoc
-protoc_compiler="${BAZEL_RUNFILES}/third_party/protobuf/3.6.0/protoc"
+protoc_compiler="${BAZEL_RUNFILES}/third_party/protobuf/3.6.1/protoc"
if [ -z ${RUNFILES_MANIFEST_ONLY+x} ]; then
junit_jar="${BAZEL_RUNFILES}/third_party/junit/junit-*.jar"
| val | train | 2018-09-04T16:25:55 | "2018-09-03T09:03:28Z" | laszlocsomor | test |
bazelbuild/bazel/6061_6082 | bazelbuild/bazel | bazelbuild/bazel/6061 | bazelbuild/bazel/6082 | [
"timestamp(timedelta=7101.0, similarity=0.8553772038536177)"
] | 27303d79c38f2bfa3b64ee7cd7a6ef03a9a87842 | 13670057b9d02a8316508297458fd9a4b5cc202e | [
"Why am I assigned to this @laszlocsomor?",
"IIRC you updated Protobuf in the past. If so, you have domain expertise. Am I confusing it with gRPC though?",
"I have, so have other people. I currently have multiple P1s I am working on and don't have time to update protobuf anytime soon. There's a detailed description on how to update protobuf here: https://github.com/bazelbuild/bazel/tree/master/third_party/protobuf",
"Thanks for the info. Let me take a look.",
"If there's a cherrypick request, please add it to the release thread (https://github.com/bazelbuild/bazel/issues/5059)."
] | [] | "2018-09-05T08:02:36Z" | [
"P1",
"type: process"
] | Update Protobuf to 3.6.1 | ### Description of the problem / feature request:
Please update Bazel's Protocol Buffer version to 3.6.1
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
This is breaking Bazel at HEAD when built with Visual C++ 2017 on Windows.
See https://github.com/bazelbuild/bazel/issues/6053#issuecomment-418031872.
### What operating system are you running Bazel on?
Windows 10
/cc @meteorcloudy @jin | [
"third_party/protobuf/README.md"
] | [
"third_party/protobuf/README.md"
] | [] | diff --git a/third_party/protobuf/README.md b/third_party/protobuf/README.md
index e2a428a2afa9dd..a678ab5b02426f 100644
--- a/third_party/protobuf/README.md
+++ b/third_party/protobuf/README.md
@@ -1,40 +1,100 @@
# Updating protobuf
+You will create and merge the following Pull Requests.
-1) Fetch the desired protobuf version and copy it in a folder `new_proto` under
-`third_party/protobuf`.
-2) Bazel uses upstream protobuf from source, except for java, as we currently don't
-build protobuf java when bootstrapping bazel. So instead we use pre-built jars.
-So build the java proto library from source and in case you cloned an upstream version
-of protobuf, remove the .git folders:
-```
-cd new_proto
-bazel build :protobuf_java :protobuf_java_util
-cp bazel-bin/libprotobuf_java.jar .
-cp bazel-bin/libprotobuf_java_util.jar .
-bazel clean --expunge
-rm -rf .git .gitignore .gitmodules
-```
-3) Modify protobuf's `BUILD` file to not build java from source, but to use
- the jars instead. To do that, in the BUILD file delete the rules listed
- under `Java support`. Then, from the `third_party/protobuf/<old_proto>/BUILD file`
- copy the rules under "Modifications made by bazel" to the new BUILD file.
- The java rules in there should have the same names as the ones you just deleted under "Java support".
- You might need to update the names of the jars in the rules sources to the ones you just build.
-4) Copy `third_party/protobuf/<old_proto>/com_google_protobuf_java.BUILD` to the new
- directory.
-5) Copy the `licenses` declaration and the `srcs` filegroup from
- `third_party/protobuf/<old_proto>/util/python/BUILD` and
- `third_party/protobuf/<old_proto>/examples/BUILD` to the corresponding
- file in the new directory.
-6) Name the `new\_proto` directory according to the protobuf version number.
-7) In `third\_party/protobuf/BUILD` update `PROTOBUF\_VERSION` to the name of the
-directory you just created.
-8) In the root `WORKSPACE` file update relative paths of protobuf to point to
-the new version.
-9) Update version number in `src/main/protobuf/BUILD` and `src/test/shell/testenv.sh`.
-10) Delete the `third_party/protobuf/<old_proto>` directory.
-11) Update this file if you found the :instructions to be wrong or incomplete.
+## 1st PR: add the new protobuf version to the Bazel tree
+
+1. Fetch the desired protobuf version and copy it in a folder `new_proto` under
+ `third_party/protobuf`.
+
+ **Example:** to upgrade to 3.6.1, download and unpack
+ [protobuf-all-3.6.1.zip](https://github.com/protocolbuffers/protobuf/releases/download/v3.6.1/protobuf-all-3.6.1.zip).
+
+1. Build the Java proto library from source and, in case you cloned an upstream version
+ of protobuf, remove the .git folders:
+
+ ```
+ cd third_party/protobuf/new_proto
+ bazel build :protobuf_java :protobuf_java_util
+ cp bazel-bin/libprotobuf_java.jar .
+ cp bazel-bin/libprotobuf_java_util.jar .
+ bazel clean --expunge
+ rm -rf .git .gitignore .gitmodules
+ ```
+
+ **Reason:** Bazel uses upstream protobuf from source, except for Java, as Bazel's bootstrapping
+ scripts currently don't build protobuf Java when bootstrapping Bazel but use pre-built jars
+ instead.
+
+1. Modify protobuf's `BUILD` file to not build java from source, but to use the jars instead:
+
+ 1. In the BUILD file delete the rules listed under `Java support`.
+
+ 1. From the `third_party/protobuf/<old_proto>/BUILD` file copy the rules under the
+ "Modifications made by bazel" section to the new BUILD file. The java rules in there should
+ have the same names as the ones you just deleted under "Java support". You might need to
+ update the names of the jars in the rules sources to the ones you just build.
+
+1. Copy `third_party/protobuf/<old_proto>/com_google_protobuf_java.BUILD` to the new directory.
+
+1. From `third_party/protobuf/<old_proto>/util/python/BUILD`,
+ `third_party/protobuf/<old_proto>/examples/BUILD`, and
+ `third_party/protobuf/<old_proto>/third_party/googletest/BUILD.bazel`:
+ copy the `licenses` declaration and the `srcs` filegroup to the corresponding file under
+ `third_party/protobuf/<new_proto>`.
+
+1. In `third_party/protobuf/<new_proto>/BUILD`, in the `srcs` filegroup rule, update the version
+ number referring to the newly added `srcs` rules.
+
+1. Rename `third_party/protobuf/<new_proto>` directory according to the protobuf version number.
+
+1. In `third_party/protobuf/BUILD`:
+
+ 1. Add a new variable `_NEW_PROTOBUF_VERSION`, set to value of the version.
+
+ 1. In the `srcs` filegroup rule, add:
+
+ ```diff
+ srcs = [
+ "//third_party/protobuf/" + PROTOBUF_VERSION + ":srcs",
+ + "//third_party/protobuf/" + _NEW_PROTOBUF_VERSION + ":srcs",
+ ],
+ ```
+
+1. Create a PR of these changes and merge it directly to
+ https://bazel.googlesource.com/bazel/+/master (without the usual process of importing it to
+ the Google-internal version control).
+
+## 2nd and 3rd PRs: update references in the Bazel tree
+
+1. In `third_party/protobuf/BUILD`:
+
+ 1. rename `PROTOBUF_VERSION` to `_OLD_PROTOBUF_VERSION`
+
+ 1. rename `_NEW_PROTOBUF_VERSION` to `PROTOBUF_VERSION`
+
+1. In the root `WORKSPACE` file update relative paths of protobuf to point to the new version.
+
+1. Update version number in `src/main/protobuf/BUILD` and `src/test/shell/testenv.sh`.
+
+1. Update the current version in this file.
+
+1. Create a PR of these changes and get it imported. Some files won't be imported (those that are
+ only hosted on GitHub); this is expected.
+
+2. Wait for the imported PR to be pushed back to GitHub. Rebase the PR from the previous step, and
+ merge it to https://bazel.googlesource.com/bazel/+/master .
+
+## 4th PR: remove the old directory
+
+1. Delete the `third_party/protobuf/<old_proto>` directory.
+
+1. Remove `_OLD_PROTOBUF_VERSION` from `third_party/protobuf/BUILD`.
+
+1. Create a PR of these changes and merge it directly to
+ https://bazel.googlesource.com/bazel/+/master .
+
+**Update this file if you found these instructions to be wrong or incomplete.**
# Current protobuf version
| null | train | train | 2018-09-05T08:45:59 | "2018-09-03T09:03:28Z" | laszlocsomor | test |
bazelbuild/bazel/6099_6100 | bazelbuild/bazel | bazelbuild/bazel/6099 | bazelbuild/bazel/6100 | [
"timestamp(timedelta=0.0, similarity=0.8646177122156461)"
] | 236e6ed3f1158ccaf928c114017bcba45961bb12 | 6a47303955f6361f126494372e5a2f2438e6cbed | [
"I found the root cause: similarly to https://github.com/bazelbuild/bazel/issues/2576, it's the java log path. Turns out we must pass the path with escaped backslashes instead of forward slashes. Working on a fix.",
"How come it worked in 0.17rc1 then?",
"I don't know yet. What I do know is that (a) the fix solves this issue, and (b) the fix removes an exception from the `<output_base>/server/jvm.out` that I've been aware of for a long time, but which never seemed to result in any problems (until now?)."
] | [
"Isn't this quadratic? Mind you, not that the strings in question are very long (cue PATH_MAX), but if there is a simple way...",
"You're fully right. Let me fix that.",
"nit: `std::count` could be used to count these numbers, but I'm not at all sure if it would result in simpler code.",
"nit: you overwrite it anyway, why zero it out?",
"I'm not sure if a blackbelt in C++ would be able to do it using the standard library, but I sure don't know how. string splitting/joining is apparently not in the standard library and this doesn't require retreating to a monastery for years to make sense of, so go ahead.",
"Thanks for the idea! I'd need to use `count_if` and I think the resulting code would be neither more readable nor more efficient.",
"Thanks! I'm also not aware of a good library function for this.",
"AFAIK this is how you reserve space in a string.",
"That sentiment, I can heartily agree with! :)"
] | "2018-09-07T14:35:26Z" | [] | Windows, Bazel 0.17.0rc2, regression: bazel no longer writes java.log | ### Description of the problem / feature request:
0.17.0 rc2 regression over rc1: Bazel on Windows no longer writes `<output_base>/java.log`.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Build anything with 0.17.0 rc1, then run `bazel info output_base`, list the reported directory, see `java.log` is there.
Do the same with rc2, see that `java.log` is not there.
### What operating system are you running Bazel on?
Windows 10 v1709 | [
"src/main/cpp/startup_options.cc",
"src/main/cpp/util/path_windows.cc"
] | [
"src/main/cpp/startup_options.cc",
"src/main/cpp/util/path_windows.cc"
] | [
"src/test/shell/integration/execution_phase_tests.sh",
"src/test/shell/integration/server_logging_test.sh"
] | diff --git a/src/main/cpp/startup_options.cc b/src/main/cpp/startup_options.cc
index 05ec6de69ac7b5..fbf34679d32e55 100644
--- a/src/main/cpp/startup_options.cc
+++ b/src/main/cpp/startup_options.cc
@@ -537,8 +537,9 @@ blaze_exit_code::ExitCode StartupOptions::AddJVMArguments(
void StartupOptions::AddJVMLoggingArguments(std::vector<string> *result) const {
// Configure logging
const string propFile =
- blaze_util::JoinPath(output_base, "javalog.properties");
- string java_log(
+ blaze_util::PathAsJvmFlag(
+ blaze_util::JoinPath(output_base, "javalog.properties"));
+ const string java_log(
blaze_util::PathAsJvmFlag(blaze_util::JoinPath(output_base, "java.log")));
if (!blaze_util::WriteFile("handlers=java.util.logging.FileHandler\n"
".level=INFO\n"
diff --git a/src/main/cpp/util/path_windows.cc b/src/main/cpp/util/path_windows.cc
index c7afe4021d3578..bb1b227e1a56f0 100644
--- a/src/main/cpp/util/path_windows.cc
+++ b/src/main/cpp/util/path_windows.cc
@@ -119,18 +119,38 @@ bool CompareAbsolutePaths(const std::string& a, const std::string& b) {
}
std::string PathAsJvmFlag(const std::string& path) {
- std::string spath;
+ std::string cpath;
std::string error;
- if (!AsShortWindowsPath(path, &spath, &error)) {
+ if (!AsWindowsPath(path, &cpath, &error)) {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "PathAsJvmFlag(" << path
- << "): AsShortWindowsPath failed: " << error;
+ << "): AsWindowsPath failed: " << error;
}
- // Convert backslashes to forward slashes, in order to avoid the JVM parsing
- // Windows paths as if they contained escaped characters.
- // See https://github.com/bazelbuild/bazel/issues/2576
- std::replace(spath.begin(), spath.end(), '\\', '/');
- return spath;
+ // Convert forward slashes and backslashes to double (escaped) backslashes, so
+ // they are safe to pass on the command line to the JVM and the JVM won't
+ // misinterpret them.
+ // See https://github.com/bazelbuild/bazel/issues/2576 and
+ // https://github.com/bazelbuild/bazel/issues/6098
+ size_t separators = 0;
+ for (const auto& c : cpath) {
+ if (c == '/' || c == '\\') {
+ separators++;
+ }
+ }
+ // In the result we replace each '/' and '\' with "\\", i.e. the total size
+ // *increases* by `separators`.
+ // Create a string of that size, filled with zeroes.
+ std::string result(/* count */ cpath.size() + separators, '\0');
+ std::string::size_type i = 0;
+ for (const auto& c : cpath) {
+ if (c == '/' || c == '\\') {
+ result[i++] = '\\';
+ result[i++] = '\\';
+ } else {
+ result[i++] = c;
+ }
+ }
+ return result;
}
void AddUncPrefixMaybe(std::wstring* path) {
| diff --git a/src/test/shell/integration/execution_phase_tests.sh b/src/test/shell/integration/execution_phase_tests.sh
index 74b3e1b14d98e2..71951a21f55f21 100755
--- a/src/test/shell/integration/execution_phase_tests.sh
+++ b/src/test/shell/integration/execution_phase_tests.sh
@@ -105,9 +105,6 @@ function assert_cache_stats() {
#### TESTS #############################################################
function test_cache_computed_file_digests_behavior() {
- # Does not work on Windows, https://github.com/bazelbuild/bazel/issues/6098
- return
-
local -r pkg="${FUNCNAME}"
mkdir -p "$pkg" || fail "could not create \"$pkg\""
@@ -168,9 +165,8 @@ EOF
assert_cache_stats "miss count" 1 # volatile-status.txt
}
-function test_cache_computed_file_digests_uncaught_changes() {
- return
-
+function DISABLED_test_cache_computed_file_digests_uncaught_changes() {
+ # Does not work on Windows, https://github.com/bazelbuild/bazel/issues/6098
local timestamp=201703151112.13 # Fixed timestamp to mark our file with.
mkdir -p package || fail "mkdir failed"
@@ -230,9 +226,6 @@ EOF
}
function test_cache_computed_file_digests_ui() {
- # Does not work on Windows, https://github.com/bazelbuild/bazel/issues/6098
- return
-
local -r pkg="${FUNCNAME}"
mkdir -p "$pkg" || fail "could not create \"$pkg\""
@@ -257,8 +250,6 @@ function test_cache_computed_file_digests_ui() {
}
function test_jobs_default_auto() {
- return
-
local -r pkg="${FUNCNAME}"
mkdir -p "$pkg" || fail "could not create \"$pkg\""
@@ -279,8 +270,6 @@ function test_jobs_default_auto() {
}
function test_analysis_warning_cached() {
- return
-
mkdir -p "foo" "bar" || fail "Could not create directories"
cat > foo/BUILD <<'EOF' || fail "foo/BUILD"
cc_library(
diff --git a/src/test/shell/integration/server_logging_test.sh b/src/test/shell/integration/server_logging_test.sh
index 931a4dedaeaa9a..bee416098fc3c8 100755
--- a/src/test/shell/integration/server_logging_test.sh
+++ b/src/test/shell/integration/server_logging_test.sh
@@ -67,9 +67,6 @@ fi
#### TESTS #############################################################
function test_log_file_uses_single_line_formatter() {
- # Does not work on Windows, https://github.com/bazelbuild/bazel/issues/6098
- return
-
local client_log="$(bazel info output_base)/java.log"
# Construct a regular expression to match a sample message in the log using
| train | train | 2018-09-07T15:36:57 | "2018-09-07T12:39:38Z" | laszlocsomor | test |
bazelbuild/bazel/6141_6142 | bazelbuild/bazel | bazelbuild/bazel/6141 | bazelbuild/bazel/6142 | [
"timestamp(timedelta=0.0, similarity=0.9339910474624503)"
] | 46e65d1fb236d0eea9d2f8511e7412d98b534fc6 | 62c66e5401d06c6bafebc8f818b25b4d5a133bad | [] | [
"Just curious: Do relative paths still work when prefixed with `\\\\?\\` ?",
"Sorry - ignore that. I somehow thought that this method can also produce relative paths (GitHub showed the diff in a strange way, until I refreshed the page and suddenly it's 10x as large)",
"TIL: you can have a directory named with `...`\r\nThanks! ;)",
"Thanks!\r\nFor completeness' sake, even though you can create such a directory (e.g. from MSYS: `mkdir '/c/...'`) it's not fully usable from Windows Explorer and other shell applications.\r\nFor example, you cannot `cd` into it but you can list its contents and access its files."
] | "2018-09-13T15:40:58Z" | [
"platform: windows",
"area-Windows",
"team-OSS"
] | Windows,Bazel client: bug in C++ impl. of NormalizeWindowsPath | `NormalizeWindowsPath` strips leading `../` from relative paths. | [
"src/main/cpp/util/path_platform.h",
"src/main/cpp/util/path_windows.cc"
] | [
"src/main/cpp/util/path_platform.h",
"src/main/cpp/util/path_windows.cc"
] | [
"src/test/cpp/util/file_windows_test.cc",
"src/test/cpp/util/path_windows_test.cc"
] | diff --git a/src/main/cpp/util/path_platform.h b/src/main/cpp/util/path_platform.h
index b0fb88de51c0ad..2b99dba00a40dc 100644
--- a/src/main/cpp/util/path_platform.h
+++ b/src/main/cpp/util/path_platform.h
@@ -82,28 +82,11 @@ std::pair<std::wstring, std::wstring> SplitPathW(const std::wstring &path);
bool IsRootDirectoryW(const std::wstring &path);
-// Returns a normalized form of the input `path`.
-//
-// `path` must be a relative or absolute Windows path, it may use "/" instead of
-// "\" but must not be a Unix-style (MSYS) path.
-// The result won't have a UNC prefix, even if `path` did.
-//
-// Normalization means removing "." references, resolving ".." references, and
-// deduplicating "/" characters while converting them to "\".
-// For example if `path` is "foo/../bar/.//qux", the result is "bar\qux".
-//
-// Uplevel references that cannot go any higher in the directory tree are simply
-// ignored, e.g. "c:/.." is normalized to "c:\" and "../../foo" is normalized to
-// "foo".
-//
-// Visible for testing, would be static otherwise.
-template <typename char_type>
-std::basic_string<char_type> NormalizeWindowsPath(
- std::basic_string<char_type> path);
+namespace testing {
+
+bool TestOnly_NormalizeWindowsPath(const std::string& path,
+ std::string* result);
-template <typename char_type>
-std::basic_string<char_type> NormalizeWindowsPath(const char_type *path) {
- return NormalizeWindowsPath(std::basic_string<char_type>(path));
}
// Converts a UTF8-encoded `path` to a normalized, widechar Windows path.
diff --git a/src/main/cpp/util/path_windows.cc b/src/main/cpp/util/path_windows.cc
index 07231475c814cb..df2a5a4e18ebd5 100644
--- a/src/main/cpp/util/path_windows.cc
+++ b/src/main/cpp/util/path_windows.cc
@@ -238,6 +238,139 @@ void assignNUL(std::string* s) { s->assign("NUL"); }
void assignNUL(std::wstring* s) { s->assign(L"NUL"); }
+// Returns a normalized form of the input `path`.
+//
+// Normalization:
+// Normalization means removing "." references, resolving ".." references,
+// and deduplicating "/" characters while converting them to "\\". For
+// example if `path` is "foo/../bar/.//qux", the result is "bar\\qux".
+//
+// Uplevel references ("..") that cannot go any higher in the directory tree
+// are preserved if the path is relative, and ignored if the path is
+// absolute, e.g. "../../foo" is normalized to "..\\..\\foo" but "c:/.." is
+// normalized to "c:\\".
+//
+// This method does not check the semantics of the `path` beyond checking if
+// it starts with a directory separator. Illegal paths such as one with a
+// drive specifier in the middle (e.g. "foo/c:/bar") are accepted -- it's the
+// caller's responsibility to pass a path that, when normalized, will be
+// semantically correct.
+//
+// Current directory references (".") are preserved if and only if they are
+// the only path segment, so "./" becomes "." but "./foo" becomes "foo".
+//
+// Arguments:
+// `path` must be a relative or absolute Windows path, it may use "/" instead
+// of "\\". The path should not start with "/" or "\\".
+//
+// Result:
+// Returns false if and only if the path starts with a directory separator.
+//
+// The result won't have a UNC prefix, even if `path` did. The result won't
+// have a trailing "\\" except when and only when the path is normalized to
+// just a drive specifier (e.g. when `path` is "c:/" or "c:/foo/.."). The
+// result will preserve the casing of the input, so "D:/Bar" becomes
+// "D:\\Bar".
+template <typename char_type>
+static bool NormalizeWindowsPath(const std::basic_string<char_type>& path,
+ std::basic_string<char_type>* result) {
+ if (path.empty()) {
+ *result = path;
+ return true;
+ }
+ if (IsPathSeparator(path[0])) {
+ return false;
+ }
+
+ static const std::basic_string<char_type> kDot =
+ std::basic_string<char_type>(1, '.');
+ static const std::basic_string<char_type> kDotDot =
+ std::basic_string<char_type>(2, '.');
+
+ std::vector<std::basic_string<char_type> > segments;
+ std::basic_string<char_type>::size_type seg_start = path.size();
+ std::basic_string<char_type>::size_type total_len = 0;
+ for (std::basic_string<char_type>::size_type i =
+ HasUncPrefix(path.c_str()) ? 4 : 0; i <= path.size(); ++i) {
+ if (i == path.size() || IsPathSeparator(path[i])) {
+ // The current character ends a segment.
+ if (seg_start < path.size() && i > seg_start) {
+ std::basic_string<char_type> seg =
+ i == path.size()
+ ? path.substr(seg_start)
+ : path.substr(seg_start, i - seg_start);
+ if (seg == kDotDot) {
+ if (segments.empty() || segments.back() == kDotDot) {
+ // Preserve ".." if the path is relative and there are only ".."
+ // segment(s) at the front.
+ segments.push_back(seg);
+ total_len += 2;
+ } else if (segments.size() == 1 && segments.back() == kDot) {
+ // Replace the existing "." if that was the only path segment.
+ segments[0] = seg;
+ total_len = 2;
+ } else if (segments.size() > 1 ||
+ !HasDriveSpecifierPrefix(segments.back().c_str())) {
+ // Remove the last segment unless the path is already at the root
+ // directory.
+ total_len -= segments.back().size();
+ segments.pop_back();
+ }
+ } else if (seg == kDot) {
+ if (segments.empty()) {
+ // Preserve "." if and only if it's the first path segment.
+ // Subsequent segments may replace this segment.
+ segments.push_back(seg);
+ total_len = 1;
+ }
+ } else {
+ // This is a normal path segment, i.e. neither "." nor ".."
+ if (segments.size() == 1 && segments[0] == kDot) {
+ // Replace the only path segment if it was "."
+ segments[0] = seg;
+ total_len = seg.size();
+ } else {
+ // Store the current segment.
+ segments.push_back(seg);
+ total_len += seg.size();
+ }
+ }
+ }
+ // Indicate that there's no segment started.
+ seg_start = path.size();
+ } else {
+ // The current character starts a new segment, or is inside one.
+ if (seg_start == path.size()) {
+ // The current character starts the segment.
+ seg_start = i;
+ }
+ }
+ }
+ if (segments.empty()) {
+ result->clear();
+ return true;
+ }
+ if (segments.size() == 1 &&
+ HasDriveSpecifierPrefix(segments.back().c_str())) {
+ *result = segments.back() + std::basic_string<char_type>(1, '\\');
+ return true;
+ }
+ // Reserve enough space for all segments plus separators between them (one
+ // less than segments.size()).
+ *result = std::basic_string<char_type>(total_len + segments.size() - 1, 0);
+ std::basic_string<char_type>::iterator pos = result->begin();
+ std::basic_string<char_type>::size_type idx = 0;
+ for (const auto& seg : segments) {
+ std::copy(seg.cbegin(), seg.cend(), pos);
+ pos += seg.size();
+ if (pos < result->cend() - 1) {
+ // Add a separator if we haven't reached the end of the string yet.
+ *pos++ = '\\';
+ }
+ }
+ return true;
+}
+
template <typename char_type>
bool AsWindowsPath(const std::basic_string<char_type>& path,
std::basic_string<char_type>* result, std::string* error) {
@@ -285,7 +418,13 @@ bool AsWindowsPath(const std::basic_string<char_type>& path,
drive.push_back(':');
mutable_path = drive + path;
} // otherwise this is a relative path, or absolute Windows path.
- result->assign(NormalizeWindowsPath(mutable_path));
+
+ if (!NormalizeWindowsPath(mutable_path, result)) {
+ if (error) {
+ *error = "path normalization failed";
+ }
+ return false;
+ }
return true;
}
@@ -315,7 +454,11 @@ bool AsAbsoluteWindowsPath(const std::basic_string<char_type>& path,
return false;
}
if (!IsRootOrAbsolute(*result, /* must_be_root */ false)) {
- *result = GetCwdW() + L"\\" + *result;
+ if (result->empty() || (result->size() == 1 && (*result)[0] == '.')) {
+ *result = GetCwdW();
+ } else {
+ *result = GetCwdW() + L"\\" + *result;
+ }
}
if (!HasUncPrefix(result->c_str())) {
*result = std::wstring(L"\\\\?\\") + *result;
@@ -430,73 +573,13 @@ static char GetCurrentDrive() {
return 'a' + wdrive - offset;
}
-template <typename char_type>
-std::basic_string<char_type> NormalizeWindowsPath(
- std::basic_string<char_type> path) {
- if (path.empty()) {
- return std::basic_string<char_type>();
- }
- if (path[0] == '/') {
- // This is an absolute MSYS path, error out.
- BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
- << "NormalizeWindowsPath(" << path << "): expected a Windows path";
- }
- if (path.size() >= 4 && HasUncPrefix(path.c_str())) {
- path = path.substr(4);
- }
-
- static const std::basic_string<char_type> dot(1, '.');
- static const std::basic_string<char_type> dotdot(2, '.');
-
- std::vector<std::basic_string<char_type>> segments;
- int segment_start = -1;
- // Find the path segments in `path` (separated by "/").
- for (int i = 0;; ++i) {
- if (!IsPathSeparator(path[i]) && path[i] != '\0') {
- // The current character does not end a segment, so start one unless it's
- // already started.
- if (segment_start < 0) {
- segment_start = i;
- }
- } else if (segment_start >= 0 && i > segment_start) {
- // The current character is "/" or "\0", so this ends a segment.
- // Add that to `segments` if there's anything to add; handle "." and "..".
- std::basic_string<char_type> segment(path, segment_start,
- i - segment_start);
- segment_start = -1;
- if (segment == dotdot) {
- if (!segments.empty() &&
- !HasDriveSpecifierPrefix(segments[0].c_str())) {
- segments.pop_back();
- }
- } else if (segment != dot) {
- segments.push_back(segment);
- }
- }
- if (path[i] == '\0') {
- break;
- }
- }
-
- // Handle the case when `path` is just a drive specifier (or some degenerate
- // form of it, e.g. "c:\..").
- if (segments.size() == 1 && segments[0].size() == 2 &&
- HasDriveSpecifierPrefix(segments[0].c_str())) {
- segments[0].push_back('\\');
- return segments[0];
- }
+namespace testing {
- // Join all segments.
- bool first = true;
- std::basic_ostringstream<char_type> result;
- for (const auto& s : segments) {
- if (!first) {
- result << '\\';
- }
- first = false;
- result << s;
- }
- return result.str();
+bool TestOnly_NormalizeWindowsPath(const std::string& path,
+ std::string* result) {
+ return NormalizeWindowsPath(path, result);
}
+} // namespace testing
+
} // namespace blaze_util
| diff --git a/src/test/cpp/util/file_windows_test.cc b/src/test/cpp/util/file_windows_test.cc
index 6c1ec2f4769a98..cae80e23d687b4 100644
--- a/src/test/cpp/util/file_windows_test.cc
+++ b/src/test/cpp/util/file_windows_test.cc
@@ -44,9 +44,6 @@ using std::string;
using std::unique_ptr;
using std::wstring;
-// Methods defined in file_windows.cc that are only visible for testing.
-string NormalizeWindowsPath(string path);
-
class FileWindowsTest : public ::testing::Test {
public:
void TearDown() override { DeleteAllUnder(GetTestTmpDirW()); }
diff --git a/src/test/cpp/util/path_windows_test.cc b/src/test/cpp/util/path_windows_test.cc
index 0638ebb06ecc5d..7d362aff43cc40 100644
--- a/src/test/cpp/util/path_windows_test.cc
+++ b/src/test/cpp/util/path_windows_test.cc
@@ -41,30 +41,87 @@ using std::unique_ptr;
using std::wstring;
TEST(PathWindowsTest, TestNormalizeWindowsPath) {
- ASSERT_EQ(string(""), NormalizeWindowsPath(""));
- ASSERT_EQ(string(""), NormalizeWindowsPath("."));
- ASSERT_EQ(string("foo"), NormalizeWindowsPath("foo"));
- ASSERT_EQ(string("foo"), NormalizeWindowsPath("foo/"));
- ASSERT_EQ(string("foo\\bar"), NormalizeWindowsPath("foo//bar"));
- ASSERT_EQ(string("foo\\bar"), NormalizeWindowsPath("../..//foo/./bar"));
- ASSERT_EQ(string("foo\\bar"), NormalizeWindowsPath("../foo/baz/../bar"));
- ASSERT_EQ(string("c:\\"), NormalizeWindowsPath("c:"));
- ASSERT_EQ(string("c:\\"), NormalizeWindowsPath("c:/"));
- ASSERT_EQ(string("c:\\"), NormalizeWindowsPath("c:\\"));
- ASSERT_EQ(string("c:\\foo\\bar"), NormalizeWindowsPath("c:\\..//foo/./bar/"));
-
- ASSERT_EQ(wstring(L""), NormalizeWindowsPath(L""));
- ASSERT_EQ(wstring(L""), NormalizeWindowsPath(L"."));
- ASSERT_EQ(wstring(L"foo"), NormalizeWindowsPath(L"foo"));
- ASSERT_EQ(wstring(L"foo"), NormalizeWindowsPath(L"foo/"));
- ASSERT_EQ(wstring(L"foo\\bar"), NormalizeWindowsPath(L"foo//bar"));
- ASSERT_EQ(wstring(L"foo\\bar"), NormalizeWindowsPath(L"../..//foo/./bar"));
- ASSERT_EQ(wstring(L"foo\\bar"), NormalizeWindowsPath(L"../foo/baz/../bar"));
- ASSERT_EQ(wstring(L"c:\\"), NormalizeWindowsPath(L"c:"));
- ASSERT_EQ(wstring(L"c:\\"), NormalizeWindowsPath(L"c:/"));
- ASSERT_EQ(wstring(L"c:\\"), NormalizeWindowsPath(L"c:\\"));
- ASSERT_EQ(wstring(L"c:\\foo\\bar"),
- NormalizeWindowsPath(L"c:\\..//foo/./bar/"));
+#define ASSERT_NORMALIZE(x, y) { \
+ std::string result; \
+ EXPECT_TRUE(blaze_util::testing::TestOnly_NormalizeWindowsPath( \
+ x, &result)); \
+ EXPECT_EQ(result, y); \
+ }
+
+ ASSERT_NORMALIZE("", "");
+ ASSERT_NORMALIZE("a", "a");
+ ASSERT_NORMALIZE("foo/bar", "foo\\bar");
+ ASSERT_NORMALIZE("foo/../bar", "bar");
+ ASSERT_NORMALIZE("a/", "a");
+ ASSERT_NORMALIZE("foo", "foo");
+ ASSERT_NORMALIZE("foo/", "foo");
+ ASSERT_NORMALIZE(".", ".");
+ ASSERT_NORMALIZE("./", ".");
+ ASSERT_NORMALIZE("..", "..");
+ ASSERT_NORMALIZE("../", "..");
+ ASSERT_NORMALIZE("./..", "..");
+ ASSERT_NORMALIZE("./../", "..");
+ ASSERT_NORMALIZE("../.", "..");
+ ASSERT_NORMALIZE(".././", "..");
+ ASSERT_NORMALIZE("...", "...");
+ ASSERT_NORMALIZE(".../", "...");
+ ASSERT_NORMALIZE("a/", "a");
+ ASSERT_NORMALIZE(".a", ".a");
+ ASSERT_NORMALIZE("..a", "..a");
+ ASSERT_NORMALIZE("...a", "...a");
+ ASSERT_NORMALIZE("./a", "a");
+ ASSERT_NORMALIZE("././a", "a");
+ ASSERT_NORMALIZE("./../a", "..\\a");
+ ASSERT_NORMALIZE(".././a", "..\\a");
+ ASSERT_NORMALIZE("../../a", "..\\..\\a");
+ ASSERT_NORMALIZE("../.../a", "..\\...\\a");
+ ASSERT_NORMALIZE(".../../a", "a");
+ ASSERT_NORMALIZE("a/..", "");
+ ASSERT_NORMALIZE("a/../", "");
+ ASSERT_NORMALIZE("a/./../", "");
+
+ ASSERT_NORMALIZE("c:/", "c:\\");
+ ASSERT_NORMALIZE("c:/a", "c:\\a");
+ ASSERT_NORMALIZE("c:/foo/bar", "c:\\foo\\bar");
+ ASSERT_NORMALIZE("c:/foo/../bar", "c:\\bar");
+ ASSERT_NORMALIZE("d:/a/", "d:\\a");
+ ASSERT_NORMALIZE("D:/foo", "D:\\foo");
+ ASSERT_NORMALIZE("c:/foo/", "c:\\foo");
+ ASSERT_NORMALIZE("c:/.", "c:\\");
+ ASSERT_NORMALIZE("c:/./", "c:\\");
+ ASSERT_NORMALIZE("c:/..", "c:\\");
+ ASSERT_NORMALIZE("c:/../", "c:\\");
+ ASSERT_NORMALIZE("c:/./..", "c:\\");
+ ASSERT_NORMALIZE("c:/./../", "c:\\");
+ ASSERT_NORMALIZE("c:/../.", "c:\\");
+ ASSERT_NORMALIZE("c:/.././", "c:\\");
+ ASSERT_NORMALIZE("c:/...", "c:\\...");
+ ASSERT_NORMALIZE("c:/.../", "c:\\...");
+ ASSERT_NORMALIZE("c:/.a", "c:\\.a");
+ ASSERT_NORMALIZE("c:/..a", "c:\\..a");
+ ASSERT_NORMALIZE("c:/...a", "c:\\...a");
+ ASSERT_NORMALIZE("c:/./a", "c:\\a");
+ ASSERT_NORMALIZE("c:/././a", "c:\\a");
+ ASSERT_NORMALIZE("c:/./../a", "c:\\a");
+ ASSERT_NORMALIZE("c:/.././a", "c:\\a");
+ ASSERT_NORMALIZE("c:/../../a", "c:\\a");
+ ASSERT_NORMALIZE("c:/../.../a", "c:\\...\\a");
+ ASSERT_NORMALIZE("c:/.../../a", "c:\\a");
+ ASSERT_NORMALIZE("c:/a/..", "c:\\");
+ ASSERT_NORMALIZE("c:/a/../", "c:\\");
+ ASSERT_NORMALIZE("c:/a/./../", "c:\\");
+
+ ASSERT_NORMALIZE("foo", "foo");
+ ASSERT_NORMALIZE("foo/", "foo");
+ ASSERT_NORMALIZE("foo//bar", "foo\\bar");
+ ASSERT_NORMALIZE("../..//foo/./bar", "..\\..\\foo\\bar");
+ ASSERT_NORMALIZE("../foo/baz/../bar", "..\\foo\\bar");
+ ASSERT_NORMALIZE("c:", "c:\\");
+ ASSERT_NORMALIZE("c:/", "c:\\");
+ ASSERT_NORMALIZE("c:\\", "c:\\");
+ ASSERT_NORMALIZE("c:\\..//foo/./bar/", "c:\\foo\\bar");
+ ASSERT_NORMALIZE("../foo", "..\\foo");
+#undef ASSERT_NORMALIZE
}
TEST(PathWindowsTest, TestDirname) {
| val | train | 2018-09-13T17:09:19 | "2018-09-13T09:51:31Z" | laszlocsomor | test |
bazelbuild/bazel/6162_8821 | bazelbuild/bazel | bazelbuild/bazel/6162 | bazelbuild/bazel/8821 | [
"timestamp(timedelta=86914.0, similarity=0.8436393502010401)"
] | a988673b45c18d0d51e10e12d570dee348481afa | 9d69b734e019c6f7a10b3d25c0c88d76079e29cd | [
"Thanks for bringing this to my attention. We're actually in the middle of a documentation audit this week, and this is exactly the type of issue we want to flag."
] | [] | "2019-07-08T18:39:11Z" | [
"type: documentation (cleanup)",
"P2",
"team-Configurability"
] | Toolchain tutorial contradicts ToolchainInfo reference documentation | ### Description of the problem / feature request:
Reference documentation:
https://docs.bazel.build/versions/master/skylark/lib/platform_common.html#ToolchainInfo
> The provider constructor for ToolchainInfo. The constructor takes the type of the toolchain, and a map of the toolchain's data.
Tutorial:
https://docs.bazel.build/versions/master/toolchains.html#creating-a-toolchain-rule
```
def _my_toolchain_impl(ctx):
toolchain = platform_common.ToolchainInfo(
compiler = ctx.attr.compiler,
system_lib = ctx.attr.system_lib,
arch_flags = ctx.attr.arch_flags,
)
return [toolchain]
```
The tutorial doesn't call `ToolchainInfo` with the type of the toolchain at all, and doesn't pass in a map, just keyword arguments. I think the tutorial documents the correct usage.
| [
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/ToolchainInfoApi.java"
] | [
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/ToolchainInfoApi.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/ToolchainInfoApi.java b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/ToolchainInfoApi.java
index ab37760d34563f..868c2801950cfa 100644
--- a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/ToolchainInfoApi.java
+++ b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/ToolchainInfoApi.java
@@ -18,13 +18,12 @@
import com.google.devtools.build.lib.skylarkinterface.SkylarkModule;
import com.google.devtools.build.lib.skylarkinterface.SkylarkModuleCategory;
-/**
- * Info object representing data about a specific toolchain.
- */
+/** Info object representing data about a specific toolchain. */
@SkylarkModule(
name = "ToolchainInfo",
- doc = "Provides access to data about a specific toolchain.",
- category = SkylarkModuleCategory.PROVIDER
-)
-public interface ToolchainInfoApi extends StructApi {
-}
+ doc =
+ "Provider which allows rule-specific toolchains to communicate data back to the actual"
+ + " rule implementation. Read more about <a"
+ + " href='../../toolchains.$DOC_EXT'>toolchains</a> for more information.",
+ category = SkylarkModuleCategory.PROVIDER)
+public interface ToolchainInfoApi extends StructApi {}
| null | val | train | 2019-07-08T19:40:00 | "2018-09-16T01:44:39Z" | endobson | test |
bazelbuild/bazel/6162_8823 | bazelbuild/bazel | bazelbuild/bazel/6162 | bazelbuild/bazel/8823 | [
"timestamp(timedelta=1.0, similarity=0.8645373485183019)"
] | a988673b45c18d0d51e10e12d570dee348481afa | 88ffc8adddc0c1be28afa1395410c935eea34bc0 | [
"Thanks for bringing this to my attention. We're actually in the middle of a documentation audit this week, and this is exactly the type of issue we want to flag."
] | [] | "2019-07-08T18:39:31Z" | [
"type: documentation (cleanup)",
"P2",
"team-Configurability"
] | Toolchain tutorial contradicts ToolchainInfo reference documentation | ### Description of the problem / feature request:
Reference documentation:
https://docs.bazel.build/versions/master/skylark/lib/platform_common.html#ToolchainInfo
> The provider constructor for ToolchainInfo. The constructor takes the type of the toolchain, and a map of the toolchain's data.
Tutorial:
https://docs.bazel.build/versions/master/toolchains.html#creating-a-toolchain-rule
```
def _my_toolchain_impl(ctx):
toolchain = platform_common.ToolchainInfo(
compiler = ctx.attr.compiler,
system_lib = ctx.attr.system_lib,
arch_flags = ctx.attr.arch_flags,
)
return [toolchain]
```
The tutorial doesn't call `ToolchainInfo` with the type of the toolchain at all, and doesn't pass in a map, just keyword arguments. I think the tutorial documents the correct usage.
| [
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/PlatformCommonApi.java"
] | [
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/PlatformCommonApi.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/PlatformCommonApi.java b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/PlatformCommonApi.java
index 5db6e4652af868..e07a30b3d20c7f 100644
--- a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/PlatformCommonApi.java
+++ b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/platform/PlatformCommonApi.java
@@ -27,8 +27,8 @@ public interface PlatformCommonApi {
@SkylarkCallable(
name = "TemplateVariableInfo",
doc =
- "The provider used to retrieve the provider that contains the template variables "
- + "defined by a particular toolchain, for example by calling "
+ "The provider used to retrieve the provider that contains the template variables defined"
+ + " by a particular toolchain, for example by calling "
+ "ctx.attr._cc_toolchain[platform_common.TemplateVariableInfo].make_variables[<name>]",
structField = true)
ProviderApi getMakeVariableProvider();
@@ -36,8 +36,8 @@ public interface PlatformCommonApi {
@SkylarkCallable(
name = "ToolchainInfo",
doc =
- "The provider constructor for ToolchainInfo. The constructor takes the type of the "
- + "toolchain, and a map of the toolchain's data.",
+ "The provider constructor for ToolchainInfo. The constructor takes a map of the "
+ + "toolchain's data.",
structField = true)
ProviderApi getToolchainInfoConstructor();
| null | test | train | 2019-07-08T19:40:00 | "2018-09-16T01:44:39Z" | endobson | test |
bazelbuild/bazel/6193_6202 | bazelbuild/bazel | bazelbuild/bazel/6193 | bazelbuild/bazel/6202 | [
"timestamp(timedelta=0.0, similarity=0.9159548986968176)"
] | 7454417833dc240f6ba359ecb2539f19d8da625d | cf9049d5e5b5cdf7027a6b56b5284097ae4f9ae1 | [
"Just for completeness, which NDK revision are you on?",
"@jin r17b"
] | [] | "2018-09-21T15:16:11Z" | [
"team-Android",
"untriaged"
] | Cross-compiling for Android (arm) is missing debug symbols (-g) | ### Description of the problem / feature request:
According to the [Compilation Mode Docs](https://docs.bazel.build/versions/master/user-manual.html#flag--compilation_mode), building with `--compilation_mode=dbg` should include `--copt=-g` to request debug symbols.
When building for Android (arm), this flag is not passed to the compiler, and debug symbols are missing. When building for Android (x86), host, or iOS, this flag is passed correctly.
It's easy enough to add this to our `bazelrc`, but this behavior is inconsistent across the platforms and contrary to the docs so I thought I'd share.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Build an Android app with native library dependencies for arm architecture, observe the compiler invocations for the native library.
`./bazel-debug build //host/Applications/HeliosNativeAndroid/app:Helios --fat_apk_cpu=arm64-v8a -s`
### What operating system are you running Bazel on?
macOS 10.13.6
### What's the output of `bazel info release`?
`release 0.17.1`
| [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r10e/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r11/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r12/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r13/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r15/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r17/ArmCrosstools.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r10e/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r11/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r12/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r13/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r15/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r17/ArmCrosstools.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r10e/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r10e/ArmCrosstools.java
index b2a7c4a826f156..440b2c9fcd4e8e 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r10e/ArmCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r10e/ArmCrosstools.java
@@ -124,6 +124,7 @@ private CToolchain.Builder createAarch64Toolchain() {
.addCompilationModeFlags(CompilationModeFlags.newBuilder()
.setMode(CompilationMode.DBG)
.addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
.addCompilerFlag("-UNDEBUG")
.addCompilerFlag("-fno-omit-frame-pointer")
.addCompilerFlag("-fno-strict-aliasing"));
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r11/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r11/ArmCrosstools.java
index 75e452909b7229..17c03cab1a74fc 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r11/ArmCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r11/ArmCrosstools.java
@@ -108,6 +108,7 @@ private CToolchain.Builder createAarch64Toolchain() {
.addCompilationModeFlags(CompilationModeFlags.newBuilder()
.setMode(CompilationMode.DBG)
.addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
.addCompilerFlag("-UNDEBUG")
.addCompilerFlag("-fno-omit-frame-pointer")
.addCompilerFlag("-fno-strict-aliasing"));
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r12/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r12/ArmCrosstools.java
index e4c0480076c315..54ccc4ac34f560 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r12/ArmCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r12/ArmCrosstools.java
@@ -88,6 +88,7 @@ private CToolchain.Builder createAarch64Toolchain() {
CompilationModeFlags.newBuilder()
.setMode(CompilationMode.DBG)
.addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
.addCompilerFlag("-UNDEBUG"));
stlImpl.addStlImpl(toolchain, "4.9");
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r13/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r13/ArmCrosstools.java
index 6578cc4f3e0cb7..32477426692807 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r13/ArmCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r13/ArmCrosstools.java
@@ -94,6 +94,7 @@ private CToolchain.Builder createAarch64ClangToolchain() {
CompilationModeFlags.newBuilder()
.setMode(CompilationMode.DBG)
.addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
.addCompilerFlag("-UNDEBUG"));
stlImpl.addStlImpl(toolchain, "4.9");
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r15/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r15/ArmCrosstools.java
index cf69457ae0159c..867e0386afc5ca 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r15/ArmCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r15/ArmCrosstools.java
@@ -99,6 +99,7 @@ private CToolchain.Builder createAarch64ClangToolchain() {
CompilationModeFlags.newBuilder()
.setMode(CompilationMode.DBG)
.addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
.addCompilerFlag("-UNDEBUG"));
stlImpl.addStlImpl(toolchain, "4.9");
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r17/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r17/ArmCrosstools.java
index eb6a0fec7fa226..cf05cf590044d9 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r17/ArmCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r17/ArmCrosstools.java
@@ -103,6 +103,7 @@ private CToolchain.Builder createAarch64ClangToolchain() {
CompilationModeFlags.newBuilder()
.setMode(CompilationMode.DBG)
.addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
.addCompilerFlag("-UNDEBUG"));
}
| null | train | train | 2018-09-21T15:28:12 | "2018-09-20T18:43:52Z" | jgavris | test |
bazelbuild/bazel/6212_6213 | bazelbuild/bazel | bazelbuild/bazel/6212 | bazelbuild/bazel/6213 | [
"timestamp(timedelta=0.0, similarity=0.9232423870207832)"
] | c1a7b4c574f956c385de5c531383bcab2e01cadd | 6482fcfad739813ddc734646b556b551f4fc7c9a | [] | [] | "2018-09-24T12:05:54Z" | [
"type: bug",
"platform: linux"
] | runfiles, python: runfiles library doesn't work for sandboxed binaries | If a `py_binary` runs in a sandbox and uses Bazel's runfiles library (in `@bazel_tools//tools/python/runfiles`), the library fails to initialize.
Repro:
1. create a py_binary with a data-dependency that uses the runfiles library to look up the runfile
2. create a genrule, add the py_binary to its `tools`
3. in the genrule's cmd, run the py_binary
4. build with sandboxing enabled; observe that it fails to init the runfiles library
Bazel 0.17.2 on Linux with sandboxing enabled. | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt"
] | [
"src/test/py/bazel/BUILD",
"src/test/py/bazel/runfiles_sandboxed_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
index b4ab41f3312f39..d5fb78fafc3dc3 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt
@@ -126,6 +126,11 @@ def RunfilesEnvvar(module_space):
if os.path.exists(runfiles):
return ('RUNFILES_DIR', runfiles)
+ # If running in a sandbox and no environment variables are set, then
+ # Look for the runfiles next to the binary.
+ if module_space.endswith('.runfiles') and os.path.isdir(module_space):
+ return ('RUNFILES_DIR', module_space)
+
return (None, None)
def Main():
| diff --git a/src/test/py/bazel/BUILD b/src/test/py/bazel/BUILD
index 57a1671d2f968d..18807473d0bf84 100644
--- a/src/test/py/bazel/BUILD
+++ b/src/test/py/bazel/BUILD
@@ -120,6 +120,18 @@ py_test(
],
)
+py_test(
+ name = "runfiles_sandboxed_test",
+ timeout = "long",
+ srcs = ["runfiles_sandboxed_test.py"],
+ data = glob(["testdata/runfiles_test/**"]),
+ deps = [":test_base"],
+ tags = [
+ # Windows does not support sandboxing yet.
+ "no_windows",
+ ],
+)
+
py_test(
name = "bazel_windows_cpp_test",
size = "large",
diff --git a/src/test/py/bazel/runfiles_sandboxed_test.py b/src/test/py/bazel/runfiles_sandboxed_test.py
new file mode 100644
index 00000000000000..c8e492482ae305
--- /dev/null
+++ b/src/test/py/bazel/runfiles_sandboxed_test.py
@@ -0,0 +1,120 @@
+# pylint: disable=g-bad-file-header
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import unittest
+from src.test.py.bazel import test_base
+
+
+class RunfilesSandboxedTest(test_base.TestBase):
+
+ def _FailWithContents(self, msg, contents):
+ self.fail("%s\ncontents =\n | %s\n---" % (msg, "\n | ".join(contents)))
+
+ def testRunfilesLibrariesFindRunfilesWithoutEnvvars(self):
+ for s, t, exe in [
+ ("WORKSPACE.mock", "WORKSPACE", False),
+ ("bar/BUILD.mock", "bar/BUILD", False),
+ ("bar/bar.py", "bar/bar.py", True),
+ ("bar/bar-py-data.txt", "bar/bar-py-data.txt", False),
+ ("bar/Bar.java", "bar/Bar.java", False),
+ ("bar/bar-java-data.txt", "bar/bar-java-data.txt", False),
+ ("bar/bar.sh", "bar/bar.sh", True),
+ ("bar/bar-sh-data.txt", "bar/bar-sh-data.txt", False),
+ ("bar/bar.cc", "bar/bar.cc", False),
+ ("bar/bar-cc-data.txt", "bar/bar-cc-data.txt", False),
+ ]:
+ self.CopyFile(
+ self.Rlocation("io_bazel/src/test/py/bazel/testdata/runfiles_test/" +
+ s), t, exe)
+ self.ScratchFile("foo/BUILD", [
+ "genrule(",
+ " name = 'gen',",
+ " outs = ['stdout.txt', 'data_files.txt'],",
+ " cmd = 'cat $$(' + ",
+ # The genrule runs all bar-<language> tools, saves the complete stdout
+ # into stdout.txt, and prints the contents of rlocations reported by the
+ # tools (i.e. the contents of the bar-<language>-data.txt files) into
+ # data_files.txt.
+ " ' ( $(location //bar:bar-py) && ' +",
+ " ' $(location //bar:bar-java) && ' +",
+ " ' $(location //bar:bar-sh) && ' +",
+ " ' $(location //bar:bar-cc) ; ' +",
+ " ' ) | ' + ",
+ " ' tee $(location stdout.txt) | ' + ",
+ " ' grep \"^rloc=\" | ' + ",
+ " ' sed \"s,^rloc=,,\"' + ",
+ " ') > $(location data_files.txt)',",
+ " tools = [",
+ " '//bar:bar-cc',",
+ " '//bar:bar-java',",
+ " '//bar:bar-py',",
+ " '//bar:bar-sh',",
+ " ],",
+ ")"])
+
+ exit_code, stdout, stderr = self.RunBazel(["info", "bazel-genfiles"])
+ self.AssertExitCode(exit_code, 0, stderr)
+ bazel_genfiles = stdout[0]
+
+ exit_code, _, stderr = self.RunBazel([
+ "build", "--verbose_failures",
+ "//foo:gen", "--genrule_strategy=sandboxed",
+ ])
+ self.AssertExitCode(exit_code, 0, stderr)
+
+ stdout_txt = os.path.join(bazel_genfiles, "foo/stdout.txt")
+ self.assertTrue(os.path.isfile(stdout_txt))
+
+ data_files_txt = os.path.join(bazel_genfiles, "foo/data_files.txt")
+ self.assertTrue(os.path.isfile(data_files_txt))
+
+ # Output of the bar-<language> binaries that they printed to stdout.
+ stdout_lines = []
+ with open(stdout_txt, "rt") as f:
+ stdout_lines = [line.strip() for line in f.readlines()]
+
+ # Contents of the bar-<language>-data.txt files.
+ data_files = []
+ with open(data_files_txt, "rt") as f:
+ data_files = [line.strip() for line in f.readlines()]
+
+ if len(stdout_lines) != 8:
+ self._FailWithContents("wrong number of output lines", stdout_lines)
+ i = 0
+ for lang in [("py", "Python", "bar.py"), ("java", "Java", "Bar.java"),
+ ("sh", "Bash", "bar.sh"), ("cc", "C++", "bar.cc")]:
+ # Check that the bar-<language> binary printed the expected output.
+ if stdout_lines[i * 2] != "Hello %s Bar!" % lang[1]:
+ self._FailWithContents("wrong line for " + lang[1], stdout_lines)
+ if not stdout_lines[i * 2 + 1].startswith("rloc="):
+ self._FailWithContents("wrong line for " + lang[1], stdout_lines)
+ if not stdout_lines[i * 2 + 1].endswith(
+ "foo_ws/bar/bar-%s-data.txt" % lang[0]):
+ self._FailWithContents("wrong line for " + lang[1], stdout_lines)
+
+ # Assert the contents of bar-<language>-data.txt. This indicates that
+ # the runfiles library in the bar-<language> binary found the correct
+ # runfile and returned a valid path.
+ if data_files[i] != "data for " + lang[2]:
+ self._FailWithContents("runfile does not exist for " + lang[1],
+ stdout_lines)
+
+ i += 1
+
+
+if __name__ == "__main__":
+ unittest.main()
+
| test | train | 2018-09-24T14:45:38 | "2018-09-24T11:21:29Z" | laszlocsomor | test |
bazelbuild/bazel/6223_6287 | bazelbuild/bazel | bazelbuild/bazel/6223 | bazelbuild/bazel/6287 | [
"timestamp(timedelta=0.0, similarity=0.8708933620718008)"
] | 645a35e1ce0f9f0025e9120399f2e7b77b4841b8 | 483fb2af62fe399aed2916e4d6c54cf1f3da3a67 | [
"`DEVELOPER_DIR` is also missing from the persistent worker env here",
"Ok I think I discovered why this is the case. When building locally we hit this codepath: https://github.com/bazelbuild/bazel/blob/18bd7dec9609ff8924d9ebed5f14be523df4eec0/src/main/java/com/google/devtools/build/lib/sandbox/DarwinSandboxedSpawnRunner.java#L224-L225 which adds the variables we want from here https://github.com/bazelbuild/bazel/blob/1f684e1b87cd8881a0a4b33e86ba66743e32d674/src/main/java/com/google/devtools/build/lib/exec/apple/XcodeLocalEnvProvider.java#L66-L108 but persistent workers don't call this local env rewrite logic https://github.com/bazelbuild/bazel/blob/5a1ed1f24e74f8a608ee145133f399c1f34a8390/src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnRunner.java#L131 meaning they don't add the variables we were hoping for.\r\n\r\nI'm not really sure what an acceptable solution for this is since I don't think normally we'd want to pass persistent workers the local environment logic, but in this case it's required for quite a few arguments.",
"@allevato assuming you have some context on these, any thoughts?",
"I've run into the same problem in my worker prototype, and my solution was to hack it by having my wrapper set DEVELOPER_DIR and SDKROOT by querying xcode-select/xcrun manually if they're not already set. Not ideal.",
"Sounds like a problem with persistent workers. @keith wanna send us a patch? :-) cc: @philwo ",
"@buchgr I'm happy to submit that fix, but is that a reasonable one? Just based on the naming tying the local environment objects to the persistent workers sounds like they're intentionally attached",
"I've submitted a PR that fixes it in this way, please let me know what you think! https://github.com/bazelbuild/bazel/pull/6287"
] | [
"I've seen some different things passed for `/tmp` here, I assume there's something other than this to be more platform agnostic that I should pass?"
] | "2018-10-01T23:32:01Z" | [] | Some environment variables not passed to persistent workers | I'm working on creating a persistent worker to support incremental compilation [for Swift](https://github.com/bazelbuild/rules_swift/issues/48). In doing so, the first issue I hit, was the lack of required environment variables being passed to the newly created persistent workers.
When running the builds normally, this is the environment passed to the build:
```
DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
TMPDIR=/var/folders/5b/bs2_gmk512147rfb9c6278f80000gp/T/
SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator12.0.sdk
XCODE_VERSION_OVERRIDE=10.0.0
__CF_USER_TEXT_ENCODING=0x1F6:0x0:0x0
PWD=/private/var/tmp/_bazel_...
SHLVL=1
APPLE_SDK_PLATFORM=iPhoneSimulator
APPLE_SDK_VERSION_OVERRIDE=12.0
```
But the persistent workers are launched with this environment:
```
XCODE_VERSION_OVERRIDE=10.0.0
PWD=/private/var/tmp/_bazel_...
SHLVL=1
APPLE_SDK_PLATFORM=iPhoneSimulator
APPLE_SDK_VERSION_OVERRIDE=12.0
```
This results in the underlying [script](https://github.com/bazelbuild/rules_swift/blob/c8138ccf8cd798aefc9533840fcab72546e4c46c/tools/wrappers/xcrunwrapper.sh#L38) to fail since `SDKROOT` is required but not defined.
Is this variable intentionally excluded from persistent workers? Or is there a place we need to whitelist this variable to be passed along? I am testing with bazel 0.17.1 | [
"src/main/java/com/google/devtools/build/lib/worker/WorkerModule.java",
"src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnRunner.java"
] | [
"src/main/java/com/google/devtools/build/lib/worker/WorkerModule.java",
"src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnRunner.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/worker/WorkerModule.java b/src/main/java/com/google/devtools/build/lib/worker/WorkerModule.java
index 46bb0dc554547c..df23d6d5d8ad0f 100644
--- a/src/main/java/com/google/devtools/build/lib/worker/WorkerModule.java
+++ b/src/main/java/com/google/devtools/build/lib/worker/WorkerModule.java
@@ -140,13 +140,15 @@ public void executorInit(CommandEnvironment env, BuildRequest request, ExecutorB
Preconditions.checkNotNull(workerPool);
ImmutableMultimap<String, String> extraFlags =
ImmutableMultimap.copyOf(env.getOptions().getOptions(WorkerOptions.class).workerExtraFlags);
+ LocalEnvProvider localEnvProvider = createLocalEnvProvider(env);
WorkerSpawnRunner spawnRunner =
new WorkerSpawnRunner(
env.getExecRoot(),
workerPool,
extraFlags,
env.getReporter(),
- createFallbackRunner(env),
+ createFallbackRunner(env, localEnvProvider),
+ localEnvProvider,
env.getOptions()
.getOptions(SandboxOptions.class)
.symlinkedSandboxExpandsTreeArtifactsInRunfilesTree);
@@ -156,15 +158,9 @@ public void executorInit(CommandEnvironment env, BuildRequest request, ExecutorB
builder.addStrategyByContext(SpawnActionContext.class, "worker");
}
- private static SpawnRunner createFallbackRunner(CommandEnvironment env) {
+ private static SpawnRunner createFallbackRunner(CommandEnvironment env, LocalEnvProvider localEnvProvider) {
LocalExecutionOptions localExecutionOptions =
env.getOptions().getOptions(LocalExecutionOptions.class);
- LocalEnvProvider localEnvProvider =
- OS.getCurrent() == OS.DARWIN
- ? new XcodeLocalEnvProvider(env.getClientEnv())
- : (OS.getCurrent() == OS.WINDOWS
- ? new WindowsLocalEnvProvider(env.getClientEnv())
- : new PosixLocalEnvProvider(env.getClientEnv()));
return new LocalSpawnRunner(
env.getExecRoot(),
localExecutionOptions,
@@ -172,6 +168,14 @@ private static SpawnRunner createFallbackRunner(CommandEnvironment env) {
localEnvProvider);
}
+ private static LocalEnvProvider createLocalEnvProvider(CommandEnvironment env) {
+ return OS.getCurrent() == OS.DARWIN
+ ? new XcodeLocalEnvProvider(env.getClientEnv())
+ : (OS.getCurrent() == OS.WINDOWS
+ ? new WindowsLocalEnvProvider(env.getClientEnv())
+ : new PosixLocalEnvProvider(env.getClientEnv()));
+ }
+
@Subscribe
public void buildComplete(BuildCompleteEvent event) {
if (options != null && options.workerQuitAfterBuild) {
diff --git a/src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnRunner.java
index 9b1c8652e38562..50473f2967a0c8 100644
--- a/src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/worker/WorkerSpawnRunner.java
@@ -19,7 +19,6 @@
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.hash.HashCode;
@@ -37,6 +36,7 @@
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.exec.SpawnRunner;
+import com.google.devtools.build.lib.exec.local.LocalEnvProvider;
import com.google.devtools.build.lib.sandbox.SandboxHelpers;
import com.google.devtools.build.lib.util.io.FileOutErr;
import com.google.devtools.build.lib.vfs.Path;
@@ -76,6 +76,7 @@ final class WorkerSpawnRunner implements SpawnRunner {
private final Multimap<String, String> extraFlags;
private final EventHandler reporter;
private final SpawnRunner fallbackRunner;
+ private final LocalEnvProvider localEnvProvider;
private final boolean sandboxUsesExpandedTreeArtifactsInRunfiles;
public WorkerSpawnRunner(
@@ -84,12 +85,14 @@ public WorkerSpawnRunner(
Multimap<String, String> extraFlags,
EventHandler reporter,
SpawnRunner fallbackRunner,
+ LocalEnvProvider localEnvProvider,
boolean sandboxUsesExpandedTreeArtifactsInRunfiles) {
this.execRoot = execRoot;
this.workers = Preconditions.checkNotNull(workers);
this.extraFlags = extraFlags;
this.reporter = reporter;
this.fallbackRunner = fallbackRunner;
+ this.localEnvProvider = localEnvProvider;
this.sandboxUsesExpandedTreeArtifactsInRunfiles = sandboxUsesExpandedTreeArtifactsInRunfiles;
}
@@ -128,7 +131,8 @@ private SpawnResult actuallyExec(Spawn spawn, SpawnExecutionContext context)
// its args and put them into the WorkRequest instead.
List<String> flagFiles = new ArrayList<>();
ImmutableList<String> workerArgs = splitSpawnArgsIntoWorkerArgsAndFlagFiles(spawn, flagFiles);
- ImmutableMap<String, String> env = spawn.getEnvironment();
+ Map<String, String> env =
+ localEnvProvider.rewriteLocalEnv(spawn.getEnvironment(), execRoot, "/tmp");
MetadataProvider inputFileCache = context.getMetadataProvider();
| null | train | train | 2018-10-01T22:05:13 | "2018-09-24T21:53:21Z" | keith | test |
bazelbuild/bazel/6257_6258 | bazelbuild/bazel | bazelbuild/bazel/6257 | bazelbuild/bazel/6258 | [
"timestamp(timedelta=0.0, similarity=0.9999999999999998)"
] | 4348e3ca10f6e2bc1bed925c51524ed78d0059ef | null | [] | [
"Can you use CppFileTypes.C_SOURCE + CPP_SOURCE?",
"That means packing an additional dependency into bazel_tools which makes the binary bigger. I copied those values to Constants.CC_EXTENSIONS and use it here to check if the file is a cc file."
] | "2018-09-26T12:31:49Z" | [
"P2",
"coverage",
"team-Rules-CPP"
] | Include coverage results for cc binaries called from sh_test in the Bazel coverage output file | Currently Bazel only outputs coverage results for java binaries called within a sh_test. | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/sh/BazelShTestRule.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/sh/ShBinary.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/sh/BazelShTestRule.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/sh/ShBinary.java"
] | [
"src/test/shell/bazel/bazel_coverage_test.sh",
"tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Constants.java",
"tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Coverage.java",
"tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Main.java",
"tools/test/CoverageOutputGenerator/javatests/com/google/devtools/coverageoutputgenerator/CoverageTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/BazelShTestRule.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/BazelShTestRule.java
index 45f5203c76f1e8..c969e4578e22a3 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/BazelShTestRule.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/BazelShTestRule.java
@@ -40,7 +40,14 @@ public RuleClass build(RuleClass.Builder builder, RuleDefinitionEnvironment envi
attr("$lcov_merger", LABEL)
.value(
Label.parseAbsoluteUnchecked(
- "@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main")));
+ "@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main")))
+ // Add the script as an attribute in order for sh_test to output code coverage results for
+ // code covered by CC binaries invocations.
+ .add(
+ attr("$collect_cc_coverage", LABEL)
+ .cfg(HostTransition.INSTANCE)
+ .singleArtifact()
+ .value(environment.getToolsLabel("//tools/test:collect_cc_coverage")));
return builder.build();
}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/ShBinary.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/ShBinary.java
index 894cb16e2099e1..7da47f292a8f38 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/ShBinary.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/sh/ShBinary.java
@@ -14,8 +14,10 @@
package com.google.devtools.build.lib.bazel.rules.sh;
import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
+import com.google.devtools.build.lib.analysis.AnalysisEnvironment;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder;
import com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory;
@@ -30,9 +32,12 @@
import com.google.devtools.build.lib.analysis.configuredtargets.RuleConfiguredTarget.Mode;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector.InstrumentationSpec;
+import com.google.devtools.build.lib.analysis.test.InstrumentedFilesCollector.LocalMetadataCollector;
import com.google.devtools.build.lib.analysis.test.InstrumentedFilesProvider;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
+import com.google.devtools.build.lib.rules.cpp.CppCompileAction;
+import com.google.devtools.build.lib.rules.cpp.CppFileTypes;
import com.google.devtools.build.lib.util.FileTypeSet;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.vfs.PathFragment;
@@ -96,12 +101,33 @@ public ConfiguredTarget create(RuleContext ruleContext)
InstrumentedFilesProvider.class,
InstrumentedFilesCollector.collect(
ruleContext,
- new InstrumentationSpec(FileTypeSet.NO_FILE),
- InstrumentedFilesCollector.NO_METADATA_COLLECTOR,
+ new InstrumentationSpec(FileTypeSet.ANY_FILE,"srcs", "deps", "data"),
+ CC_METADATA_COLLECTOR,
filesToBuild))
.build();
}
+ // Collects coverage metadata (.gcno files) for the artifacts that are generated by C++ rules.
+ private static final LocalMetadataCollector CC_METADATA_COLLECTOR =
+ new LocalMetadataCollector() {
+ @Override
+ public void collectMetadataArtifacts(
+ Iterable<Artifact> artifacts,
+ AnalysisEnvironment analysisEnvironment,
+ NestedSetBuilder<Artifact> metadataFilesBuilder) {
+ for (Artifact artifact : artifacts) {
+ ActionAnalysisMetadata action = analysisEnvironment.getLocalGeneratingAction(artifact);
+ if (action instanceof CppCompileAction) {
+ addOutputs(metadataFilesBuilder, action, CppFileTypes.COVERAGE_NOTES);
+ } else if (action != null) {
+ // Recurse on inputs.
+ collectMetadataArtifacts(
+ action.getInputs(), analysisEnvironment, metadataFilesBuilder);
+ }
+ }
+ }
+ };
+
private static boolean isWindowsExecutable(Artifact artifact) {
return artifact.getExtension().equals("exe")
|| artifact.getExtension().equals("cmd")
| diff --git a/src/test/shell/bazel/bazel_coverage_test.sh b/src/test/shell/bazel/bazel_coverage_test.sh
index a725d214aec057..fa8bf021bc9b8c 100755
--- a/src/test/shell/bazel/bazel_coverage_test.sh
+++ b/src/test/shell/bazel/bazel_coverage_test.sh
@@ -77,7 +77,7 @@ function assert_coverage_result() {
local expected_coverage_no_newlines="$( echo "$expected_coverage" | tr '\n' ',' )"
local output_file_no_newlines="$( cat "$output_file" | tr '\n' ',' )"
- ( echo $output_file_no_newlines | grep $expected_coverage_no_newlines ) \
+ ( echo "$output_file_no_newlines" | grep -F "$expected_coverage_no_newlines" ) \
|| fail "Expected coverage result
<$expected_coverage>
was not found in actual coverage report:
@@ -625,4 +625,418 @@ EOF
cmp result.dat "$coverage_file_path" || fail "Coverage output file is different than the expected file"
}
+function test_sh_test_coverage_cc_binary() {
+ local -r gcov_location=$(which gcov)
+ if [[ ! -x ${gcov_location:-/usr/bin/gcov} ]]; then
+ echo "gcov not installed. Skipping test."
+ return
+ fi
+
+ "$gcov_location" -version | grep "LLVM" && \
+ echo "gcov LLVM version not supported. Skipping test." && return
+ # gcov -v | grep "gcov" outputs a line that looks like this:
+ # gcov (Debian 7.3.0-5) 7.3.0
+ local gcov_version="$(gcov -v | grep "gcov" | cut -d " " -f 4 | cut -d "." -f 1)"
+ [ "$gcov_version" -lt 7 ] \
+ && echo "gcov version before 7.0 is not supported. Skipping test." \
+ && return
+
+ ########### Setup source files and BUILD file ###########
+ cat <<EOF > BUILD
+sh_test(
+ name = "hello-sh",
+ srcs = ["hello-test.sh"],
+ data = ["//examples/cpp:hello-world"]
+)
+EOF
+ cat <<EOF > hello-test.sh
+#!/bin/bash
+
+examples/cpp/hello-world
+EOF
+ chmod +x hello-test.sh
+
+ mkdir -p examples/cpp
+
+ cat <<EOF > examples/cpp/BUILD
+package(default_visibility = ["//visibility:public"])
+
+cc_binary(
+ name = "hello-world",
+ srcs = ["hello-world.cc"],
+ deps = [":hello-lib"],
+)
+
+cc_library(
+ name = "hello-lib",
+ srcs = ["hello-lib.cc"],
+ hdrs = ["hello-lib.h"]
+)
+EOF
+
+ cat <<EOF > examples/cpp/hello-world.cc
+#include "examples/cpp/hello-lib.h"
+
+#include <string>
+
+using hello::HelloLib;
+using std::string;
+
+int main(int argc, char** argv) {
+ HelloLib lib("Hello");
+ string thing = "world";
+ if (argc > 1) {
+ thing = argv[1];
+ }
+ lib.greet(thing);
+ return 0;
+}
+EOF
+
+ cat <<EOF > examples/cpp/hello-lib.h
+#ifndef EXAMPLES_CPP_HELLO_LIB_H_
+#define EXAMPLES_CPP_HELLO_LIB_H_
+
+#include <string>
+#include <memory>
+
+namespace hello {
+
+class HelloLib {
+ public:
+ explicit HelloLib(const std::string &greeting);
+
+ void greet(const std::string &thing);
+
+ private:
+ std::auto_ptr<const std::string> greeting_;
+};
+
+} // namespace hello
+
+#endif // EXAMPLES_CPP_HELLO_LIB_H_
+EOF
+
+ cat <<EOF > examples/cpp/hello-lib.cc
+#include "examples/cpp/hello-lib.h"
+
+#include <iostream>
+
+using std::cout;
+using std::endl;
+using std::string;
+
+namespace hello {
+
+HelloLib::HelloLib(const string& greeting) : greeting_(new string(greeting)) {
+}
+
+void HelloLib::greet(const string& thing) {
+ cout << *greeting_ << " " << thing << endl;
+}
+
+} // namespace hello
+EOF
+
+ ########### Run bazel coverage ###########
+ bazel coverage --experimental_cc_coverage --test_output=all \
+ //:hello-sh &>$TEST_log || fail "Coverage for //:orange-sh failed"
+
+ ########### Assert coverage results. ###########
+ local coverage_file_path="$( get_coverage_file_path_from_test_log )"
+ local expected_result_hello_lib="SF:examples/cpp/hello-lib.cc
+FN:18,_GLOBAL__sub_I_hello_lib.cc
+FN:18,_Z41__static_initialization_and_destruction_0ii
+FN:14,_ZN5hello8HelloLib5greetERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FN:11,_ZN5hello8HelloLibC2ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FNDA:1,_GLOBAL__sub_I_hello_lib.cc
+FNDA:1,_Z41__static_initialization_and_destruction_0ii
+FNDA:1,_ZN5hello8HelloLib5greetERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FNDA:1,_ZN5hello8HelloLibC2ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FNF:4
+FNH:4
+BA:11,2
+BA:18,2
+BRF:2
+BRH:2
+DA:11,1
+DA:12,1
+DA:14,1
+DA:15,1
+DA:16,1
+DA:18,3
+LH:6
+LF:6
+end_of_record"
+ assert_coverage_result "$expected_result_hello_lib" "$coverage_file_path"
+
+ local coverage_result_hello_lib_header="SF:examples/cpp/hello-world.cc
+FN:8,main
+FNDA:1,main
+FNF:1
+FNH:1
+BA:9,2
+BA:10,2
+BA:11,2
+BA:12,0
+BA:14,2
+BRF:5
+BRH:4
+DA:8,1
+DA:9,2
+DA:10,2
+DA:11,1
+DA:12,0
+DA:14,1
+DA:15,1
+LH:6
+LF:7
+end_of_record"
+ assert_coverage_result "$coverage_result_hello_lib_header" "$coverage_file_path"
+}
+
+function test_sh_test_coverage_cc_binary_and_java_binary() {
+local -r gcov_location=$(which gcov)
+ if [[ ! -x ${gcov_location:-/usr/bin/gcov} ]]; then
+ echo "gcov not installed. Skipping test."
+ return
+ fi
+
+ "$gcov_location" -version | grep "LLVM" && \
+ echo "gcov LLVM version not supported. Skipping test." && return
+ # gcov -v | grep "gcov" outputs a line that looks like this:
+ # gcov (Debian 7.3.0-5) 7.3.0
+ local gcov_version="$(gcov -v | grep "gcov" | cut -d " " -f 4 | cut -d "." -f 1)"
+ [ "$gcov_version" -lt 7 ] \
+ && echo "gcov version before 7.0 is not supported. Skipping test." \
+ && return
+
+ ########### Setup source files and BUILD file ###########
+ cat <<EOF > BUILD
+sh_test(
+ name = "hello-sh",
+ srcs = ["hello-test.sh"],
+ data = [
+ "//examples/cpp:hello-world",
+ "//java/com/google/orange:orange-bin"
+ ]
+)
+EOF
+ cat <<EOF > hello-test.sh
+#!/bin/bash
+
+examples/cpp/hello-world
+java/com/google/orange/orange-bin
+EOF
+ chmod +x hello-test.sh
+
+ mkdir -p examples/cpp
+
+ cat <<EOF > examples/cpp/BUILD
+package(default_visibility = ["//visibility:public"])
+
+cc_binary(
+ name = "hello-world",
+ srcs = ["hello-world.cc"],
+ deps = [":hello-lib"],
+)
+
+cc_library(
+ name = "hello-lib",
+ srcs = ["hello-lib.cc"],
+ hdrs = ["hello-lib.h"]
+)
+EOF
+
+ cat <<EOF > examples/cpp/hello-world.cc
+#include "examples/cpp/hello-lib.h"
+
+#include <string>
+
+using hello::HelloLib;
+using std::string;
+
+int main(int argc, char** argv) {
+ HelloLib lib("Hello");
+ string thing = "world";
+ if (argc > 1) {
+ thing = argv[1];
+ }
+ lib.greet(thing);
+ return 0;
+}
+EOF
+
+ cat <<EOF > examples/cpp/hello-lib.h
+#ifndef EXAMPLES_CPP_HELLO_LIB_H_
+#define EXAMPLES_CPP_HELLO_LIB_H_
+
+#include <string>
+#include <memory>
+
+namespace hello {
+
+class HelloLib {
+ public:
+ explicit HelloLib(const std::string &greeting);
+
+ void greet(const std::string &thing);
+
+ private:
+ std::auto_ptr<const std::string> greeting_;
+};
+
+} // namespace hello
+
+#endif // EXAMPLES_CPP_HELLO_LIB_H_
+EOF
+
+ cat <<EOF > examples/cpp/hello-lib.cc
+#include "examples/cpp/hello-lib.h"
+
+#include <iostream>
+
+using std::cout;
+using std::endl;
+using std::string;
+
+namespace hello {
+
+HelloLib::HelloLib(const string& greeting) : greeting_(new string(greeting)) {
+}
+
+void HelloLib::greet(const string& thing) {
+ cout << *greeting_ << " " << thing << endl;
+}
+
+} // namespace hello
+EOF
+
+ ########### Setup Java sources ###########
+ mkdir -p java/com/google/orange
+
+ cat <<EOF > java/com/google/orange/BUILD
+package(default_visibility = ["//visibility:public"])
+java_binary(
+ name = "orange-bin",
+ srcs = ["orangeBin.java"],
+ main_class = "com.google.orange.orangeBin",
+ deps = [":orange-lib"],
+)
+java_library(
+ name = "orange-lib",
+ srcs = ["orangeLib.java"],
+)
+EOF
+
+ cat <<EOF > java/com/google/orange/orangeLib.java
+package com.google.orange;
+public class orangeLib {
+ public void print() {
+ System.out.println("orange prints a message!");
+ }
+}
+EOF
+
+ cat <<EOF > java/com/google/orange/orangeBin.java
+package com.google.orange;
+public class orangeBin {
+ public static void main(String[] args) {
+ orangeLib orange = new orangeLib();
+ orange.print();
+ }
+}
+EOF
+
+ ########### Run bazel coverage ###########
+ bazel coverage --experimental_cc_coverage --test_output=all \
+ //:hello-sh &>$TEST_log || fail "Coverage for //:orange-sh failed"
+
+ ########### Assert coverage results. ###########
+ local coverage_file_path="$( get_coverage_file_path_from_test_log )"
+ local expected_result_hello_lib="SF:examples/cpp/hello-lib.cc
+FN:18,_GLOBAL__sub_I_hello_lib.cc
+FN:18,_Z41__static_initialization_and_destruction_0ii
+FN:14,_ZN5hello8HelloLib5greetERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FN:11,_ZN5hello8HelloLibC2ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FNDA:1,_GLOBAL__sub_I_hello_lib.cc
+FNDA:1,_Z41__static_initialization_and_destruction_0ii
+FNDA:1,_ZN5hello8HelloLib5greetERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FNDA:1,_ZN5hello8HelloLibC2ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
+FNF:4
+FNH:4
+BA:11,2
+BA:18,2
+BRF:2
+BRH:2
+DA:11,1
+DA:12,1
+DA:14,1
+DA:15,1
+DA:16,1
+DA:18,3
+LH:6
+LF:6
+end_of_record"
+ assert_coverage_result "$expected_result_hello_lib" "$coverage_file_path"
+
+ local coverage_result_hello_lib_header="SF:examples/cpp/hello-world.cc
+FN:8,main
+FNDA:1,main
+FNF:1
+FNH:1
+BA:9,2
+BA:10,2
+BA:11,2
+BA:12,0
+BA:14,2
+BRF:5
+BRH:4
+DA:8,1
+DA:9,2
+DA:10,2
+DA:11,1
+DA:12,0
+DA:14,1
+DA:15,1
+LH:6
+LF:7
+end_of_record"
+ assert_coverage_result "$coverage_result_hello_lib_header" "$coverage_file_path"
+
+
+ ############# Assert Java code coverage results
+
+ local coverage_result_orange_bin="SF:com/google/orange/orangeBin.java
+FN:2,com/google/orange/orangeBin::<init> ()V
+FN:4,com/google/orange/orangeBin::main ([Ljava/lang/String;)V
+FNDA:0,com/google/orange/orangeBin::<init> ()V
+FNDA:1,com/google/orange/orangeBin::main ([Ljava/lang/String;)V
+FNF:2
+FNH:1
+DA:2,0
+DA:4,4
+DA:5,2
+DA:6,1
+LH:3
+LF:4
+end_of_record"
+ assert_coverage_result "$coverage_result_orange_bin" "$coverage_file_path"
+
+ local coverage_result_orange_lib="SF:com/google/orange/orangeLib.java
+FN:2,com/google/orange/orangeLib::<init> ()V
+FN:4,com/google/orange/orangeLib::print ()V
+FNDA:1,com/google/orange/orangeLib::<init> ()V
+FNDA:1,com/google/orange/orangeLib::print ()V
+FNF:2
+FNH:2
+DA:2,3
+DA:4,3
+DA:5,1
+LH:3
+LF:3
+end_of_record"
+ assert_coverage_result "$coverage_result_orange_lib" "$coverage_file_path"
+}
+
run_suite "test tests"
diff --git a/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Constants.java b/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Constants.java
index 13adcc6a5581d9..728fb37f8ecbdc 100644
--- a/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Constants.java
+++ b/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Constants.java
@@ -14,6 +14,8 @@
package com.google.devtools.coverageoutputgenerator;
+import com.google.common.collect.ImmutableList;
+
/**
* Stores markers used by the lcov tracefile and gcov intermediate format file. See <a
* href="http://ltp.sourceforge.net/coverage/lcov/geninfo.1.php">lcov documentation</a> and the flag
@@ -48,4 +50,6 @@ class Constants {
static final String GCOV_BRANCH_NOTEXEC = "notexec";
static final String GCOV_BRANCH_NOTTAKEN = "taken";
static final String GCOV_BRANCH_TAKEN = "nottaken";
+ static final ImmutableList<String> CC_EXTENSIONS = ImmutableList.of(
+ ".cc", ".cpp", ".cxx", ".c++", ".C", ".c", ".h", ".hh", ".hpp", ".ipp", ".hxx", ".inc");
}
diff --git a/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Coverage.java b/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Coverage.java
index 484e9870f6c1da..f24290ac8f1305 100644
--- a/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Coverage.java
+++ b/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Coverage.java
@@ -14,6 +14,8 @@
package com.google.devtools.coverageoutputgenerator;
+import static com.google.devtools.coverageoutputgenerator.Constants.CC_EXTENSIONS;
+
import java.util.Collection;
import java.util.List;
import java.util.Set;
@@ -48,13 +50,13 @@ static Coverage merge(Coverage c1, Coverage c2) {
}
/**
- * Returns {@link Coverage} only for the given source filenames, filtering out everything else in
- * the given coverage.
+ * Returns {@link Coverage} only for the given CC source filenames, filtering out every other CC
+ * sources the given coverage. Other type of source files (e.g. Java) will not be filtered out.
*
* @param coverage The initial coverage.
* @param sourcesToKeep The filenames of the sources to keep from the initial coverage.
*/
- static Coverage getOnlyTheseSources(Coverage coverage, Set<String> sourcesToKeep) {
+ static Coverage getOnlyTheseCcSources(Coverage coverage, Set<String> sourcesToKeep) {
if (coverage == null || sourcesToKeep == null) {
throw new IllegalArgumentException("Coverage and sourcesToKeep should not be null.");
}
@@ -66,13 +68,23 @@ static Coverage getOnlyTheseSources(Coverage coverage, Set<String> sourcesToKeep
}
Coverage finalCoverage = new Coverage();
for (SourceFileCoverage source : coverage.getAllSourceFiles()) {
- if (sourcesToKeep.contains(source.sourceFileName())) {
+ if (!isCcSourceFile(source.sourceFileName())
+ || sourcesToKeep.contains(source.sourceFileName())) {
finalCoverage.add(source);
}
}
return finalCoverage;
}
+ private static boolean isCcSourceFile(String filename) {
+ for (String ccExtension : CC_EXTENSIONS) {
+ if (filename.endsWith(ccExtension)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
static Coverage filterOutMatchingSources(Coverage coverage, List<String> regexes)
throws IllegalArgumentException {
if (coverage == null || regexes == null) {
diff --git a/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Main.java b/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Main.java
index 897732374d7b59..019943c8997746 100644
--- a/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Main.java
+++ b/tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator/Main.java
@@ -112,7 +112,7 @@ public static void main(String[] args) {
Set<String> ccSources = getCcSourcesFromSourceFileManifest(flags.sourceFileManifest());
if (!ccSources.isEmpty()) {
// Only filter out coverage if there were C++ sources found in the coverage manifest.
- coverage = Coverage.getOnlyTheseSources(coverage, ccSources);
+ coverage = Coverage.getOnlyTheseCcSources(coverage, ccSources);
}
}
diff --git a/tools/test/CoverageOutputGenerator/javatests/com/google/devtools/coverageoutputgenerator/CoverageTest.java b/tools/test/CoverageOutputGenerator/javatests/com/google/devtools/coverageoutputgenerator/CoverageTest.java
index 00d4a178f652e6..5e8e9599ffbd69 100644
--- a/tools/test/CoverageOutputGenerator/javatests/com/google/devtools/coverageoutputgenerator/CoverageTest.java
+++ b/tools/test/CoverageOutputGenerator/javatests/com/google/devtools/coverageoutputgenerator/CoverageTest.java
@@ -191,18 +191,18 @@ public void testGetOnlyTheseSources() {
assertThat(
getSourceFileNames(
- Coverage.getOnlyTheseSources(coverage, sourcesToKeep).getAllSourceFiles()))
+ Coverage.getOnlyTheseCcSources(coverage, sourcesToKeep).getAllSourceFiles()))
.containsExactly("source/common/protobuf/utility.cc", "source/common/grpc/common.cc");
}
@Test(expected = IllegalArgumentException.class)
public void testGetOnlyTheseSourcesNullCoverage() {
- Coverage.getOnlyTheseSources(null, new HashSet<>());
+ Coverage.getOnlyTheseCcSources(null, new HashSet<>());
}
@Test(expected = IllegalArgumentException.class)
public void testGetOnlyTheseSourcesNullSources() {
- Coverage.getOnlyTheseSources(new Coverage(), null);
+ Coverage.getOnlyTheseCcSources(new Coverage(), null);
}
@Test
@@ -213,7 +213,7 @@ public void testGetOnlyTheseSourcesEmptySources() {
coverage.add(new SourceFileCoverage("source/server/options.cc"));
coverage.add(new SourceFileCoverage("source/server/manager.cc"));
- assertThat(Coverage.getOnlyTheseSources(coverage, new HashSet<>()).getAllSourceFiles())
+ assertThat(Coverage.getOnlyTheseCcSources(coverage, new HashSet<>()).getAllSourceFiles())
.isEmpty();
}
}
| train | train | 2018-09-26T14:18:55 | "2018-09-26T12:20:14Z" | iirina | test |
bazelbuild/bazel/6271_6936 | bazelbuild/bazel | bazelbuild/bazel/6271 | bazelbuild/bazel/6936 | [
"timestamp(timedelta=21605.0, similarity=0.9246448239924371)"
] | c67dceca77a93646961fc4bb863826e344fda5e0 | 7f3b91a3f332af569a0c062d66518a9feae8a255 | [
"Sounds like a great idea!",
"Just hit this too. It looks like the fix is trivial (adding a no-op `doc` parameter), so I've mailed https://github.com/bazelbuild/bazel/pull/6936 . Note that rules using this param won't work with any older Bazel versions."
] | [] | "2018-12-15T18:40:58Z" | [
"type: feature request",
"P2",
"team-ExternalDeps"
] | `repository_rule` should have a `doc` argument | `repository_rule` is similar to `rule`, except it lives on the `WORKSPACE` level. `rule` has a nice `doc` attribute which is extracted by documentation tools. It would be nice if `repository_rule` followed suit.
In [`rules_nixpkgs`](https://github.com/tweag/rules_nixpkgs) and [`rules_haskell`](https://github.com/tweag/rules_haskell) we have to resort to [manually written docs](https://github.com/tweag/rules_nixpkgs/blob/master/README.md#rules-1), which tend go out of sync easily. | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java",
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java",
"src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java",
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java",
"src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java"
] | [
"src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java
index 31846125fc0e6b..d68fff2a12eac6 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java
@@ -61,7 +61,8 @@ public BaseFunction repositoryRule(
Boolean local,
SkylarkList<String> environ,
FuncallExpression ast,
- com.google.devtools.build.lib.syntax.Environment funcallEnv)
+ com.google.devtools.build.lib.syntax.Environment funcallEnv,
+ String doc)
throws EvalException {
SkylarkUtils.checkLoadingOrWorkspacePhase(funcallEnv, "repository_rule", ast.getLocation());
// We'll set the name later, pass the empty string for now.
diff --git a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java
index 36728cb4856864..fdc5e9313e7278 100644
--- a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java
+++ b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java
@@ -78,6 +78,15 @@ public interface RepositoryModuleApi {
+ "an environment variable in that list change, the repository will be "
+ "refetched.",
named = true,
+ positional = false),
+ @Param(
+ name = "doc",
+ type = String.class,
+ defaultValue = "''",
+ doc =
+ "A description of the repository rule that can be extracted by documentation "
+ + "generating tools."
+ named = true,
positional = false)
},
useAst = true,
@@ -88,6 +97,7 @@ public BaseFunction repositoryRule(
Boolean local,
SkylarkList<String> environ,
FuncallExpression ast,
- Environment env)
+ Environment env,
+ String doc)
throws EvalException;
}
diff --git a/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java b/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java
index 8f22cb7585ca11..abee2f3b8f9f23 100644
--- a/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java
+++ b/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java
@@ -27,7 +27,7 @@ public class FakeRepositoryModule implements RepositoryModuleApi {
@Override
public BaseFunction repositoryRule(BaseFunction implementation, Object attrs, Boolean local,
- SkylarkList<String> environ, FuncallExpression ast, Environment env) {
+ SkylarkList<String> environ, FuncallExpression ast, Environment env, String doc) {
return implementation;
}
}
| diff --git a/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl b/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl
index d083028376cf84..24a75a703bd7d2 100644
--- a/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl
+++ b/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl
@@ -8,7 +8,10 @@ def my_rule_impl(ctx):
def exercise_the_api():
var1 = config_common.FeatureFlagInfo
var2 = platform_common.TemplateVariableInfo
- var3 = repository_rule(implementation = my_rule_impl)
+ var3 = repository_rule(
+ implementation = my_rule_impl,
+ doc = "This repository rule has documentation.",
+ )
var4 = testing.ExecutionInfo({})
exercise_the_api()
| train | train | 2019-01-17T20:26:01 | "2018-09-28T16:07:35Z" | Profpatsch | test |
bazelbuild/bazel/6271_7401 | bazelbuild/bazel | bazelbuild/bazel/6271 | bazelbuild/bazel/7401 | [
"timestamp(timedelta=1.0, similarity=0.9242516503873975)"
] | 5263093ee0cae01e2dd7a36ed83f29bb90850c12 | 0c4541e618d148a6617232147d4b652f27394f35 | [
"Sounds like a great idea!",
"Just hit this too. It looks like the fix is trivial (adding a no-op `doc` parameter), so I've mailed https://github.com/bazelbuild/bazel/pull/6936 . Note that rules using this param won't work with any older Bazel versions."
] | [] | "2019-02-12T11:51:47Z" | [
"type: feature request",
"P2",
"team-ExternalDeps"
] | `repository_rule` should have a `doc` argument | `repository_rule` is similar to `rule`, except it lives on the `WORKSPACE` level. `rule` has a nice `doc` attribute which is extracted by documentation tools. It would be nice if `repository_rule` followed suit.
In [`rules_nixpkgs`](https://github.com/tweag/rules_nixpkgs) and [`rules_haskell`](https://github.com/tweag/rules_haskell) we have to resort to [manually written docs](https://github.com/tweag/rules_nixpkgs/blob/master/README.md#rules-1), which tend go out of sync easily. | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java",
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java",
"src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java",
"src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java",
"src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java"
] | [
"src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java
index a1532dad894b31..61e3884706789c 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/skylark/SkylarkRepositoryModule.java
@@ -60,6 +60,7 @@ public BaseFunction repositoryRule(
Object attrs,
Boolean local,
SkylarkList<String> environ,
+ String doc,
FuncallExpression ast,
com.google.devtools.build.lib.syntax.Environment funcallEnv)
throws EvalException {
diff --git a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java
index 36728cb4856864..b41304bfbdb5e7 100644
--- a/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java
+++ b/src/main/java/com/google/devtools/build/lib/skylarkbuildapi/repository/RepositoryModuleApi.java
@@ -78,6 +78,15 @@ public interface RepositoryModuleApi {
+ "an environment variable in that list change, the repository will be "
+ "refetched.",
named = true,
+ positional = false),
+ @Param(
+ name = "doc",
+ type = String.class,
+ defaultValue = "''",
+ doc =
+ "A description of the repository rule that can be extracted by documentation "
+ + "generating tools.",
+ named = true,
positional = false)
},
useAst = true,
@@ -87,6 +96,7 @@ public BaseFunction repositoryRule(
Object attrs,
Boolean local,
SkylarkList<String> environ,
+ String doc,
FuncallExpression ast,
Environment env)
throws EvalException;
diff --git a/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java b/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java
index 8f22cb7585ca11..8f72a4ebbb52f8 100644
--- a/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java
+++ b/src/main/java/com/google/devtools/build/skydoc/fakebuildapi/repository/FakeRepositoryModule.java
@@ -27,7 +27,7 @@ public class FakeRepositoryModule implements RepositoryModuleApi {
@Override
public BaseFunction repositoryRule(BaseFunction implementation, Object attrs, Boolean local,
- SkylarkList<String> environ, FuncallExpression ast, Environment env) {
+ SkylarkList<String> environ, String doc, FuncallExpression ast, Environment env) {
return implementation;
}
}
| diff --git a/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl b/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl
index d083028376cf84..24a75a703bd7d2 100644
--- a/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl
+++ b/src/test/java/com/google/devtools/build/skydoc/testdata/misc_apis_test/input.bzl
@@ -8,7 +8,10 @@ def my_rule_impl(ctx):
def exercise_the_api():
var1 = config_common.FeatureFlagInfo
var2 = platform_common.TemplateVariableInfo
- var3 = repository_rule(implementation = my_rule_impl)
+ var3 = repository_rule(
+ implementation = my_rule_impl,
+ doc = "This repository rule has documentation.",
+ )
var4 = testing.ExecutionInfo({})
exercise_the_api()
| train | train | 2019-02-12T12:41:53 | "2018-09-28T16:07:35Z" | Profpatsch | test |
bazelbuild/bazel/6297_8097 | bazelbuild/bazel | bazelbuild/bazel/6297 | bazelbuild/bazel/8097 | [
"timestamp(timedelta=65146.0, similarity=0.9342796586228654)"
] | a626990141cb77cc7e7973596fce4db7031e92a6 | 21f1c93e527f6c567ee1f8160c66e7b94b75c8f2 | [
"r19 beta 2 is available, r19 is expected to ship soon.\r\n\r\nhttps://developer.android.com/ndk/downloads/",
"NDK 19 has dropped: https://developer.android.com/ndk/downloads/#stable-downloads",
"Link to changelog: https://github.com/android-ndk/ndk/wiki/Changelog-r19",
"After speaking with @hlopko, the right way forward here is to implement the NDK CROSSTOOL in Starlark. This isn't a necessary blocker for NDK 19, since we can adapt the NDK 18 configuration for 19, but it would be nice to turn down proto CROSSTOOL generation to move to the modern approach.\r\n\r\n@hlopko's suggestion:\r\n\r\n> write a rule ndk_cc_toolchain_config that has attributes for things that are different between versions, and only instantiate that in BUILD files.\r\n\r\nMore information: \r\n\r\n- https://github.com/bazelbuild/bazel/issues/7320\r\n- https://docs.bazel.build/versions/master/cc-toolchain-config-reference.html\r\n",
"@jin do you plan on supporting `lld` too ?",
"@steeve definitely. We want the Android rules to be 100% compatible with the recommended set of tools in the NDK.",
"The NDK CROSSTOOL has been ported to Starlark with massive help from @hlopko - thanks!\r\n\r\nGoing through the [changelog](https://github.com/android-ndk/ndk/wiki/Changelog-r19):\r\n\r\n> # Announcements\r\n\r\n> Developers should begin testing their apps with LLD. AOSP has switched to using LLD by default and the NDK will use it by default in the next release. BFD and Gold will be removed once LLD has been through a release cycle with no major unresolved issues (estimated r21). Test LLD in your app by passing -fuse-ld=lld when linking.\r\n \r\n> Note: lld does not currently support compressed symbols on Windows. See Issue 888. Clang also cannot generate compressed symbols on Windows, but this can be a problem when using artifacts built from Darwin or Linux.\r\n\r\nWe will need to add support for this.\r\n\r\n> The Play Store will require 64-bit support when uploading an APK beginning in August 2019. Start porting now to avoid surprises when the time comes. For more information, see this blog post.\r\n\r\nWe may want to add a warning message about this when building for non-64-bit.\r\n\r\n> Issue 780: Standalone toolchains are now unnecessary. Clang, binutils, the sysroot, and other toolchain pieces are now all installed to $NDK/toolchains/llvm/prebuilt/<host-tag> and Clang will automatically find them. Instead of creating a standalone toolchain for API 26 ARM, instead invoke the compiler directly from the NDK:\r\n> \r\n> $ $NDK/toolchains/llvm/prebuilt/<host-tag>/bin/armv7a-linux-androideabi26-clang++ src.cpp\r\n> For r19 the toolchain is also installed to the old path to give build systems a chance to adapt to the new layout. The old paths will be removed in r20.\r\n\r\nWe must definitely support this, but the effects of it should be transparent to end users. It's not clear what the impact of having a standalone toolchain will be on the Starlark crosstool configuration.\r\n \r\n> The make_standalone_toolchain.py script will not be removed. It is now unnecessary and will emit a warning with the above information, but the script will remain to preserve existing workflows.\r\n\r\nNot applicable, we don't use this.\r\n\r\n> If you're using ndk-build, CMake, or a standalone toolchain, there should be no change to your workflow. This change is meaningful for maintainers of third-party build systems, who should now be able to delete some Android-specific code. For more information, see the Build System Maintainers guide.\r\n\r\nMore reading: https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md\r\n\r\n> ndk-depends has been removed. We believe that ReLinker is a better solution to native library loading issues on old Android versions.\r\n\r\nNot applicable, we don't use this.\r\n\r\n> Issue 862: The GCC wrapper scripts which redirected to Clang have been removed, as they are not functional enough to be drop in replacements.\r\n\r\nThis should be addressed by the standalone toolchain support.\r\n\r\n---\r\n\r\n> r19c\r\n> ----\r\n> \r\n> * [Issue 912]: Prevent the CMake toolchain file from clobbering a user\r\n> specified `CMAKE_FIND_ROOT_PATH`.\r\n> * [Issue 920]: Fix clang wrapper scripts on Windows.\r\n> \r\n> [Issue 912]: https://github.com/android-ndk/ndk/issues/912\r\n> [Issue 920]: https://github.com/android-ndk/ndk/issues/920\r\n> \r\n> r19b\r\n> ----\r\n> \r\n> * [Issue 855]: ndk-build automatically disables multithreaded linking for LLD\r\n> on Windows, where it may hang. It is not possible for the NDK to detect this\r\n> situation for CMake, so CMake users and custom build systems must pass\r\n> `-Wl,--no-threads` when linking with LLD on Windows.\r\n\r\nWe'll need to take note of this for the `lld` support.\r\n\r\n> * [Issue 849]: Fixed unused command line argument warning when using standalone\r\n> toolchains to compile C code.\r\n> * [Issue 890]: Fixed `CMAKE_FIND_ROOT_PATH`. CMake projects will no longer\r\n> search the host's sysroot for headers and libraries.\r\n> * [Issue 906]: Explicitly set `-march=armv7-a` for 32-bit ARM to workaround\r\n> Clang not setting that flag automatically when using `-fno-integrated-as`.\r\n> This fix only affects ndk-build and CMake. Standalone toolchains and custom\r\n> build systems will need to apply this fix themselves.\r\n> * [Issue 907]: Fixed `find_path` for NDK headers in CMake.\r\n> \r\n> [Issue 849]: https://github.com/android-ndk/ndk/issues/849\r\n> [Issue 890]: https://github.com/android-ndk/ndk/issues/890\r\n> [Issue 907]: https://github.com/android-ndk/ndk/issues/907\r\n> \r\n> Changes\r\n> -------\r\n> \r\n> * Updated Clang to r339409.\r\n> * C++ compilation now defaults to C++14.\r\n\r\nNeed to update default std to `-std=c++14`.\r\n\r\n> * [Issue 780]: A complete NDK toolchain is now installed to the Clang\r\n> directory. See the announcements section for more information.\r\n> * ndk-build no longer removes artifacts from `NDK_LIBS_OUT` for ABIs not\r\n> present in `APP_ABI`. This enables workflows like the following:\r\n> \r\n> ```bash\r\n> for abi in armeabi-v7a arm64-v8a x86 x86_64; do\r\n> ndk-build APP_ABI=$abi\r\n> done\r\n> ```\r\n> \r\n> Prior to this change, the above workflow would remove the previously built\r\n> ABI's artifacts on each successive build, resulting in only x86_64 being\r\n> present at the end of the loop.\r\n> * ndk-stack has been rewritten in Python.\r\n> * [Issue 776]: To better support LLD, ndk-build and CMake no longer pass\r\n> `-Wl,--fix-cortex-a8` by default.\r\n> * CPUs that require this fix are uncommon in the NDK's supported API range\r\n> (16+).\r\n> * If you need to continue supporting these devices, add\r\n> `-Wl,--fix-cortex-a8` to your `APP_LDFLAGS` or `CMAKE_C_FLAGS`, but note\r\n> that LLD will not be adding support for this workaround.\r\n> * Alternatively, use the Play Console to [blacklist] Cortex-A8 CPUs to\r\n> disallow your app from being installed on those devices.\r\n\r\nOur ARM crosstool add this `--fix-cortex-a8` linker flag, so we should drop them here.\r\n\r\n```\r\nsrc/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ArmCrosstools.java\r\n149: .addLinkerFlag(\"-Wl,--fix-cortex-a8\")\r\n```\r\n\r\n> * [Issue 798]: The ndk-build and CMake options to disable RelRO and noexecstack\r\n> are now ignored. All code is built with RelRO and non-executable stacks.\r\n\r\nNot sure how/if we do this, will need to investigate.\r\n\r\n> * [Issue 294]: All code is now built with a subset of [compiler-rt] to provide\r\n> a complete set of compiler built-ins for Clang.\r\n> \r\n> [Issue 294]: https://github.com/android-ndk/ndk/issues/294\r\n> [Issue 776]: https://github.com/android-ndk/ndk/issues/776\r\n> [Issue 798]: https://github.com/android-ndk/ndk/issues/798\r\n> [blacklist]: https://support.google.com/googleplay/android-developer/answer/7353455?hl=en\r\n> [compiler-rt]: https://compiler-rt.llvm.org/\r\n> \r\n> Known Issues\r\n> ------------\r\n> \r\n> * This is not intended to be a comprehensive list of all outstanding bugs.\r\n> * [Issue 888]: lld does not support compressed symbols on Windows. Clang also\r\n> cannot generate compressed symbols on Windows, but this can be a problem when\r\n> using artifacts built from Darwin or Linux.\r\n> * [Issue 360]: `thread_local` variables with non-trivial destructors will cause\r\n> segfaults if the containing library is `dlclose`ed on devices running M or\r\n> newer, or devices before M when using a static STL. The simple workaround is\r\n> to not call `dlclose`.\r\n> * [Issue 70838247]: Gold emits broken debug information for AArch64. AArch64\r\n> still uses BFD by default.\r\n> * [Issue 855]: LLD may hang on Windows when using multithreaded linking.\r\n> ndk-build will automatically disable multithreaded linking in this situation,\r\n> but CMake users and custom build systems should pass `-Wl,--no-threads` when\r\n> using LLD on Windows. The other linkers and operating systems are unaffected.\r\n\r\nAddressed above.\r\n\r\n> * [Issue 884]: Third-party build systems must pass `-fno-addrsig` to Clang for\r\n> compatibility with binutils. ndk-build, CMake, and standalone toolchains\r\n> handle this automatically.\r\n\r\nLooks like standalone toolchains support this, but will be good to verify.\r\n\r\n> * [Issue 906]: Clang does not pass `-march=armv7-a` to the assembler when using\r\n> `-fno-integrated-as`. This results in the assembler generating ARMv5\r\n> instructions. Note that by default Clang uses the integrated assembler which\r\n> does not have this problem. To workaround this issue, explicitly use\r\n> `-march=armv7-a` when building for 32-bit ARM with the non-integrated\r\n> assembler, or use the integrated assembler. ndk-build and CMake already\r\n> contain these workarounds.\r\n\r\nWe'll need to add this workaround.\r\n\r\n> * This version of the NDK is incompatible with the Android Gradle plugin\r\n> version 3.0 or older. If you see an error like\r\n> `No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android`,\r\n> update your project file to [use plugin version 3.1 or newer]. You will also\r\n> need to upgrade to Android Studio 3.1 or newer.\r\n> \r\n> [Issue 360]: https://github.com/android-ndk/ndk/issues/360\r\n> [Issue 70838247]: https://issuetracker.google.com/70838247\r\n> [Issue 855]: https://github.com/android-ndk/ndk/issues/855\r\n> [Issue 884]: https://github.com/android-ndk/ndk/issues/884\r\n> [Issue 888]: https://github.com/android-ndk/ndk/issues/888\r\n> [Issue 906]: https://github.com/android-ndk/ndk/issues/906\r\n> [use plugin version 3.1 or newer]: https://developer.android.com/studio/releases/gradle-plugin#updating-plugin\r\n\r\n\r\n",
"Addressed in https://github.com/bazelbuild/bazel/pull/8524"
] | [] | "2019-04-18T22:07:45Z" | [
"type: feature request",
"P1",
"team-Android"
] | Support NDK r19 | Expected release: Q4 2018
Changes: https://android.googlesource.com/platform/ndk/+/master/docs/Roadmap.md#ndk-r19
* Make all toolchains be standalone toolchains
> Now that the NDK is down to a single compiler and STL, if we just taught the Clang driver to emit -D__ANDROID_API__=foo and to link libc.so.18 instead of libc.so, standalone toolchains would be obsolete because the compiler would already be a standalone toolchain. The NDK toolchain would Just Work regardless of build system, and the logic contained in each build system could be greatly reduced.
> Related to this (but maybe occurring in a later release), we'll want to switch from libgcc to libcompiler-rt and our own unwinder.
> See the corresponding bug make all toolchains standalone toolchains for detailed discussion of the implementation and sub-tasks. | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java",
"src/test/shell/bazel/android/android_ndk_integration_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
index d595dfe5b340d2..ab4bd6e30dd20a 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
@@ -23,6 +23,7 @@
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r15.NdkMajorRevisionR15;
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r17.NdkMajorRevisionR17;
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18.NdkMajorRevisionR18;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19.NdkMajorRevisionR19;
import com.google.devtools.build.lib.util.OS;
import java.util.Map;
@@ -50,6 +51,7 @@ private AndroidNdkCrosstools() {}
.put(16, new NdkMajorRevisionR15("5.0.300080")) // no changes relevant to Bazel
.put(17, new NdkMajorRevisionR17("6.0.2"))
.put(18, new NdkMajorRevisionR18("7.0.2"))
+ .put(19, new NdkMajorRevisionR19("8.0.1"))
.build();
public static final Map.Entry<Integer, NdkMajorRevision> LATEST_KNOWN_REVISION =
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java
new file mode 100644
index 00000000000000..5fc2c6945b1d83
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java
@@ -0,0 +1,78 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Generates a CrosstoolRelease proto for the Android NDK. */
+final class AndroidNdkCrosstoolsR19 {
+
+ /**
+ * Creates a CrosstoolRelease proto for the Android NDK, given the API level to use and the
+ * release revision. The crosstools are generated through code rather than checked in as a flat
+ * file to reduce the amount of templating needed (for parameters like the release name and
+ * certain paths), to reduce duplication, and to make it easier to support future versions of the
+ * NDK. TODO(bazel-team): Eventually we should move this into Skylark so the crosstools can be
+ * updated independently of Bazel itself.
+ *
+ * @return A CrosstoolRelease for the Android NDK.
+ */
+ static CrosstoolRelease create(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+ return CrosstoolRelease.newBuilder()
+ .setMajorVersion("android")
+ .setMinorVersion("")
+ .setDefaultTargetCpu("armeabi")
+ .addAllToolchain(createToolchains(ndkPaths, stlImpl, hostPlatform, clangVersion))
+ .build();
+ }
+
+ private static ImmutableList<CToolchain> createToolchains(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+
+ List<CToolchain.Builder> toolchainBuilders = new ArrayList<>();
+ toolchainBuilders.addAll(new ArmCrosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+ toolchainBuilders.addAll(new X86Crosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+
+ ImmutableList.Builder<CToolchain> toolchains = new ImmutableList.Builder<>();
+
+ // Set attributes common to all toolchains.
+ for (CToolchain.Builder toolchainBuilder : toolchainBuilders) {
+ toolchainBuilder
+ .setHostSystemName(hostPlatform)
+ .setTargetLibc("local")
+ .setAbiVersion(toolchainBuilder.getTargetCpu())
+ .setAbiLibcVersion("local");
+
+ // builtin_sysroot is set individually on each toolchain.
+ // platforms/arch sysroot
+ toolchainBuilder.addCxxBuiltinIncludeDirectory("%sysroot%/usr/include");
+ toolchainBuilder.addCxxBuiltinIncludeDirectory(
+ ndkPaths.createBuiltinSysroot() + "/usr/include");
+ toolchainBuilder.addUnfilteredCxxFlag(
+ "-isystem%ndk%/usr/include".replace("%ndk%", ndkPaths.createBuiltinSysroot()));
+
+ toolchains.add(toolchainBuilder.build());
+ }
+
+ return toolchains.build();
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java
new file mode 100644
index 00000000000000..cdcee9caba93a1
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java
@@ -0,0 +1,61 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.events.EventHandler;
+
+/** Class which encodes information from the Android NDK makefiles about API levels. */
+final class ApiLevelR19 extends ApiLevel {
+ /** This is the contents of {@code platforms/android-*} */
+ private static final ImmutableListMultimap<String, String> API_LEVEL_TO_ARCHITECTURES =
+ ImmutableListMultimap.<String, String>builder()
+ .putAll("16", "arm", "x86")
+ .putAll("17", "arm", "x86")
+ .putAll("18", "arm", "x86")
+ .putAll("19", "arm", "x86")
+ .putAll("21", "arm", "x86", "arm64", "x86_64")
+ .putAll("22", "arm", "x86", "arm64", "x86_64")
+ .putAll("23", "arm", "x86", "arm64", "x86_64")
+ .putAll("24", "arm", "x86", "arm64", "x86_64")
+ .putAll("26", "arm", "x86", "arm64", "x86_64")
+ .putAll("27", "arm", "x86", "arm64", "x86_64")
+ .putAll("28", "arm", "x86", "arm64", "x86_64")
+ .build();
+
+ /** This map fill in the gaps of {@code API_LEVEL_TO_ARCHITECTURES}. */
+ private static final ImmutableMap<String, String> API_EQUIVALENCIES =
+ ImmutableMap.<String, String>builder()
+ .put("16", "16")
+ .put("17", "16")
+ .put("18", "18")
+ .put("19", "19")
+ .put("20", "19")
+ .put("21", "21")
+ .put("22", "22")
+ .put("23", "23")
+ .put("24", "24")
+ .put("25", "24")
+ .put("26", "26")
+ .put("27", "27")
+ .put("28", "28")
+ .build();
+
+ ApiLevelR19(EventHandler eventHandler, String repositoryName, String apiLevel) {
+ super(API_LEVEL_TO_ARCHITECTURES, API_EQUIVALENCIES, eventHandler, repositoryName, apiLevel);
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java
new file mode 100644
index 00000000000000..f88ee6672219fb
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java
@@ -0,0 +1,172 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for ARM. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class ArmCrosstools {
+ private final NdkPaths ndkPaths;
+ private final StlImpl stlImpl;
+ private final String clangVersion;
+
+ ArmCrosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+ this.ndkPaths = ndkPaths;
+ this.stlImpl = stlImpl;
+ this.clangVersion = clangVersion;
+ }
+
+ ImmutableList<CToolchain.Builder> createCrosstools() {
+ CToolchain.Builder aarch64Toolchain = createAarch64ClangToolchain();
+ CToolchain.Builder armeabiToolchain = createArmeabiClangToolchain();
+
+ stlImpl.addStlImpl(aarch64Toolchain, "4.9");
+ stlImpl.addStlImpl(armeabiToolchain, "4.9");
+
+ return ImmutableList.<CToolchain.Builder>builder()
+ .add(aarch64Toolchain)
+ .add(armeabiToolchain)
+ .build();
+ }
+
+ private CToolchain.Builder createAarch64ClangToolchain() {
+ String toolchainName = "aarch64-linux-android-4.9";
+ String targetPlatform = "aarch64-linux-android";
+ String gccToolchain = ndkPaths.createGccToolchainPath(toolchainName);
+ String llvmTriple = "aarch64-none-linux-android";
+
+ return CToolchain.newBuilder()
+ .setToolchainIdentifier("aarch64-linux-android-clang" + clangVersion)
+ .setTargetSystemName(targetPlatform)
+ .setTargetCpu("arm64-v8a")
+ .setCompiler("clang" + clangVersion)
+ .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm64"))
+
+ // Compiler flags
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-target")
+ .addCompilerFlag(llvmTriple)
+ .addCompilerFlag("-ffunction-sections")
+ .addCompilerFlag("-funwind-tables")
+ .addCompilerFlag("-fstack-protector-strong")
+ .addCompilerFlag("-fpic")
+ .addCompilerFlag("-Wno-invalid-command-line-argument")
+ .addCompilerFlag("-Wno-unused-command-line-argument")
+ .addCompilerFlag("-no-canonical-prefixes")
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", targetPlatform))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+
+ // Linker flags
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-target")
+ .addLinkerFlag(llvmTriple)
+ .addLinkerFlag("-no-canonical-prefixes")
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-O2")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-UNDEBUG"));
+ }
+
+ private CToolchain.Builder createArmeabiClangToolchain() {
+ String toolchainName = "arm-linux-androideabi-4.9";
+ String targetPlatform = "arm-linux-androideabi";
+ String gccToolchain = ndkPaths.createGccToolchainPath("arm-linux-androideabi-4.9");
+
+ return CToolchain.newBuilder()
+ .setToolchainIdentifier("arm-linux-androideabi-clang" + clangVersion + "-v7a")
+ .setTargetCpu("armeabi-v7a")
+ .setTargetSystemName("arm-linux-androideabi")
+ .setCompiler("clang" + clangVersion)
+ .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm"))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", targetPlatform))
+
+ // Compiler flags
+ .addCompilerFlag("-target")
+ .addCompilerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+ .addCompilerFlag("-march=armv7-a")
+ .addCompilerFlag("-mfloat-abi=softfp")
+ .addCompilerFlag("-mfpu=vfpv3-d16")
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-fpic")
+ .addCompilerFlag("-ffunction-sections")
+ .addCompilerFlag("-funwind-tables")
+ .addCompilerFlag("-fstack-protector-strong")
+ .addCompilerFlag("-Wno-invalid-command-line-argument")
+ .addCompilerFlag("-Wno-unused-command-line-argument")
+ .addCompilerFlag("-no-canonical-prefixes")
+
+ // Linker flags
+ .addLinkerFlag("-target")
+ .addLinkerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+ .addLinkerFlag("-Wl,--fix-cortex-a8")
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-no-canonical-prefixes")
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-mthumb")
+ .addCompilerFlag("-Os")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-fno-strict-aliasing")
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-UNDEBUG"));
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java
new file mode 100644
index 00000000000000..067475d8391d7a
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java
@@ -0,0 +1,42 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkMajorRevision;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.events.EventHandler;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+
+/** Logic specific to Android NDK R17. */
+public class NdkMajorRevisionR19 implements NdkMajorRevision {
+ private final String clangVersion;
+
+ public NdkMajorRevisionR19(String clangVersion) {
+ this.clangVersion = clangVersion;
+ }
+
+ @Override
+ public CrosstoolRelease crosstoolRelease(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform) {
+ return AndroidNdkCrosstoolsR19.create(ndkPaths, stlImpl, hostPlatform, clangVersion);
+ }
+
+ @Override
+ public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
+ return new ApiLevelR19(eventHandler, name, apiLevel);
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java
new file mode 100644
index 00000000000000..a3c24fe2276682
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java
@@ -0,0 +1,118 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for x86. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class X86Crosstools {
+ private final NdkPaths ndkPaths;
+ private final StlImpl stlImpl;
+ private final String clangVersion;
+
+ X86Crosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+ this.ndkPaths = ndkPaths;
+ this.stlImpl = stlImpl;
+ this.clangVersion = clangVersion;
+ }
+
+ ImmutableList<CToolchain.Builder> createCrosstools() {
+ /** x86 */
+ // clang
+ CToolchain.Builder x86Clang =
+ createBaseX86ClangToolchain("x86", "i686", "i686-linux-android")
+ // Workaround for https://code.google.com/p/android/issues/detail?id=220159.
+ .addCompilerFlag("-mstackrealign")
+ .setToolchainIdentifier("x86-clang" + clangVersion)
+ .setTargetCpu("x86")
+ .addAllToolPath(ndkPaths.createClangToolpaths("x86-4.9", "i686-linux-android", null))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86"));
+
+ stlImpl.addStlImpl(x86Clang, null);
+
+ /** x86_64 */
+ CToolchain.Builder x8664Clang =
+ createBaseX86ClangToolchain("x86_64", "x86_64", "x86_64-linux-android")
+ .setToolchainIdentifier("x86_64-clang" + clangVersion)
+ .setTargetCpu("x86_64")
+ .addAllToolPath(
+ ndkPaths.createClangToolpaths("x86_64-4.9", "x86_64-linux-android", null))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86_64"));
+
+ stlImpl.addStlImpl(x8664Clang, null);
+
+ return ImmutableList.of(x86Clang, x8664Clang);
+ }
+
+ private CToolchain.Builder createBaseX86ClangToolchain(
+ String x86Arch, String llvmArch, String triple) {
+ String gccToolchain = ndkPaths.createGccToolchainPath(x86Arch + "-4.9");
+ String llvmTriple = llvmArch + "-none-linux-android";
+
+ return CToolchain.newBuilder()
+ .setCompiler("clang" + clangVersion)
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+
+ // Compiler flags
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-target")
+ .addCompilerFlag(llvmTriple)
+ .addCompilerFlag("-ffunction-sections")
+ .addCompilerFlag("-funwind-tables")
+ .addCompilerFlag("-fstack-protector-strong")
+ .addCompilerFlag("-fPIC")
+ .addCompilerFlag("-Wno-invalid-command-line-argument")
+ .addCompilerFlag("-Wno-unused-command-line-argument")
+ .addCompilerFlag("-no-canonical-prefixes")
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", triple))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel(x86Arch))
+
+ // Linker flags
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-target")
+ .addLinkerFlag(llvmTriple)
+ .addLinkerFlag("-no-canonical-prefixes")
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-O2")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-g"))
+ .setTargetSystemName("x86-linux-android");
+ }
+}
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
index c75bad7eb217d4..5260e67ec454c1 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
@@ -115,7 +115,7 @@ public void testInvalidNdkReleaseTxt() throws Exception {
eventCollector,
"The revision of the Android NDK referenced by android_ndk_repository rule 'androidndk' "
+ "could not be determined (the revision string found is 'not a valid release string')."
- + " Bazel will attempt to treat the NDK as if it was r18.");
+ + " Bazel will attempt to treat the NDK as if it was r19.");
}
@Test
@@ -142,7 +142,7 @@ public void testInvalidNdkSourceProperties() throws Exception {
eventCollector,
"The revision of the Android NDK referenced by android_ndk_repository rule 'androidndk' "
+ "could not be determined (the revision string found is 'invalid package revision'). "
- + "Bazel will attempt to treat the NDK as if it was r18.");
+ + "Bazel will attempt to treat the NDK as if it was r19.");
}
@Test
@@ -166,8 +166,8 @@ public void testUnsupportedNdkVersion() throws Exception {
eventCollector,
"The major revision of the Android NDK referenced by android_ndk_repository rule "
+ "'androidndk' is 19. The major revisions supported by Bazel are "
- + "[10, 11, 12, 13, 14, 15, 16, 17, 18]. Bazel will attempt to treat the NDK as if it "
- + "was r18.");
+ + "[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]. Bazel will attempt to treat the NDK as if "
+ + "it was r19.");
}
@Test
diff --git a/src/test/shell/bazel/android/android_ndk_integration_test.sh b/src/test/shell/bazel/android/android_ndk_integration_test.sh
index c8e85e7ee304a4..8c82626b5f701f 100755
--- a/src/test/shell/bazel/android/android_ndk_integration_test.sh
+++ b/src/test/shell/bazel/android/android_ndk_integration_test.sh
@@ -175,7 +175,7 @@ EOF
function check_num_sos() {
num_sos=$(unzip -Z1 bazel-bin/java/bazel/bin.apk '*.so' | wc -l | sed -e 's/[[:space:]]//g')
- assert_equals "5" "$num_sos"
+ assert_equals "4" "$num_sos"
}
function check_soname() {
@@ -202,7 +202,7 @@ function test_android_binary() {
setup_android_ndk_support
create_android_binary
- cpus="armeabi,armeabi-v7a,arm64-v8a,x86,x86_64"
+ cpus="armeabi-v7a,arm64-v8a,x86,x86_64"
bazel build -s //java/bazel:bin --fat_apk_cpu="$cpus" || fail "build failed"
check_num_sos
@@ -215,11 +215,11 @@ function test_android_binary_clang() {
setup_android_ndk_support
create_android_binary
- cpus="armeabi,armeabi-v7a,arm64-v8a,x86,x86_64"
+ cpus="armeabi-v7a,arm64-v8a,x86,x86_64"
bazel build -s //java/bazel:bin \
--fat_apk_cpu="$cpus" \
- --android_compiler=clang5.0.300080 \
+ --android_compiler=clang8.0.1 \
|| fail "build failed"
check_num_sos
check_soname
@@ -234,6 +234,7 @@ cc_binary(
name = "foo",
srcs = ["foo.cc"],
copts = ["-mfpu=neon"],
+ linkopts = ["-ldl"],
)
EOF
cat > foo.cc <<EOF
@@ -241,7 +242,7 @@ EOF
int main() { return 0; }
EOF
bazel build //:foo \
- --compiler=clang5.0.300080 \
+ --compiler=clang8.0.1 \
--cpu=armeabi-v7a \
--crosstool_top=//external:android/crosstool \
--host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
@@ -296,6 +297,7 @@ function test_stripped_cc_binary() {
cc_binary(
name = "foo",
srcs = ["foo.cc"],
+ linkopts = ["-ldl"],
)
EOF
cat > foo.cc <<EOF
@@ -308,7 +310,8 @@ EOF
|| fail "build failed"
}
-function test_crosstool_stlport() {
+# stlport is no longer in the ndk
+function ignore_test_crosstool_stlport() {
create_new_workspace
setup_android_ndk_support
cat > BUILD <<EOF
@@ -370,7 +373,8 @@ EOF
--host_crosstool_top=@bazel_tools//tools/cpp:toolchain
}
-function test_crosstool_gnu_libstdcpp() {
+# libstdcpp is no longer in the NDK
+function ignore_test_crosstool_gnu_libstdcpp() {
create_new_workspace
setup_android_ndk_support
cat > BUILD <<EOF
@@ -406,7 +410,7 @@ function test_crosstool_libcpp_with_multiarch() {
setup_android_ndk_support
create_android_binary
- cpus="armeabi,armeabi-v7a,arm64-v8a,x86,x86_64"
+ cpus="armeabi-v7a,arm64-v8a,x86,x86_64"
assert_build //java/bazel:bin \
--fat_apk_cpu="$cpus" \
| test | train | 2019-05-31T00:34:50 | "2018-10-03T18:25:55Z" | jin | test |
bazelbuild/bazel/6297_8524 | bazelbuild/bazel | bazelbuild/bazel/6297 | bazelbuild/bazel/8524 | [
"timestamp(timedelta=641.0, similarity=0.9231411341872593)"
] | 536a166270590a8dbc701718550383f3a07cc763 | 7446e1fbf85259f3cbb5be3740813e0601f46e54 | [
"r19 beta 2 is available, r19 is expected to ship soon.\r\n\r\nhttps://developer.android.com/ndk/downloads/",
"NDK 19 has dropped: https://developer.android.com/ndk/downloads/#stable-downloads",
"Link to changelog: https://github.com/android-ndk/ndk/wiki/Changelog-r19",
"After speaking with @hlopko, the right way forward here is to implement the NDK CROSSTOOL in Starlark. This isn't a necessary blocker for NDK 19, since we can adapt the NDK 18 configuration for 19, but it would be nice to turn down proto CROSSTOOL generation to move to the modern approach.\r\n\r\n@hlopko's suggestion:\r\n\r\n> write a rule ndk_cc_toolchain_config that has attributes for things that are different between versions, and only instantiate that in BUILD files.\r\n\r\nMore information: \r\n\r\n- https://github.com/bazelbuild/bazel/issues/7320\r\n- https://docs.bazel.build/versions/master/cc-toolchain-config-reference.html\r\n",
"@jin do you plan on supporting `lld` too ?",
"@steeve definitely. We want the Android rules to be 100% compatible with the recommended set of tools in the NDK.",
"The NDK CROSSTOOL has been ported to Starlark with massive help from @hlopko - thanks!\r\n\r\nGoing through the [changelog](https://github.com/android-ndk/ndk/wiki/Changelog-r19):\r\n\r\n> # Announcements\r\n\r\n> Developers should begin testing their apps with LLD. AOSP has switched to using LLD by default and the NDK will use it by default in the next release. BFD and Gold will be removed once LLD has been through a release cycle with no major unresolved issues (estimated r21). Test LLD in your app by passing -fuse-ld=lld when linking.\r\n \r\n> Note: lld does not currently support compressed symbols on Windows. See Issue 888. Clang also cannot generate compressed symbols on Windows, but this can be a problem when using artifacts built from Darwin or Linux.\r\n\r\nWe will need to add support for this.\r\n\r\n> The Play Store will require 64-bit support when uploading an APK beginning in August 2019. Start porting now to avoid surprises when the time comes. For more information, see this blog post.\r\n\r\nWe may want to add a warning message about this when building for non-64-bit.\r\n\r\n> Issue 780: Standalone toolchains are now unnecessary. Clang, binutils, the sysroot, and other toolchain pieces are now all installed to $NDK/toolchains/llvm/prebuilt/<host-tag> and Clang will automatically find them. Instead of creating a standalone toolchain for API 26 ARM, instead invoke the compiler directly from the NDK:\r\n> \r\n> $ $NDK/toolchains/llvm/prebuilt/<host-tag>/bin/armv7a-linux-androideabi26-clang++ src.cpp\r\n> For r19 the toolchain is also installed to the old path to give build systems a chance to adapt to the new layout. The old paths will be removed in r20.\r\n\r\nWe must definitely support this, but the effects of it should be transparent to end users. It's not clear what the impact of having a standalone toolchain will be on the Starlark crosstool configuration.\r\n \r\n> The make_standalone_toolchain.py script will not be removed. It is now unnecessary and will emit a warning with the above information, but the script will remain to preserve existing workflows.\r\n\r\nNot applicable, we don't use this.\r\n\r\n> If you're using ndk-build, CMake, or a standalone toolchain, there should be no change to your workflow. This change is meaningful for maintainers of third-party build systems, who should now be able to delete some Android-specific code. For more information, see the Build System Maintainers guide.\r\n\r\nMore reading: https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md\r\n\r\n> ndk-depends has been removed. We believe that ReLinker is a better solution to native library loading issues on old Android versions.\r\n\r\nNot applicable, we don't use this.\r\n\r\n> Issue 862: The GCC wrapper scripts which redirected to Clang have been removed, as they are not functional enough to be drop in replacements.\r\n\r\nThis should be addressed by the standalone toolchain support.\r\n\r\n---\r\n\r\n> r19c\r\n> ----\r\n> \r\n> * [Issue 912]: Prevent the CMake toolchain file from clobbering a user\r\n> specified `CMAKE_FIND_ROOT_PATH`.\r\n> * [Issue 920]: Fix clang wrapper scripts on Windows.\r\n> \r\n> [Issue 912]: https://github.com/android-ndk/ndk/issues/912\r\n> [Issue 920]: https://github.com/android-ndk/ndk/issues/920\r\n> \r\n> r19b\r\n> ----\r\n> \r\n> * [Issue 855]: ndk-build automatically disables multithreaded linking for LLD\r\n> on Windows, where it may hang. It is not possible for the NDK to detect this\r\n> situation for CMake, so CMake users and custom build systems must pass\r\n> `-Wl,--no-threads` when linking with LLD on Windows.\r\n\r\nWe'll need to take note of this for the `lld` support.\r\n\r\n> * [Issue 849]: Fixed unused command line argument warning when using standalone\r\n> toolchains to compile C code.\r\n> * [Issue 890]: Fixed `CMAKE_FIND_ROOT_PATH`. CMake projects will no longer\r\n> search the host's sysroot for headers and libraries.\r\n> * [Issue 906]: Explicitly set `-march=armv7-a` for 32-bit ARM to workaround\r\n> Clang not setting that flag automatically when using `-fno-integrated-as`.\r\n> This fix only affects ndk-build and CMake. Standalone toolchains and custom\r\n> build systems will need to apply this fix themselves.\r\n> * [Issue 907]: Fixed `find_path` for NDK headers in CMake.\r\n> \r\n> [Issue 849]: https://github.com/android-ndk/ndk/issues/849\r\n> [Issue 890]: https://github.com/android-ndk/ndk/issues/890\r\n> [Issue 907]: https://github.com/android-ndk/ndk/issues/907\r\n> \r\n> Changes\r\n> -------\r\n> \r\n> * Updated Clang to r339409.\r\n> * C++ compilation now defaults to C++14.\r\n\r\nNeed to update default std to `-std=c++14`.\r\n\r\n> * [Issue 780]: A complete NDK toolchain is now installed to the Clang\r\n> directory. See the announcements section for more information.\r\n> * ndk-build no longer removes artifacts from `NDK_LIBS_OUT` for ABIs not\r\n> present in `APP_ABI`. This enables workflows like the following:\r\n> \r\n> ```bash\r\n> for abi in armeabi-v7a arm64-v8a x86 x86_64; do\r\n> ndk-build APP_ABI=$abi\r\n> done\r\n> ```\r\n> \r\n> Prior to this change, the above workflow would remove the previously built\r\n> ABI's artifacts on each successive build, resulting in only x86_64 being\r\n> present at the end of the loop.\r\n> * ndk-stack has been rewritten in Python.\r\n> * [Issue 776]: To better support LLD, ndk-build and CMake no longer pass\r\n> `-Wl,--fix-cortex-a8` by default.\r\n> * CPUs that require this fix are uncommon in the NDK's supported API range\r\n> (16+).\r\n> * If you need to continue supporting these devices, add\r\n> `-Wl,--fix-cortex-a8` to your `APP_LDFLAGS` or `CMAKE_C_FLAGS`, but note\r\n> that LLD will not be adding support for this workaround.\r\n> * Alternatively, use the Play Console to [blacklist] Cortex-A8 CPUs to\r\n> disallow your app from being installed on those devices.\r\n\r\nOur ARM crosstool add this `--fix-cortex-a8` linker flag, so we should drop them here.\r\n\r\n```\r\nsrc/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ArmCrosstools.java\r\n149: .addLinkerFlag(\"-Wl,--fix-cortex-a8\")\r\n```\r\n\r\n> * [Issue 798]: The ndk-build and CMake options to disable RelRO and noexecstack\r\n> are now ignored. All code is built with RelRO and non-executable stacks.\r\n\r\nNot sure how/if we do this, will need to investigate.\r\n\r\n> * [Issue 294]: All code is now built with a subset of [compiler-rt] to provide\r\n> a complete set of compiler built-ins for Clang.\r\n> \r\n> [Issue 294]: https://github.com/android-ndk/ndk/issues/294\r\n> [Issue 776]: https://github.com/android-ndk/ndk/issues/776\r\n> [Issue 798]: https://github.com/android-ndk/ndk/issues/798\r\n> [blacklist]: https://support.google.com/googleplay/android-developer/answer/7353455?hl=en\r\n> [compiler-rt]: https://compiler-rt.llvm.org/\r\n> \r\n> Known Issues\r\n> ------------\r\n> \r\n> * This is not intended to be a comprehensive list of all outstanding bugs.\r\n> * [Issue 888]: lld does not support compressed symbols on Windows. Clang also\r\n> cannot generate compressed symbols on Windows, but this can be a problem when\r\n> using artifacts built from Darwin or Linux.\r\n> * [Issue 360]: `thread_local` variables with non-trivial destructors will cause\r\n> segfaults if the containing library is `dlclose`ed on devices running M or\r\n> newer, or devices before M when using a static STL. The simple workaround is\r\n> to not call `dlclose`.\r\n> * [Issue 70838247]: Gold emits broken debug information for AArch64. AArch64\r\n> still uses BFD by default.\r\n> * [Issue 855]: LLD may hang on Windows when using multithreaded linking.\r\n> ndk-build will automatically disable multithreaded linking in this situation,\r\n> but CMake users and custom build systems should pass `-Wl,--no-threads` when\r\n> using LLD on Windows. The other linkers and operating systems are unaffected.\r\n\r\nAddressed above.\r\n\r\n> * [Issue 884]: Third-party build systems must pass `-fno-addrsig` to Clang for\r\n> compatibility with binutils. ndk-build, CMake, and standalone toolchains\r\n> handle this automatically.\r\n\r\nLooks like standalone toolchains support this, but will be good to verify.\r\n\r\n> * [Issue 906]: Clang does not pass `-march=armv7-a` to the assembler when using\r\n> `-fno-integrated-as`. This results in the assembler generating ARMv5\r\n> instructions. Note that by default Clang uses the integrated assembler which\r\n> does not have this problem. To workaround this issue, explicitly use\r\n> `-march=armv7-a` when building for 32-bit ARM with the non-integrated\r\n> assembler, or use the integrated assembler. ndk-build and CMake already\r\n> contain these workarounds.\r\n\r\nWe'll need to add this workaround.\r\n\r\n> * This version of the NDK is incompatible with the Android Gradle plugin\r\n> version 3.0 or older. If you see an error like\r\n> `No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android`,\r\n> update your project file to [use plugin version 3.1 or newer]. You will also\r\n> need to upgrade to Android Studio 3.1 or newer.\r\n> \r\n> [Issue 360]: https://github.com/android-ndk/ndk/issues/360\r\n> [Issue 70838247]: https://issuetracker.google.com/70838247\r\n> [Issue 855]: https://github.com/android-ndk/ndk/issues/855\r\n> [Issue 884]: https://github.com/android-ndk/ndk/issues/884\r\n> [Issue 888]: https://github.com/android-ndk/ndk/issues/888\r\n> [Issue 906]: https://github.com/android-ndk/ndk/issues/906\r\n> [use plugin version 3.1 or newer]: https://developer.android.com/studio/releases/gradle-plugin#updating-plugin\r\n\r\n\r\n",
"Addressed in https://github.com/bazelbuild/bazel/pull/8524"
] | [] | "2019-05-30T23:43:08Z" | [
"type: feature request",
"P1",
"team-Android"
] | Support NDK r19 | Expected release: Q4 2018
Changes: https://android.googlesource.com/platform/ndk/+/master/docs/Roadmap.md#ndk-r19
* Make all toolchains be standalone toolchains
> Now that the NDK is down to a single compiler and STL, if we just taught the Clang driver to emit -D__ANDROID_API__=foo and to link libc.so.18 instead of libc.so, standalone toolchains would be obsolete because the compiler would already be a standalone toolchain. The NDK toolchain would Just Work regardless of build system, and the logic contained in each build system could be greatly reduced.
> Related to this (but maybe occurring in a later release), we'll want to switch from libgcc to libcompiler-rt and our own unwinder.
> See the corresponding bug make all toolchains standalone toolchains for detailed discussion of the implementation and sub-tasks. | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java"
] | [
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java",
"src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
index d595dfe5b340d2..a97ea71b692abe 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
@@ -23,6 +23,7 @@
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r15.NdkMajorRevisionR15;
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r17.NdkMajorRevisionR17;
import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18.NdkMajorRevisionR18;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19.NdkMajorRevisionR19;
import com.google.devtools.build.lib.util.OS;
import java.util.Map;
@@ -50,6 +51,8 @@ private AndroidNdkCrosstools() {}
.put(16, new NdkMajorRevisionR15("5.0.300080")) // no changes relevant to Bazel
.put(17, new NdkMajorRevisionR17("6.0.2"))
.put(18, new NdkMajorRevisionR18("7.0.2"))
+ .put(19, new NdkMajorRevisionR19("8.0.2"))
+ .put(20, new NdkMajorRevisionR19("8.0.7")) // no changes relevant to Bazel
.build();
public static final Map.Entry<Integer, NdkMajorRevision> LATEST_KNOWN_REVISION =
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java
new file mode 100644
index 00000000000000..0758edd40f8e94
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java
@@ -0,0 +1,108 @@
+// Copyright 2019 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Generates a CrosstoolRelease proto for the Android NDK. */
+final class AndroidNdkCrosstoolsR19 {
+
+ /**
+ * Creates a CrosstoolRelease proto for the Android NDK, given the API level to use and the
+ * release revision. The crosstools are generated through code rather than checked in as a flat
+ * file to reduce the amount of templating needed (for parameters like the release name and
+ * certain paths), to reduce duplication, and to make it easier to support future versions of the
+ * NDK. TODO(bazel-team): Eventually we should move this into Skylark so the crosstools can be
+ * updated independently of Bazel itself.
+ *
+ * @return A CrosstoolRelease for the Android NDK.
+ */
+ static CrosstoolRelease create(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+ return CrosstoolRelease.newBuilder()
+ .setMajorVersion("android")
+ .setMinorVersion("")
+ .setDefaultTargetCpu("armeabi")
+ .addAllToolchain(createToolchains(ndkPaths, stlImpl, hostPlatform, clangVersion))
+ .build();
+ }
+
+ private static ImmutableList<CToolchain> createToolchains(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+
+ List<CToolchain.Builder> toolchainBuilders = new ArrayList<>();
+ toolchainBuilders.addAll(new ArmCrosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+ toolchainBuilders.addAll(new X86Crosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+
+ ImmutableList.Builder<CToolchain> toolchains = new ImmutableList.Builder<>();
+
+ // Set attributes common to all toolchains.
+ for (CToolchain.Builder toolchainBuilder : toolchainBuilders) {
+ toolchainBuilder
+ .setHostSystemName(hostPlatform)
+ .setTargetLibc("local")
+ .setAbiVersion(toolchainBuilder.getTargetCpu())
+ .setAbiLibcVersion("local");
+
+ toolchainBuilder
+ .addCompilerFlag("-no-canonical-prefixes")
+ .addCompilerFlag("-Wno-invalid-command-line-argument")
+ .addCompilerFlag("-Wno-unused-command-line-argument")
+ .addCompilerFlag("-funwind-tables")
+ .addCompilerFlag("-fstack-protector-strong");
+
+ toolchainBuilder.addLinkerFlag("-no-canonical-prefixes");
+
+ https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md#additional-required-arguments
+ toolchainBuilder
+ // "Clang uses -faddrsig by default, but this produces output that is incompatible with GNU binutils. To workaround this, -fno-addrsig must be passed to Clang when using GNU binutils."
+ .addCompilerFlag("-fno-addrsig")
+ // "All code must be linked with -Wl,-z,relro, which causes relocations to be made read-only after relocation is performed."
+ .addLinkerFlag("-Wl,-z,relro");
+
+ // https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md#controlling-binary-size
+ toolchainBuilder
+ .addCompilerFlag("-ffunction-sections")
+ .addCompilerFlag("-fdata-sections")
+ .addLinkerFlag("-Wl,--gc-sections");
+
+ // https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md#helpful-warnings
+ toolchainBuilder
+ .addCompilerFlag("-Werror=return-type")
+ .addCompilerFlag("-Werror=int-to-pointer-cast")
+ .addCompilerFlag("-Werror=pointer-to-int-cast")
+ .addCompilerFlag("-Werror=implicit-function-declaration");
+
+
+ // builtin_sysroot is set individually on each toolchain.
+ // platforms/arch sysroot
+ toolchainBuilder.addCxxBuiltinIncludeDirectory("%sysroot%/usr/include");
+ toolchainBuilder.addCxxBuiltinIncludeDirectory(
+ ndkPaths.createBuiltinSysroot() + "/usr/include");
+ toolchainBuilder.addUnfilteredCxxFlag(
+ "-isystem%ndk%/usr/include".replace("%ndk%", ndkPaths.createBuiltinSysroot()));
+
+ toolchains.add(toolchainBuilder.build());
+ }
+
+ return toolchains.build();
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java
new file mode 100644
index 00000000000000..894b7d3631a572
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java
@@ -0,0 +1,61 @@
+// Copyright 2019 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.events.EventHandler;
+
+/** Class which encodes information from the Android NDK makefiles about API levels. */
+final class ApiLevelR19 extends ApiLevel {
+ /** This is the contents of {@code platforms/android-*} */
+ private static final ImmutableListMultimap<String, String> API_LEVEL_TO_ARCHITECTURES =
+ ImmutableListMultimap.<String, String>builder()
+ .putAll("16", "arm", "x86")
+ .putAll("17", "arm", "x86")
+ .putAll("18", "arm", "x86")
+ .putAll("19", "arm", "x86")
+ .putAll("21", "arm", "x86", "arm64", "x86_64")
+ .putAll("22", "arm", "x86", "arm64", "x86_64")
+ .putAll("23", "arm", "x86", "arm64", "x86_64")
+ .putAll("24", "arm", "x86", "arm64", "x86_64")
+ .putAll("26", "arm", "x86", "arm64", "x86_64")
+ .putAll("27", "arm", "x86", "arm64", "x86_64")
+ .putAll("28", "arm", "x86", "arm64", "x86_64")
+ .build();
+
+ /** This map fill in the gaps of {@code API_LEVEL_TO_ARCHITECTURES}. */
+ private static final ImmutableMap<String, String> API_EQUIVALENCIES =
+ ImmutableMap.<String, String>builder()
+ .put("16", "16")
+ .put("17", "16")
+ .put("18", "18")
+ .put("19", "19")
+ .put("20", "19")
+ .put("21", "21")
+ .put("22", "22")
+ .put("23", "23")
+ .put("24", "24")
+ .put("25", "24")
+ .put("26", "26")
+ .put("27", "27")
+ .put("28", "28")
+ .build();
+
+ ApiLevelR19(EventHandler eventHandler, String repositoryName, String apiLevel) {
+ super(API_LEVEL_TO_ARCHITECTURES, API_EQUIVALENCIES, eventHandler, repositoryName, apiLevel);
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java
new file mode 100644
index 00000000000000..c4dbebf296b52e
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java
@@ -0,0 +1,159 @@
+// Copyright 2019 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for ARM. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class ArmCrosstools {
+ private final NdkPaths ndkPaths;
+ private final StlImpl stlImpl;
+ private final String clangVersion;
+
+ ArmCrosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+ this.ndkPaths = ndkPaths;
+ this.stlImpl = stlImpl;
+ this.clangVersion = clangVersion;
+ }
+
+ ImmutableList<CToolchain.Builder> createCrosstools() {
+ CToolchain.Builder aarch64Toolchain = createAarch64ClangToolchain();
+ CToolchain.Builder armeabiToolchain = createArmeabiClangToolchain();
+
+ stlImpl.addStlImpl(aarch64Toolchain, "4.9");
+ stlImpl.addStlImpl(armeabiToolchain, "4.9");
+
+ return ImmutableList.<CToolchain.Builder>builder()
+ .add(aarch64Toolchain)
+ .add(armeabiToolchain)
+ .build();
+ }
+
+ private CToolchain.Builder createAarch64ClangToolchain() {
+ String toolchainName = "aarch64-linux-android-4.9";
+ String targetPlatform = "aarch64-linux-android";
+ String gccToolchain = ndkPaths.createGccToolchainPath(toolchainName);
+ String llvmTriple = "aarch64-none-linux-android";
+
+ return CToolchain.newBuilder()
+ .setToolchainIdentifier("aarch64-linux-android-clang" + clangVersion)
+ .setTargetSystemName(targetPlatform)
+ .setTargetCpu("arm64-v8a")
+ .setCompiler("clang" + clangVersion)
+ .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm64"))
+
+ // Compiler flags
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-target")
+ .addCompilerFlag(llvmTriple)
+ .addCompilerFlag("-fpic")
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", targetPlatform))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+
+ // Linker flags
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-target")
+ .addLinkerFlag(llvmTriple)
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-O2")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-UNDEBUG"));
+ }
+
+ private CToolchain.Builder createArmeabiClangToolchain() {
+ String toolchainName = "arm-linux-androideabi-4.9";
+ String targetPlatform = "arm-linux-androideabi";
+ String gccToolchain = ndkPaths.createGccToolchainPath("arm-linux-androideabi-4.9");
+
+ return CToolchain.newBuilder()
+ .setToolchainIdentifier("arm-linux-androideabi-clang" + clangVersion + "-v7a")
+ .setTargetCpu("armeabi-v7a")
+ .setTargetSystemName("arm-linux-androideabi")
+ .setCompiler("clang" + clangVersion)
+ .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm"))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", targetPlatform))
+
+ // Compiler flags
+ .addCompilerFlag("-target")
+ .addCompilerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+ .addCompilerFlag("-march=armv7-a")
+ .addCompilerFlag("-mfloat-abi=softfp")
+ // "32-bit ARM targets should use -mfpu=vfpv3-d16 when compiling unless using NEON. This allows the compiler to make use of the FPU."
+ // https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md#additional-required-arguments
+ .addCompilerFlag("-mfpu=vfpv3-d16")
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-fpic")
+
+ // Linker flags
+ .addLinkerFlag("-target")
+ .addLinkerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-mthumb")
+ .addCompilerFlag("-Os")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-fno-strict-aliasing")
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-UNDEBUG"));
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java
new file mode 100644
index 00000000000000..a9eae019af8e81
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java
@@ -0,0 +1,42 @@
+// Copyright 2019 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkMajorRevision;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.events.EventHandler;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+
+/** Logic specific to Android NDK R17. */
+public class NdkMajorRevisionR19 implements NdkMajorRevision {
+ private final String clangVersion;
+
+ public NdkMajorRevisionR19(String clangVersion) {
+ this.clangVersion = clangVersion;
+ }
+
+ @Override
+ public CrosstoolRelease crosstoolRelease(
+ NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform) {
+ return AndroidNdkCrosstoolsR19.create(ndkPaths, stlImpl, hostPlatform, clangVersion);
+ }
+
+ @Override
+ public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
+ return new ApiLevelR19(eventHandler, name, apiLevel);
+ }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java
new file mode 100644
index 00000000000000..7a91da2e992268
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java
@@ -0,0 +1,121 @@
+// Copyright 2019 The Bazel Authors. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for x86. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class X86Crosstools {
+ private final NdkPaths ndkPaths;
+ private final StlImpl stlImpl;
+ private final String clangVersion;
+
+ X86Crosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+ this.ndkPaths = ndkPaths;
+ this.stlImpl = stlImpl;
+ this.clangVersion = clangVersion;
+ }
+
+ ImmutableList<CToolchain.Builder> createCrosstools() {
+ /** x86 */
+ // clang
+ CToolchain.Builder x86Clang =
+ createBaseX86ClangToolchain("x86", "i686", "i686-linux-android")
+ // Workaround for https://code.google.com/p/android/issues/detail?id=220159.
+ .addCompilerFlag("-mstackrealign")
+ .setToolchainIdentifier("x86-clang" + clangVersion)
+ .setTargetCpu("x86")
+ .addAllToolPath(ndkPaths.createClangToolpaths("x86-4.9", "i686-linux-android", null))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86"));
+
+ stlImpl.addStlImpl(x86Clang, null);
+
+ /** x86_64 */
+ CToolchain.Builder x8664Clang =
+ createBaseX86ClangToolchain("x86_64", "x86_64", "x86_64-linux-android")
+ .setToolchainIdentifier("x86_64-clang" + clangVersion)
+ .setTargetCpu("x86_64")
+ .addAllToolPath(
+ ndkPaths.createClangToolpaths("x86_64-4.9", "x86_64-linux-android", null))
+ .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86_64"));
+
+ stlImpl.addStlImpl(x8664Clang, null);
+
+ return ImmutableList.of(x86Clang, x8664Clang);
+ }
+
+ private CToolchain.Builder createBaseX86ClangToolchain(
+ String x86Arch, String llvmArch, String triple) {
+ String gccToolchain = ndkPaths.createGccToolchainPath(x86Arch + "-4.9");
+ String llvmTriple = llvmArch + "-none-linux-android";
+
+ CToolchain.Builder cToolchainBuilder = CToolchain.newBuilder();
+
+ cToolchainBuilder
+ .setCompiler("clang" + clangVersion)
+ .addCxxBuiltinIncludeDirectory(
+ ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+
+ // Compiler flags
+ .addCompilerFlag("-gcc-toolchain")
+ .addCompilerFlag(gccToolchain)
+ .addCompilerFlag("-target")
+ .addCompilerFlag(llvmTriple)
+ .addCompilerFlag("-fPIC")
+ .addCompilerFlag(
+ "-isystem%ndk%/usr/include/%triple%"
+ .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+ .replace("%triple%", triple))
+ .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel(x86Arch))
+
+ // Linker flags
+ .addLinkerFlag("-gcc-toolchain")
+ .addLinkerFlag(gccToolchain)
+ .addLinkerFlag("-target")
+ .addLinkerFlag(llvmTriple)
+
+ // Additional release flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.OPT)
+ .addCompilerFlag("-O2")
+ .addCompilerFlag("-g")
+ .addCompilerFlag("-DNDEBUG"))
+
+ // Additional debug flags
+ .addCompilationModeFlags(
+ CompilationModeFlags.newBuilder()
+ .setMode(CompilationMode.DBG)
+ .addCompilerFlag("-O0")
+ .addCompilerFlag("-g"))
+ .setTargetSystemName("x86-linux-android");
+
+ if (Integer.parseInt(ndkPaths.getCorrectedApiLevel(x86Arch)) < 24) {
+ // "For x86 targets prior to Android Nougat (API 24), -mstackrealign is needed to properly align stacks for global constructors. See Issue 635."
+ // https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md#additional-required-arguments
+ cToolchainBuilder.addCompilerFlag("-mstackrealign");
+ }
+
+ return cToolchainBuilder;
+ }
+}
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
index 0ce4aa1802d6cd..4bfc3cc0dcbdcd 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
@@ -115,7 +115,7 @@ public void testInvalidNdkReleaseTxt() throws Exception {
eventCollector,
"The revision of the Android NDK referenced by android_ndk_repository rule 'androidndk' "
+ "could not be determined (the revision string found is 'not a valid release string')."
- + " Bazel will attempt to treat the NDK as if it was r18.");
+ + " Bazel will attempt to treat the NDK as if it was r20.");
}
@Test
@@ -142,7 +142,7 @@ public void testInvalidNdkSourceProperties() throws Exception {
eventCollector,
"The revision of the Android NDK referenced by android_ndk_repository rule 'androidndk' "
+ "could not be determined (the revision string found is 'invalid package revision'). "
- + "Bazel will attempt to treat the NDK as if it was r18.");
+ + "Bazel will attempt to treat the NDK as if it was r20.");
}
@Test
@@ -158,16 +158,16 @@ public void testUnsupportedNdkVersion() throws Exception {
")");
scratch.overwriteFile(
- "/ndk/source.properties", "Pkg.Desc = Android NDK", "Pkg.Revision = 19.0.3675639-beta2");
+ "/ndk/source.properties", "Pkg.Desc = Android NDK", "Pkg.Revision = 21.0.3675639-beta2");
invalidatePackages();
assertThat(getConfiguredTarget("@androidndk//:files")).isNotNull();
MoreAsserts.assertContainsEvent(
eventCollector,
"The major revision of the Android NDK referenced by android_ndk_repository rule "
- + "'androidndk' is 19. The major revisions supported by Bazel are "
- + "[10, 11, 12, 13, 14, 15, 16, 17, 18]. Bazel will attempt to treat the NDK as if it "
- + "was r18.");
+ + "'androidndk' is 21. The major revisions supported by Bazel are "
+ + "[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]. "
+ + "Bazel will attempt to treat the NDK as if it was r20.");
}
@Test
| train | train | 2019-05-31T01:41:31 | "2018-10-03T18:25:55Z" | jin | test |
bazelbuild/bazel/6321_6322 | bazelbuild/bazel | bazelbuild/bazel/6321 | bazelbuild/bazel/6322 | [
"timestamp(timedelta=0.0, similarity=0.9904610207971085)"
] | 2a207cac61e2eb3a308f35ef7feb5a5964526fce | 9226fe4a5c00957645ddde0d2d6bf3d08da0a170 | [
"Release blocker for 0.18 #5963 "
] | [
"the legacy behavior would be to have this hidden behind --master_blazerc, in case that matters to you at this point"
] | "2018-10-05T14:05:44Z" | [
"P0"
] | Temporarily restore processing of workspace-wide tools/bazel.rc file | Mitigate widespread breakage that occured after landing https://github.com/bazelbuild/bazel/issues/5765 by implementing the fix proposed in https://groups.google.com/d/msg/bazel-discuss/ycDacctX2vw/EGFxGLibAgAJ.
This introduces a weird new behavior that not fully compatible with either the old or the new (per #5765) way of doing things, but will probably work for a vast majority of users. #6319 track removal of this temporary behavior once it is introduced.
| [
"src/main/cpp/option_processor.cc"
] | [
"src/main/cpp/option_processor.cc"
] | [
"src/test/cpp/rc_file_test.cc"
] | diff --git a/src/main/cpp/option_processor.cc b/src/main/cpp/option_processor.cc
index 04f7f4f8ff60c8..8fc06b66b4a86a 100644
--- a/src/main/cpp/option_processor.cc
+++ b/src/main/cpp/option_processor.cc
@@ -322,6 +322,9 @@ blaze_exit_code::ExitCode OptionProcessor::GetRcFiles(
SearchNullaryOption(cmd_line->startup_args, "workspace_rc", true)) {
const std::string workspaceRcFile =
blaze_util::JoinPath(workspace, kRcBasename);
+ // Legacy behavior.
+ rc_files.push_back(
+ workspace_layout->GetWorkspaceRcPath(workspace, cmd_line->startup_args));
rc_files.push_back(workspaceRcFile);
}
@@ -417,6 +420,16 @@ blaze_exit_code::ExitCode OptionProcessor::GetRcFiles(
<< joined_lost_rcs;
}
+ std::string legacy_workspace_file = workspace_layout->GetWorkspaceRcPath(workspace, cmd_line->startup_args);
+ if (old_files.find(legacy_workspace_file) != old_files.end()) {
+ BAZEL_LOG(WARNING)
+ << "Processed legacy workspace file "
+ << legacy_workspace_file
+ << ". This file will not be processed in the next release of Bazel. "
+ << " Please read https://github.com/bazelbuild/bazel/issues/6319 for further information, "
+ << " including how to upgrade.";
+ }
+
return blaze_exit_code::SUCCESS;
}
| diff --git a/src/test/cpp/rc_file_test.cc b/src/test/cpp/rc_file_test.cc
index 711e7b655e8843..f0a9744d19deb0 100644
--- a/src/test/cpp/rc_file_test.cc
+++ b/src/test/cpp/rc_file_test.cc
@@ -261,8 +261,39 @@ TEST_F(GetRcFileTest, GetRcFilesWarnsAboutIgnoredMasterRcFiles) {
// read as expected.
EXPECT_THAT(output,
HasSubstr("The following rc files are no longer being read"));
- EXPECT_THAT(output, HasSubstr(workspace_rc));
EXPECT_THAT(output, HasSubstr(binary_rc));
+
+ EXPECT_THAT(output,
+ HasSubstr("Processed legacy workspace file"));
+ EXPECT_THAT(output, HasSubstr(workspace_rc));
+}
+
+TEST_F(GetRcFileTest, GetRcFilesWarnsAboutLegacyWorkspaceFile) {
+ std::string workspace_rc;
+ ASSERT_TRUE(SetUpLegacyMasterRcFileInWorkspace("", &workspace_rc));
+
+ const CommandLine cmd_line = CommandLine(binary_path_, {}, "build", {});
+ std::string error = "check that this string is not modified";
+ std::vector<std::unique_ptr<RcFile>> parsed_rcs;
+
+ testing::internal::CaptureStderr();
+ const blaze_exit_code::ExitCode exit_code =
+ option_processor_->GetRcFiles(workspace_layout_.get(), workspace_, cwd_,
+ &cmd_line, &parsed_rcs, &error);
+ const std::string output = testing::internal::GetCapturedStderr();
+
+ EXPECT_EQ(blaze_exit_code::SUCCESS, exit_code);
+ EXPECT_EQ("check that this string is not modified", error);
+
+ // tools/blaze.rc should be read...
+ EXPECT_THAT(output,
+ Not(HasSubstr("The following rc files are no longer being read")));
+
+ // ... but reported specially.
+ // (cf https://github.com/bazelbuild/bazel/issues/6321).
+ EXPECT_THAT(output,
+ HasSubstr("Processed legacy workspace file"));
+ EXPECT_THAT(output, HasSubstr(workspace_rc));
}
TEST_F(
| train | train | 2018-10-05T13:14:34 | "2018-10-05T14:02:28Z" | dslomov | test |
bazelbuild/bazel/6323_6326 | bazelbuild/bazel | bazelbuild/bazel/6323 | bazelbuild/bazel/6326 | [
"timestamp(timedelta=0.0, similarity=0.8946550413544082)"
] | 3aca5780154f2bc177e90b87186a421bdd14cc91 | 8a13698d24a81980d35d6bbba326cab109855301 | [
"This can also be reproduced easily on a Linux system directly:\r\n\r\n- Check out the Bazel source code.\r\n- Change the line endings of `tools/genrule/genrule-setup.sh` to CRLF (e.g., using `:set ff=dos` in Vim and saving the file).\r\n- Run it directly using Bash. It will print the same errors as shown above."
] | [] | "2018-10-05T20:24:13Z" | [
"P1",
"area-Windows",
"untriaged",
"team-OSS"
] | On Windows, genrule-setup.sh contains carriage returns | ### Description of the problem / feature request:
On both a Linux and a Windows box, I have Bazel 0.17.2 installed. On the Linux system, the copy of `tools/genrule/genrule-setup.sh` is 858 bytes in size, whereas the copy shipped with the Windows version of Bazel is 882 bytes in size. The former uses NL, whereas the latter uses CR+NL.
Though `genrule-setup.sh` may contain CR+NL on Windows and work properly, the problem is that remote builds from Windows on a Linux cluster breaks as a result of it. Bash doesn't seem to like executing such files.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. Create a [Buildbarn](https://github.com/EdSchouten/bazel-buildbarn) setup running on a pile of Linux servers.
2. Install Bazel on a Windows system.
3. Perform a build of a `genrule()` target against the Buildbarn setup, using flags along the lines of `--host_cpu=k8 --cpu=k8`.
4. Notice that targets will throw the following warnings during execution:
```
external/bazel_tools/tools/genrule/genrule-setup.sh: line 2: $'\r': command not found
external/bazel_tools/tools/genrule/genrule-setup.sh: line 16: $'\r': command not found
: invalid optionools/tools/genrule/genrule-setup.sh: line 18: set: -
set: usage: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
external/bazel_tools/tools/genrule/genrule-setup.sh: line 19: $'\r': command not found
: invalid optionools/tools/genrule/genrule-setup.sh: line 21: set: -
set: usage: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]
external/bazel_tools/tools/genrule/genrule-setup.sh: line 22: $'\r': command not found
: invalid option nametools/genrule/genrule-setup.sh: line 24: set: pipefail
```
### What operating system are you running Bazel on?
Windows 10 1803.
### What's the output of `bazel info release`?
release 0.17.2
Installed it using Chocolatey.
### Have you found anything relevant by searching the web?
No.
### Any other information, logs, or outputs that you want to share?
Maybe the artifacts that are shipped with Bazel and are used as input files should be marked as binary, so they are byte-for-byte identical between platforms? | [
".gitattributes"
] | [
".gitattributes"
] | [] | diff --git a/.gitattributes b/.gitattributes
index c0f7b6a44d1b9c..35e4e72eeb31a1 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,3 +1,6 @@
*.bzl linguist-language=Python
BUILD linguist-language=Python
site/* linguist-documentation
+
+# Files that should not use CRLF line endings, even on Windows.
+tools/genrule/genrule-setup.sh -text
| null | train | train | 2018-10-05T22:14:03 | "2018-10-05T17:39:31Z" | EdSchouten | test |
bazelbuild/bazel/6351_7473 | bazelbuild/bazel | bazelbuild/bazel/6351 | bazelbuild/bazel/7473 | [
"timestamp(timedelta=0.0, similarity=0.873985520432397)"
] | a57c879dbca95316ecf50f5e96143eb9f7d1acb8 | 8517554049a44c6935d73eeac9e557e85c97509c | [
"@laszlocsomor there should be only one team label. Is that better for your team or for External dependencies?",
"I cannot tell. We have the Windows expertise, the Ext.Deps team has the rule logic expertise.",
"I spent some time with #7063 so I'm also investigating this bug now.",
"More observation:\r\n- When I add a new file to the external repo, Bazel *does* notice this, as proven by logging I added. Bazel creates a new `RegularDirectoryListingValue` SkyValue, however the downstream action is not re-executed.\r\n- If I re-run the build once more without any change, Bazel creates yet another `RegularDirectoryListingValue` SkyValue, whose hashcode is different from that in the previous bullet point, and this time Bazel also re-executes the downstream genrule.",
"Found the culprit. It's complex, so I'll write it down in a document and paste here later.",
"## Repro\r\n\r\nLet's have two directories, \"A\" and \"B\". \"A\" contains a WORKSPACE and BUILD file, while \"B\" contains just a dummy file:\r\n\r\n/src/A/WORKSPACE:\r\n```\r\nnew_local_repository(\r\n name = \"B\",\r\n build_file_content = \"\"\"\r\nfilegroup(\r\n name = \"F\",\r\n srcs = glob([\"*.txt\"]),\r\n visibility = [\"//visibility:public\"],\r\n)\r\n\"\"\",\r\n path = \"/src/B\",\r\n)\r\n```\r\n\r\n/src/A/BUILD:\r\n```\r\ngenrule(\r\n name = \"G\",\r\n srcs = [\"@B//:F\"],\r\n outs = [\"g.txt\"],\r\n cmd = \"echo $(SRCS) > $@\",\r\n)\r\n```\r\n\r\n/src/B/a.txt:\r\n```\r\ndummy\r\n```\r\n\r\n## Bug\r\n\r\nIf we build \"//:G\" inside /src/A, then g.txt correctly lists external/B/a.txt and nothing else.\r\n\r\nIf we add a new file /src/B/b.txt and rebuild :G, then g.txt should list external/B/a.txt and external/B/b.txt -- and it does on Linux but not on Windows.\r\n\r\nIf we build a third time on Windows without doing anything, g.txt will contain the correct output.\r\n\r\n## Analysis\r\n\r\nnew_local_repository creates symlinks to every file and directory in its root, e.g. external/B/a.txt is a symlink to /src/B/a.txt. This is done as part of computing the REPOSITORY_DIRECTORY SkyValue, which is done by evaluating the [RepositoryDelegatorFunction](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryDelegatorFunction.java#L179), which calls into [NewLocalRepositoryFunction.fetch](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryFunction.java#L100), which creates these symlinks. On Linux these are all symlinks indeed, but on Windows only the directory symlinks are really symlinks, the files are copies (because we cannot create file symlinks).\r\n\r\nOn both Linux and Windows, FILE_STATEs and DIRECTORY_LISTING_STATEs of paths under the external directory have special handling -- they all depend on the corresponding REPOSITORY_DIRECTORY. This dependency is established [here](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/skyframe/FileStateFunction.java#L48) and [here](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/skyframe/DirectoryListingStateFunction.java#L54), by the [ExternalFilesHelper.maybeHandleExternalFile()](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/skyframe/ExternalFilesHelper.java#L208) --> [RepositoryFunction.addExternalFilesDependencies()](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java#L510) call chain, and it makes perfect sense, because it is the repository's SkyFunction that populates the external/B directory and creates the symlinks (or files) under it. Furthermore, the REPOSITORY_DIRECTORY depends on the DIRECTORY_LISTING_STATE of /src/B, so on both platforms Skyframe recomputes the REPOSITORY_DIRECTORY after we added /src/B/b.txt and correctly creates the new symlink (copy) under external/B/. This is all good.\r\n\r\nThe difference is that on Linux the GLOB depends on external/B/a.txt while on Windows it doesn't, because on Linux it's a symlink but on Windows it's a regular file. The reason is a performance optimization: GLOB only depends on FILE_STATEs of symlinks and directories but not files, to avoid recomputing the glob when a matched file's contents change, but to dirty the glob when a directory (or symlink to one) is replaced by a file with the same name (which affects recursive globbing).\r\n\r\nOn both Linux and Windows, the GLOB depends on the DIRECTORY_LISTING_STATE of external/B, and on Linux the GLOB also depends on the FILE_STATE of external/B/a.txt (because it's a symlink).\r\nOn both platforms, the FILE_STATE of external/B/a.txt depends on the REPOSITORY_DIRECTORY of @B, because the file is under external/. When we add the new file to B and rebuild, Skyframe's invalidation phase dirties the DIRECTORY_LISTING_STATE of /src/B, which dirties the REPOSITORY_DIRECTORY, which dirties the FILE_STATE of external/B/a.txt and on Linux this also dirties the GLOB.\r\n\r\nThis is a big difference: on Linux the GLOB is dirty but on Windows it's not. Upon closer inspection though, we notice that on Linux the GLOB is not recomputed but revalidated in the second build, and its SkyValue does not contain the newly added file -- however, the PACKAGE for \"@B//\" is recomputed and it does have the new glob contents and there's a new TARGET for @B//:b.txt -- what's going on?!\r\n\r\nTurns out there's some package reloading logic [in PackageFunction](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/skyframe/PackageFunction.java#L1188) that [uses Skyframe's dirtiness information](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/skyframe/PackageFunction.java#L908) to decide which GLOBs to recompute, but doesn't actually recompute the GlobValue. On Linux the GLOB is dirtied in the second build but on Windows it's not, so on Linux we re-glob (and find external/B/b.txt) but on Windows we don't (even though external/B/b.txt is there).\r\n\r\nWhy doesn't the GLOB depend on the DIRECTORY_LISTING_STATE of external/B though? [It actually does](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/skyframe/GlobFunction.java#L135). So why isn't this DIRECTORY_LISTING_STATE dirtied on Windows? It actually is! The problem is that the DIRECTORY_LISTING_STATE of external/B does not depend on the REPOSITORY_DIRECTORY of @B, because the [RepositoryFunction.addExternalFilesDependencies() call doesn't add this dependency if the path is the same as the repository's root path, in order to avoid a dependency cycle](https://github.com/bazelbuild/bazel/blob/d3d90630fa53d7d99e7e3de0a88bc0dfebefd50d/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java#L534-L551). Which is cool for the FILE_STATE of /src/B, but unnecessary for DIRECTORY_LISTING_STATE of it -- that's the bug.\r\n\r\nIf we change RepositoryFunction.addExternalFilesDependencies() to depend on the REPOSITORY_DIRECTORY for DIRECTORY_LISTING_STATEs, even of external/B itself, then everything works correctly on Windows. Becaues then adding the new file to /src/B will dirty the DIRECTORY_LISTING_STATE of /src/B, dirtying the REPOSITORY_DIRECTORY, dirtying the DIRECTORY_LISTING_STATE of /external/B, dirtying the GLOB, so the partial package reloading logic will re-compute that GLOB, even on Windows.\r\n\r\nIronically the bug was there on Linux too, just never manifested… because on Linux, external/B always contains symlinks, so the GLOB depends on their FILE_STATEs, and thus depends on the REPOSITORY_DIRECTORY."
] | [] | "2019-02-20T09:31:32Z" | [
"type: bug",
"P1",
"area-Windows",
"team-OSS"
] | Windows: new_local_repository doesn't reevaluate glob | ### Description of the problem / feature request:
If a "new_local_repository" rule with "build_file_content" creates a rule with a glob, and a rule in the main repo depends on this one, then Bazel on Windows won't detect changes of the glob. (It does on Linux.)
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. `git clone https://github.com/laszlocsomor/projects`
1. modify the "new_local_repository" rule's "path" in "bazel/examples/repo_rule_glob_bug/main_repo/WORKSPACE" to use the correct path on your system
1. `cd bazel/examples/repo_rule_glob_bug/main_repo`
1. `bazel build //foo:all`
List the contents of "bazel-genfiles/foo/x.txt" and "bazel-genfiles/foo/y.txt": they will contain "external/external_repo/a.txt" and "foo/foo.txt" respectively, as they should.
Now create "b.txt" in the external_repo directory (next to "a.txt") and "foo/bar.txt" (next to "foo.txt"), and rebuild "//foo:all".
If you now list the contents of the output files, "bazel-genfiles/foo/x.txt" is stale, it sill contains only "external/external_repo/a.txt", whereas "bazel-genfiles/foo/y.txt" correctly contains "foo/foo.txt" and "foo/bar.txt".
The problem doesn't seem to manifest when using a "local_repository" rule and having a BUILD file in the external_repo directory.
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
```
release 0.17.2
```
| [
"src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/DirectoryListingStateFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ExternalFilesHelper.java",
"src/main/java/com/google/devtools/build/lib/skyframe/FileStateFunction.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/DirectoryListingStateFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ExternalFilesHelper.java",
"src/main/java/com/google/devtools/build/lib/skyframe/FileStateFunction.java"
] | [
"src/test/shell/bazel/BUILD",
"src/test/shell/bazel/new_local_repo_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java
index ee2141dce465bc..f037d79339f5e8 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryFunction.java
@@ -508,7 +508,7 @@ protected static Path getExternalRepositoryDirectory(BlazeDirectories directorie
* encourage nor optimize for since it is not common. So the set of external files is small.
*/
public static void addExternalFilesDependencies(
- RootedPath rootedPath, BlazeDirectories directories, Environment env)
+ RootedPath rootedPath, boolean isDirectory, BlazeDirectories directories, Environment env)
throws IOException, InterruptedException {
Path externalRepoDir = getExternalRepositoryDirectory(directories);
PathFragment repositoryPath = rootedPath.asPath().relativeTo(externalRepoDir);
@@ -531,8 +531,8 @@ public static void addExternalFilesDependencies(
return;
}
- if (repositoryPath.segmentCount() > 1) {
- if (rule.getRuleClass().equals(LocalRepositoryRule.NAME)
+ if (isDirectory || repositoryPath.segmentCount() > 1) {
+ if (!isDirectory && rule.getRuleClass().equals(LocalRepositoryRule.NAME)
&& repositoryPath.endsWith(BuildFileName.WORKSPACE.getFilenameFragment())) {
// Ignore this, there is a dependency from LocalRepositoryFunction->WORKSPACE file already
return;
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/DirectoryListingStateFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/DirectoryListingStateFunction.java
index 49a6aaa2f2117c..c3d3ce9db9166b 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/DirectoryListingStateFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/DirectoryListingStateFunction.java
@@ -51,7 +51,7 @@ public DirectoryListingStateValue compute(SkyKey skyKey, Environment env)
RootedPath dirRootedPath = (RootedPath) skyKey.argument();
try {
- externalFilesHelper.maybeHandleExternalFile(dirRootedPath, env);
+ externalFilesHelper.maybeHandleExternalFile(dirRootedPath, true, env);
if (env.valuesMissing()) {
return null;
}
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/ExternalFilesHelper.java b/src/main/java/com/google/devtools/build/lib/skyframe/ExternalFilesHelper.java
index aa7f0362840109..37581eb6fe134e 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/ExternalFilesHelper.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/ExternalFilesHelper.java
@@ -205,7 +205,8 @@ FileType getAndNoteFileType(RootedPath rootedPath) {
* a {@link NonexistentImmutableExternalFileException} instead.
*/
@ThreadSafe
- void maybeHandleExternalFile(RootedPath rootedPath, SkyFunction.Environment env)
+ void maybeHandleExternalFile(
+ RootedPath rootedPath, boolean isDirectory, SkyFunction.Environment env)
throws NonexistentImmutableExternalFileException, IOException, InterruptedException {
FileType fileType = getAndNoteFileType(rootedPath);
if (fileType == FileType.INTERNAL) {
@@ -225,6 +226,6 @@ void maybeHandleExternalFile(RootedPath rootedPath, SkyFunction.Environment env)
Preconditions.checkState(
externalFileAction == ExternalFileAction.DEPEND_ON_EXTERNAL_PKG_FOR_EXTERNAL_REPO_PATHS,
externalFileAction);
- RepositoryFunction.addExternalFilesDependencies(rootedPath, directories, env);
+ RepositoryFunction.addExternalFilesDependencies(rootedPath, isDirectory, directories, env);
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/FileStateFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/FileStateFunction.java
index 15b876351093b6..940b2d72429640 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/FileStateFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/FileStateFunction.java
@@ -45,7 +45,7 @@ public FileStateValue compute(SkyKey skyKey, Environment env)
RootedPath rootedPath = (RootedPath) skyKey.argument();
try {
- externalFilesHelper.maybeHandleExternalFile(rootedPath, env);
+ externalFilesHelper.maybeHandleExternalFile(rootedPath, false, env);
if (env.valuesMissing()) {
return null;
}
| diff --git a/src/test/shell/bazel/BUILD b/src/test/shell/bazel/BUILD
index dc9f3033f44de2..547c888b35ec9b 100644
--- a/src/test/shell/bazel/BUILD
+++ b/src/test/shell/bazel/BUILD
@@ -806,3 +806,10 @@ sh_test(
data = [":test-deps"],
deps = ["@bazel_tools//tools/bash/runfiles"],
)
+
+sh_test(
+ name = "new_local_repo_test",
+ srcs = ["new_local_repo_test.sh"],
+ data = [":test-deps"],
+ deps = ["@bazel_tools//tools/bash/runfiles"],
+)
diff --git a/src/test/shell/bazel/new_local_repo_test.sh b/src/test/shell/bazel/new_local_repo_test.sh
new file mode 100644
index 00000000000000..ede0ed014d166d
--- /dev/null
+++ b/src/test/shell/bazel/new_local_repo_test.sh
@@ -0,0 +1,113 @@
+#!/bin/bash
+#
+# Copyright 2019 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# --- begin runfiles.bash initialization ---
+# Copy-pasted from Bazel's Bash runfiles library (tools/bash/runfiles/runfiles.bash).
+set -euo pipefail
+if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ if [[ -f "$0.runfiles_manifest" ]]; then
+ export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"
+ elif [[ -f "$0.runfiles/MANIFEST" ]]; then
+ export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"
+ elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
+ export RUNFILES_DIR="$0.runfiles"
+ fi
+fi
+if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then
+ source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"
+elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then
+ source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \
+ "$RUNFILES_MANIFEST_FILE" | cut -d ' ' -f 2-)"
+else
+ echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"
+ exit 1
+fi
+# --- end runfiles.bash initialization ---
+
+source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
+ || { echo "integration_test_setup.sh not found!" >&2; exit 1; }
+
+# `uname` returns the current platform, e.g "MSYS_NT-10.0" or "Linux".
+# `tr` converts all upper case letters to lower case.
+# `case` matches the result if the `uname | tr` expression to string prefixes
+# that use the same wildcards as names do in Bash, i.e. "msys*" matches strings
+# starting with "msys", and "*" matches everything (it's the default case).
+case "$(uname -s | tr [:upper:] [:lower:])" in
+msys*)
+ # As of 2019-02-20, Bazel on Windows only supports MSYS Bash.
+ declare -r is_windows=true
+ ;;
+*)
+ declare -r is_windows=false
+ ;;
+esac
+
+if "$is_windows"; then
+ # Disable MSYS path conversion that converts path-looking command arguments to
+ # Windows paths (even if they arguments are not in fact paths).
+ export MSYS_NO_PATHCONV=1
+ export MSYS2_ARG_CONV_EXCL="*"
+fi
+
+# Regression test for GitHub issue #6351, see
+# https://github.com/bazelbuild/bazel/issues/6351#issuecomment-465488344
+function test_glob_in_synthesized_build_file() {
+ local -r pkg=${FUNCNAME[0]}
+ mkdir $pkg || fail "mkdir $pkg"
+ mkdir $pkg/A || fail "mkdir $pkg/A"
+ mkdir $pkg/B || fail "mkdir $pkg/B"
+
+ cat >$pkg/A/WORKSPACE <<'eof'
+new_local_repository(
+ name = "B",
+ build_file_content = """
+filegroup(
+ name = "F",
+ srcs = glob(["*.txt"]),
+ visibility = ["//visibility:public"],
+)
+""",
+ path = "../B",
+)
+eof
+
+ cat >$pkg/A/BUILD <<'eof'
+genrule(
+ name = "G",
+ srcs = ["@B//:F"],
+ outs = ["g.txt"],
+ cmd = "echo $(SRCS) > $@",
+)
+eof
+
+ echo "dummy" >$pkg/B/a.txt
+
+ # Build 1: x.txt should contain external/B/a.txt
+ cd $pkg/A
+ bazel build //:G || fail "build failed"
+ cat bazel-genfiles/g.txt >$TEST_log
+ expect_log "external/B/a.txt"
+ expect_not_log "external/B/b.txt"
+
+ # Build 2: add B/b.txt and see if the glob picks it up.
+ echo "dummy" > ../B/b.txt
+ bazel build //:G || fail "build failed"
+ cat bazel-genfiles/g.txt >$TEST_log
+ expect_log "external/B/a.txt"
+ expect_log "external/B/b.txt"
+}
+
+run_suite "new_local_repository correctness tests"
| train | train | 2019-02-20T09:55:17 | "2018-10-10T20:41:48Z" | laszlocsomor | test |
bazelbuild/bazel/6362_6424 | bazelbuild/bazel | bazelbuild/bazel/6362 | bazelbuild/bazel/6424 | [
"timestamp(timedelta=0.0, similarity=0.8539077854347784)"
] | 486a2fb12281408187951d83e7c46c3c80e96afd | 2328f423155e44183e507078ff075bd219ed1e2b | [
"Can you provide example output showing where the message should be?",
"This is a snippet from an output from a failed build for TF:\r\n\r\nERROR: /tmpfs/tmp/bazel/external/org_tensorflow/third_party/toolchains/preconfig/ubuntu14.04/cuda9.0-cudnn7/cuda/BUILD:206:1: Couldn't build file external/org_tensorflow/third_party/toolchains/preconfig/ubuntu14.04/cuda9.0-cudnn7/cuda/cuda/include/CL/cl.h: Executing genrule @org_tensorflow//third_party/toolchains/preconfig/ubuntu14.04/cuda9.0-cudnn7/cuda:cuda-include failed (Exit 1)\r\ncp: cannot stat '/usr/local/cuda-9.0/include/CL/cl.h': No such file or directory\r\n[9,866 / 10,412] 278 / 503 tests, 278 failed; no action\r\n\r\nThe error message coming from the use of --verbose_failures is:\r\n\"cp: cannot stat '/usr/local/cuda-9.0/include/CL/cl.h': No such file or directory\"\r\n\r\nThis error occurred because the wrong platform was selected to run this action (due to a user mistake in flags)\r\n\r\nIt would have been ideal to get something like\r\n\r\ncp: cannot stat '/usr/local/cuda-9.0/include/CL/cl.h': No such file or directory\r\nPlatform info: this action ran in <something about the platform that either shows all details here or points me to the platform target that was selected for this action>\r\n\r\nPlease let me know if you want more details / a more comprehensive example.\r\n"
] | [
"nit: Bogus indentation, here and below.",
"Why null? Why cannot we use the same value as in the branch below?",
"Why all these no-op changes here? I mean, I guess they're fine, but they make it harder to see what actually changed :)",
"Sorry, I just wanted to shorten my new target, but my regex was a little greedy and fixed all of the local targets. I can revert everything except command-utils if you'd like.",
"In an ideal world, we'd have two different execution platforms here:\r\n- The actual spawn's execution platform, which would describe the sandbox (and ideally give configuration for it)\r\n- The sandbox's execution platform, which describes the environment that the sandbox container can run in.\r\n\r\nWe don't actually define either of these very well right now, but it's definitely wrong to assume they're the same, so it's best to just pass null and not describe it.",
"The formatter was confused because this is correct but previous commits left the indent wrong on the previous lines. Fixed it.",
"(I see now that the two branches are subtly different in what they call `get*` on.)\r\n\r\nBut can the platforms between the sandbox and the action ever be different?",
"One of my goals is to better couple execution strategies and platforms. Ideally, we'd end up with platform definitions like this (this is entirely a strawman, don't take any actual syntax seriously):\r\n\r\n```\r\nplatform(name = \"linux_sandbox\",\r\n constraint_values = [...],\r\n execution_strategy = \"linux-sandbox\",\r\n execution_properties = \"\"\"\r\n sandbox_base_dir: /tmp/sandbox\r\n sandbox_allow_networking: false\r\n \"\"\")\r\n\r\nplatform(name = \"host\",\r\n constraint_values = [...],\r\n)\r\n```\r\n\r\nIn this case, both of these are execution platforms, but \"host\" is the platform the sandbox runs on. They might have identical constraint_values, but they mean very different things.",
"Oh man, I was going to point you at someone else about this platform stuff... until I dug who \"katre\" was, so I cannot point you at yourself ;-)"
] | "2018-10-17T15:49:53Z" | [
"type: feature request",
"P1",
"team-Configurability"
] | Print platform info with error message when -versbose_failures is selected |
### Description of the problem / feature request:
Feature Request: Print platform info with error message when -verbose_failures is selected.
If a user passes the verbose_failures and the build fails, the error message should include some info about which platform was used to run the failed action.
### Feature requests: what underlying problem are you trying to solve with this feature?
Users can make simple mistakes that lead to incorrect platform being selected. Error message showing platform would help identify these kinds of issues very easily.
| [
"src/main/java/com/google/devtools/build/lib/BUILD",
"src/main/java/com/google/devtools/build/lib/actions/BUILD",
"src/main/java/com/google/devtools/build/lib/exec/AbstractSpawnStrategy.java",
"src/main/java/com/google/devtools/build/lib/query2/BUILD",
"src/main/java/com/google/devtools/build/lib/sandbox/AbstractSandboxSpawnRunner.java",
"src/main/java/com/google/devtools/build/lib/sandbox/BUILD",
"src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java",
"src/main/java/com/google/devtools/build/lib/util/CommandUtils.java"
] | [
"src/main/java/com/google/devtools/build/lib/BUILD",
"src/main/java/com/google/devtools/build/lib/actions/BUILD",
"src/main/java/com/google/devtools/build/lib/exec/AbstractSpawnStrategy.java",
"src/main/java/com/google/devtools/build/lib/query2/BUILD",
"src/main/java/com/google/devtools/build/lib/sandbox/AbstractSandboxSpawnRunner.java",
"src/main/java/com/google/devtools/build/lib/sandbox/BUILD",
"src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java",
"src/main/java/com/google/devtools/build/lib/util/CommandUtils.java"
] | [
"src/test/java/com/google/devtools/build/lib/BUILD",
"src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/BUILD b/src/main/java/com/google/devtools/build/lib/BUILD
index 42c7e7fd28831a..3ed78099f9601c 100644
--- a/src/main/java/com/google/devtools/build/lib/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/BUILD
@@ -100,7 +100,7 @@ java_library(
"//conditions:default": ["//src/main/native:libunix.so"],
}),
deps = [
- "//src/main/java/com/google/devtools/build/lib:os_util",
+ ":os_util",
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/profiler",
"//src/main/java/com/google/devtools/build/lib/shell",
@@ -154,8 +154,8 @@ java_library(
name = "process_util",
srcs = ["util/ProcessUtils.java"],
deps = [
- "//src/main/java/com/google/devtools/build/lib:os_util",
- "//src/main/java/com/google/devtools/build/lib:unix",
+ ":os_util",
+ ":unix",
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/windows",
"//src/main/java/com/google/devtools/build/lib/windows/jni:processes",
@@ -181,11 +181,28 @@ java_library(
],
)
+COMMAND_UTILS_SRCS = [
+ "util/CommandFailureUtils.java",
+ "util/CommandUtils.java",
+]
+
+java_library(
+ name = "command-utils",
+ srcs = COMMAND_UTILS_SRCS,
+ deps = [
+ ":util",
+ "//src/main/java/com/google/devtools/build/lib/analysis/platform",
+ "//src/main/java/com/google/devtools/build/lib/shell",
+ "//third_party:guava",
+ "//third_party:jsr305",
+ ],
+)
+
java_library(
name = "util",
srcs = glob(
["util/*.java"],
- exclude = [
+ exclude = COMMAND_UTILS_SRCS + [
"util/BlazeClock.java",
"util/Clock.java",
"util/ExitCode.java",
@@ -204,20 +221,20 @@ java_library(
],
),
exports = [
- "//src/main/java/com/google/devtools/build/lib:base-util",
- "//src/main/java/com/google/devtools/build/lib:exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:filetype",
- "//src/main/java/com/google/devtools/build/lib:os_util",
- "//src/main/java/com/google/devtools/build/lib:resource_usage",
- "//src/main/java/com/google/devtools/build/lib:string_util",
+ ":base-util",
+ ":exitcode-external",
+ ":filetype",
+ ":os_util",
+ ":resource_usage",
+ ":string_util",
"//src/main/java/com/google/devtools/build/lib/clock",
"//src/main/java/com/google/devtools/build/lib/collect",
],
deps = [
- "//src/main/java/com/google/devtools/build/lib:base-util",
- "//src/main/java/com/google/devtools/build/lib:exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:os_util",
- "//src/main/java/com/google/devtools/build/lib:unix",
+ ":base-util",
+ ":exitcode-external",
+ ":os_util",
+ ":unix",
"//src/main/java/com/google/devtools/build/lib/collect",
"//src/main/java/com/google/devtools/build/lib/collect/compacthashset",
"//src/main/java/com/google/devtools/build/lib/concurrent",
@@ -296,7 +313,7 @@ java_library(
name = "events",
srcs = glob(["events/*.java"]),
deps = [
- "//src/main/java/com/google/devtools/build/lib:io",
+ ":io",
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/skyframe/serialization/autocodec",
"//src/main/java/com/google/devtools/build/lib/vfs",
@@ -316,8 +333,8 @@ java_library(
java_library(
name = "foundation",
exports = [
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":events",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/vfs",
"//src/main/java/com/google/devtools/common/options",
@@ -332,9 +349,9 @@ java_library(
name = "skylark-lang",
visibility = ["//visibility:public"],
exports = [
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:syntax",
+ ":events",
+ ":skylarkinterface",
+ ":syntax",
"//src/main/java/com/google/devtools/build/lib/vfs",
"//src/main/java/com/google/devtools/build/lib/vfs:pathfragment",
"//src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs",
@@ -399,9 +416,9 @@ java_library(
"syntax/**/*.java",
]),
deps = [
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":events",
+ ":skylarkinterface",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/cmdline",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
"//src/main/java/com/google/devtools/build/lib/concurrent",
@@ -446,17 +463,17 @@ java_library(
exclude = ["packages/BuilderFactoryForTesting.java"],
),
exports = [
- "//src/main/java/com/google/devtools/build/lib:syntax",
+ ":syntax",
"//src/main/java/com/google/devtools/build/lib/cmdline",
],
deps = [
- "//src/main/java/com/google/devtools/build/lib:config-matching-provider",
- "//src/main/java/com/google/devtools/build/lib:config-transitions",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:syntax",
- "//src/main/java/com/google/devtools/build/lib:transitive-info-provider",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":config-matching-provider",
+ ":config-transitions",
+ ":events",
+ ":skylarkinterface",
+ ":syntax",
+ ":transitive-info-provider",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
"//src/main/java/com/google/devtools/build/lib/buildeventstream/proto:build_event_stream_java_proto",
"//src/main/java/com/google/devtools/build/lib/cmdline",
@@ -491,8 +508,8 @@ java_library(
java_library(
name = "packages",
exports = [
- "//src/main/java/com/google/devtools/build/lib:foundation",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
+ ":foundation",
+ ":packages-internal",
],
)
@@ -519,8 +536,8 @@ java_library(
"analysis/ProviderCollection.java",
],
deps = [
+ ":packages-internal",
":transitive-info-provider",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
"//third_party:jsr305",
],
)
@@ -532,7 +549,7 @@ java_library(
"//src/main/java/com/google/devtools/build/lib/rules/config:__pkg__",
],
deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
+ ":build-base",
],
)
@@ -574,24 +591,25 @@ java_library(
"runtime/BuildEventStreamerUtils.java",
],
exports = [
- "//src/main/java/com/google/devtools/build/lib:transitive-info-provider",
+ ":transitive-info-provider",
],
deps = [
+ ":base-util",
":build-request-options",
+ ":command-utils",
+ ":events",
+ ":exitcode-external",
+ ":io",
+ ":keep-going-option",
+ ":os_util",
+ ":packages-internal",
+ ":process_util",
":provider-collection",
- "//src/main/java/com/google/devtools/build/lib:base-util",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:io",
- "//src/main/java/com/google/devtools/build/lib:keep-going-option",
- "//src/main/java/com/google/devtools/build/lib:os_util",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:process_util",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:syntax",
- "//src/main/java/com/google/devtools/build/lib:transitive-info-provider",
- "//src/main/java/com/google/devtools/build/lib:unix",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":skylarkinterface",
+ ":syntax",
+ ":transitive-info-provider",
+ ":unix",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:commandline_item",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
@@ -651,22 +669,22 @@ java_library(
],
),
deps = [
- "//src/main/java/com/google/devtools/build/lib:RpcSupport",
- "//src/main/java/com/google/devtools/build/lib:android-rules",
- "//src/main/java/com/google/devtools/build/lib:bazel",
- "//src/main/java/com/google/devtools/build/lib:bazel-repository",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:build-info",
- "//src/main/java/com/google/devtools/build/lib:core-rules",
- "//src/main/java/com/google/devtools/build/lib:core-workspace-rules",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:java-compilation",
- "//src/main/java/com/google/devtools/build/lib:java-rules",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:proto-rules",
- "//src/main/java/com/google/devtools/build/lib:python-rules",
- "//src/main/java/com/google/devtools/build/lib:testing-support-rules",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":RpcSupport",
+ ":android-rules",
+ ":bazel",
+ ":bazel-repository",
+ ":build-base",
+ ":build-info",
+ ":core-rules",
+ ":core-workspace-rules",
+ ":events",
+ ":java-compilation",
+ ":java-rules",
+ ":packages-internal",
+ ":proto-rules",
+ ":python-rules",
+ ":testing-support-rules",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/analysis/platform",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
@@ -707,15 +725,15 @@ java_library(
name = "bazel/BazelRepositoryModule",
srcs = ["bazel/BazelRepositoryModule.java"],
deps = [
- "//src/main/java/com/google/devtools/build/lib:bazel-commands",
- "//src/main/java/com/google/devtools/build/lib:bazel-repository",
- "//src/main/java/com/google/devtools/build/lib:bazel-rules",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:io",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:runtime",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":bazel-commands",
+ ":bazel-repository",
+ ":bazel-rules",
+ ":build-base",
+ ":events",
+ ":io",
+ ":packages-internal",
+ ":runtime",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/bazel/repository/cache",
"//src/main/java/com/google/devtools/build/lib/bazel/repository/downloader",
"//src/main/java/com/google/devtools/build/lib/cmdline",
@@ -737,20 +755,20 @@ java_library(
"bazel/rules/python/python_stub_template.txt",
],
deps = [
+ ":bazel",
+ ":bazel-commands",
":bazel-coverage",
+ ":bazel-modules",
+ ":bazel-repository",
+ ":bazel-rules",
":bazel/BazelRepositoryModule",
+ ":build-base",
+ ":build-info",
+ ":events",
":exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:bazel",
- "//src/main/java/com/google/devtools/build/lib:bazel-commands",
- "//src/main/java/com/google/devtools/build/lib:bazel-modules",
- "//src/main/java/com/google/devtools/build/lib:bazel-repository",
- "//src/main/java/com/google/devtools/build/lib:bazel-rules",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:build-info",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:io",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":io",
+ ":packages-internal",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/bazel/debug:workspace-rule-module",
"//src/main/java/com/google/devtools/build/lib/bazel/repository/cache",
"//src/main/java/com/google/devtools/build/lib/bazel/repository/downloader",
@@ -779,13 +797,13 @@ java_library(
],
),
deps = [
+ ":build-base",
+ ":build-info",
+ ":events",
":exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:build-info",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:io",
- "//src/main/java/com/google/devtools/build/lib:runtime",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":io",
+ ":runtime",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/shell",
"//src/main/java/com/google/devtools/build/lib/skyframe/serialization/autocodec",
@@ -804,15 +822,15 @@ java_library(
"bazel/commands/sync.txt",
],
deps = [
+ ":build-base",
+ ":events",
+ ":exitcode-external",
+ ":java-compilation",
+ ":java-rules",
":keep-going-option",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:java-compilation",
- "//src/main/java/com/google/devtools/build/lib:java-rules",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:runtime",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":packages-internal",
+ ":runtime",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/query2",
"//src/main/java/com/google/devtools/build/lib/query2:abstract-blaze-query-env",
"//src/main/java/com/google/devtools/build/lib/query2:query-engine",
@@ -829,10 +847,10 @@ java_library(
name = "bazel-coverage",
srcs = glob(["bazel/coverage/*.java"]),
deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:runtime",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":build-base",
+ ":events",
+ ":runtime",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
"//src/main/java/com/google/devtools/build/lib/concurrent",
@@ -855,15 +873,15 @@ java_library(
exclude = ["bazel/repository/MavenConnector.java"],
),
deps = [
+ ":build-base",
+ ":events",
+ ":io",
+ ":maven-connector",
+ ":packages-internal",
+ ":runtime",
+ ":skylarkinterface",
+ ":util",
"//src/java_tools/singlejar/java/com/google/devtools/build/zip",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:io",
- "//src/main/java/com/google/devtools/build/lib:maven-connector",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:runtime",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/bazel/debug:workspace-rule-event",
"//src/main/java/com/google/devtools/build/lib/bazel/repository/cache",
@@ -909,9 +927,9 @@ java_library(
["rules/nativedeps/*.java"],
),
deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":build-base",
+ ":packages-internal",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/collect",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
@@ -930,10 +948,10 @@ java_library(
["rules/proto/*.java"],
),
deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":build-base",
+ ":packages-internal",
+ ":skylarkinterface",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:commandline_item",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
@@ -993,16 +1011,16 @@ java_library(
"rules/java/proto/StrictDepsUtils.java",
],
deps = [
+ ":RpcSupport",
+ ":build-base",
+ ":events",
+ ":java-compilation",
+ ":java-implicit-attributes",
+ ":packages-internal",
+ ":proto-rules",
":provider-collection",
- "//src/main/java/com/google/devtools/build/lib:RpcSupport",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:java-compilation",
- "//src/main/java/com/google/devtools/build/lib:java-implicit-attributes",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:proto-rules",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":skylarkinterface",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/collect",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
@@ -1026,10 +1044,10 @@ java_library(
name = "RpcSupport",
srcs = ["rules/java/proto/RpcSupport.java"],
deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:java-compilation",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:proto-rules",
+ ":build-base",
+ ":java-compilation",
+ ":packages-internal",
+ ":proto-rules",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/collect",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
@@ -1086,14 +1104,14 @@ java_library(
"rules/java/proto/GeneratedExtensionRegistryProvider.java",
],
deps = [
+ ":build-base",
+ ":build-info",
+ ":events",
+ ":java-implicit-attributes",
+ ":packages-internal",
":provider-collection",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:build-info",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:java-implicit-attributes",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":skylarkinterface",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:commandline_item",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
@@ -1128,8 +1146,8 @@ java_library(
["rules/core/*.java"],
),
deps = [
+ ":build-base",
":packages-internal",
- "//src/main/java/com/google/devtools/build/lib:build-base",
"//third_party:guava",
],
)
@@ -1143,10 +1161,10 @@ java_library(
"rules/repository/CoreWorkspaceRules.java",
],
deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:core-rules",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":build-base",
+ ":core-rules",
+ ":packages-internal",
+ ":util",
"//third_party:guava",
],
)
@@ -1157,13 +1175,13 @@ java_library(
["rules/test/*.java"],
),
deps = [
+ ":build-base",
+ ":core-rules",
":packages-internal",
":skylarkinterface",
+ ":syntax",
+ ":transitive-info-provider",
":util",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:core-rules",
- "//src/main/java/com/google/devtools/build/lib:syntax",
- "//src/main/java/com/google/devtools/build/lib:transitive-info-provider",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
"//src/main/java/com/google/devtools/build/lib/buildeventstream/proto:build_event_stream_proto",
@@ -1188,15 +1206,15 @@ java_library(
"rules/android/test_suite_property_name.txt",
],
deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:java-compilation",
- "//src/main/java/com/google/devtools/build/lib:java-rules",
- "//src/main/java/com/google/devtools/build/lib:nativedeps-rules",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:proto-rules",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":build-base",
+ ":events",
+ ":java-compilation",
+ ":java-rules",
+ ":nativedeps-rules",
+ ":packages-internal",
+ ":proto-rules",
+ ":skylarkinterface",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:commandline_item",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
@@ -1227,11 +1245,11 @@ java_library(
["rules/python/*.java"],
),
deps = [
+ ":build-base",
":events",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:skylarkinterface",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":packages-internal",
+ ":skylarkinterface",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/collect",
"//src/main/java/com/google/devtools/build/lib/collect/nestedset",
@@ -1251,12 +1269,12 @@ java_library(
java_library(
name = "shared-base-rules",
exports = [
- "//src/main/java/com/google/devtools/build/lib:android-rules",
- "//src/main/java/com/google/devtools/build/lib:java-compilation",
- "//src/main/java/com/google/devtools/build/lib:java-rules",
- "//src/main/java/com/google/devtools/build/lib:nativedeps-rules",
- "//src/main/java/com/google/devtools/build/lib:proto-rules",
- "//src/main/java/com/google/devtools/build/lib:python-rules",
+ ":android-rules",
+ ":java-compilation",
+ ":java-rules",
+ ":nativedeps-rules",
+ ":proto-rules",
+ ":python-rules",
],
)
@@ -1264,7 +1282,7 @@ java_library(
name = "build-request-options",
srcs = ["buildtool/BuildRequestOptions.java"],
deps = [
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
"//src/main/java/com/google/devtools/build/lib/vfs",
@@ -1295,11 +1313,11 @@ java_library(
"server/IdleServerTasks.java",
],
deps = [
+ ":exitcode-external",
+ ":io",
":runtime",
- "//src/main/java/com/google/devtools/build/lib:exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:io",
- "//src/main/java/com/google/devtools/build/lib:unix",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":unix",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/clock",
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/profiler",
@@ -1336,19 +1354,20 @@ java_library(
"server/signal/InterruptSignalHandler.java",
],
deps = [
+ ":build-base",
":build-request-options",
+ ":command-utils",
+ ":events",
+ ":exitcode-external",
+ ":io",
":keep-going-option",
":loading-phase-threads-option",
+ ":packages-internal",
+ ":process_util",
+ ":shared-base-rules",
+ ":unix",
+ ":util",
"//src/main/java/com/google/devtools/build/docgen:docgen_javalib",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:exitcode-external",
- "//src/main/java/com/google/devtools/build/lib:io",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:process_util",
- "//src/main/java/com/google/devtools/build/lib:shared-base-rules",
- "//src/main/java/com/google/devtools/build/lib:unix",
- "//src/main/java/com/google/devtools/build/lib:util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/actions:localhost_capacity",
"//src/main/java/com/google/devtools/build/lib/bazel/repository/downloader",
@@ -1414,17 +1433,17 @@ java_library(
"runtime/commands/*.txt",
"runtime/mobileinstall/*.txt",
]) + [
- "//src/main/java/com/google/devtools/build/lib:runtime/commands/LICENSE",
+ ":runtime/commands/LICENSE",
],
- exports = ["//src/main/java/com/google/devtools/build/lib:runtime"],
+ exports = [":runtime"],
)
java_library(
name = "all-build-rules",
exports = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:packages-internal",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":build-base",
+ ":packages-internal",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/actions",
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/graph",
@@ -1438,11 +1457,11 @@ java_library(
java_library(
name = "build",
exports = [
- "//src/main/java/com/google/devtools/build/lib:all-build-rules",
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:foundation",
- "//src/main/java/com/google/devtools/build/lib:packages",
- "//src/main/java/com/google/devtools/build/lib:query2",
+ ":all-build-rules",
+ ":build-base",
+ ":foundation",
+ ":packages",
+ ":query2",
"//src/main/java/com/google/devtools/build/lib/actions",
],
)
@@ -1455,10 +1474,10 @@ java_library(
java_library(
name = "query2",
exports = [
- "//src/main/java/com/google/devtools/build/lib:events",
- "//src/main/java/com/google/devtools/build/lib:foundation",
- "//src/main/java/com/google/devtools/build/lib:packages",
- "//src/main/java/com/google/devtools/build/lib:util",
+ ":events",
+ ":foundation",
+ ":packages",
+ ":util",
"//src/main/java/com/google/devtools/build/lib/concurrent",
"//src/main/java/com/google/devtools/build/lib/graph",
"//src/main/java/com/google/devtools/build/lib/query2",
@@ -1477,9 +1496,9 @@ java_binary(
],
main_class = "com.google.devtools.build.lib.bazel.Bazel",
runtime_deps = [
+ ":bazel-main",
":server",
- "//src/main/java/com/google/devtools/build/lib:bazel-main",
- "//src/main/java/com/google/devtools/build/lib:single-line-formatter", # See startup_options.cc
+ ":single-line-formatter", # See startup_options.cc
],
)
@@ -1501,7 +1520,7 @@ filegroup(
genrule(
name = "gen_buildencyclopedia",
- srcs = ["//src/main/java/com/google/devtools/build/lib:docs_embedded_in_sources"],
+ srcs = [":docs_embedded_in_sources"],
outs = ["build-encyclopedia.zip"],
cmd = (
"mkdir -p $(@D)/be && " +
@@ -1540,7 +1559,7 @@ genrule(
"cat $(location //site:command-line-reference-suffix.html) >> $@"
),
tools = [
- "//src/main/java/com/google/devtools/build/lib:bazel/BazelServer",
+ ":bazel/BazelServer",
],
visibility = [
"//site:__pkg__",
diff --git a/src/main/java/com/google/devtools/build/lib/actions/BUILD b/src/main/java/com/google/devtools/build/lib/actions/BUILD
index 005e53593ae9cb..430e3a39fff3f9 100644
--- a/src/main/java/com/google/devtools/build/lib/actions/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/actions/BUILD
@@ -30,6 +30,7 @@ java_library(
deps = [
":commandline_item",
":localhost_capacity",
+ "//src/main/java/com/google/devtools/build/lib:command-utils",
"//src/main/java/com/google/devtools/build/lib:events",
"//src/main/java/com/google/devtools/build/lib:io",
"//src/main/java/com/google/devtools/build/lib:packages-internal",
diff --git a/src/main/java/com/google/devtools/build/lib/exec/AbstractSpawnStrategy.java b/src/main/java/com/google/devtools/build/lib/exec/AbstractSpawnStrategy.java
index e186975dd59463..d8908639fbabb0 100644
--- a/src/main/java/com/google/devtools/build/lib/exec/AbstractSpawnStrategy.java
+++ b/src/main/java/com/google/devtools/build/lib/exec/AbstractSpawnStrategy.java
@@ -147,7 +147,8 @@ public List<SpawnResult> exec(
actionExecutionContext.getVerboseFailures(),
spawn.getArguments(),
spawn.getEnvironment(),
- cwd);
+ cwd,
+ spawn.getExecutionPlatform());
throw new SpawnExecException(message, spawnResult, /*forciblyRunRemotely=*/false);
}
return ImmutableList.of(spawnResult);
diff --git a/src/main/java/com/google/devtools/build/lib/query2/BUILD b/src/main/java/com/google/devtools/build/lib/query2/BUILD
index 3ccf9fb5bd2fc0..dea8203a771ded 100644
--- a/src/main/java/com/google/devtools/build/lib/query2/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/query2/BUILD
@@ -23,6 +23,7 @@ java_library(
":query-engine",
":query-output",
"//src/main/java/com/google/devtools/build/lib:build-base",
+ "//src/main/java/com/google/devtools/build/lib:command-utils",
"//src/main/java/com/google/devtools/build/lib:events",
"//src/main/java/com/google/devtools/build/lib:packages-internal",
"//src/main/java/com/google/devtools/build/lib:util",
diff --git a/src/main/java/com/google/devtools/build/lib/sandbox/AbstractSandboxSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/sandbox/AbstractSandboxSpawnRunner.java
index 5610242eaaefbb..2d4eb2487c824f 100644
--- a/src/main/java/com/google/devtools/build/lib/sandbox/AbstractSandboxSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/sandbox/AbstractSandboxSpawnRunner.java
@@ -123,19 +123,25 @@ private final SpawnResult run(
sandbox.getArguments().toArray(new String[0]),
sandbox.getEnvironment(),
sandbox.getSandboxExecRoot().getPathFile());
- String failureMessage;
- if (sandboxOptions.sandboxDebug) {
- failureMessage =
- CommandFailureUtils.describeCommandFailure(
- true, sandbox.getArguments(), sandbox.getEnvironment(), execRoot.getPathString());
- } else {
- failureMessage =
- CommandFailureUtils.describeCommandFailure(
- verboseFailures,
- originalSpawn.getArguments(),
- originalSpawn.getEnvironment(),
- execRoot.getPathString()) + SANDBOX_DEBUG_SUGGESTION;
- }
+ String failureMessage;
+ if (sandboxOptions.sandboxDebug) {
+ failureMessage =
+ CommandFailureUtils.describeCommandFailure(
+ true,
+ sandbox.getArguments(),
+ sandbox.getEnvironment(),
+ execRoot.getPathString(),
+ null);
+ } else {
+ failureMessage =
+ CommandFailureUtils.describeCommandFailure(
+ verboseFailures,
+ originalSpawn.getArguments(),
+ originalSpawn.getEnvironment(),
+ execRoot.getPathString(),
+ originalSpawn.getExecutionPlatform())
+ + SANDBOX_DEBUG_SUGGESTION;
+ }
long startTime = System.currentTimeMillis();
CommandResult commandResult;
diff --git a/src/main/java/com/google/devtools/build/lib/sandbox/BUILD b/src/main/java/com/google/devtools/build/lib/sandbox/BUILD
index c8da1fd574f4af..5298b94b03f16d 100644
--- a/src/main/java/com/google/devtools/build/lib/sandbox/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/sandbox/BUILD
@@ -17,6 +17,7 @@ java_library(
],
deps = [
"//src/main/java/com/google/devtools/build/lib:build-base",
+ "//src/main/java/com/google/devtools/build/lib:command-utils",
"//src/main/java/com/google/devtools/build/lib:events",
"//src/main/java/com/google/devtools/build/lib:io",
"//src/main/java/com/google/devtools/build/lib:packages-internal",
diff --git a/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java b/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java
index 5317e818c962cb..df3f666f8e9315 100644
--- a/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java
+++ b/src/main/java/com/google/devtools/build/lib/util/CommandFailureUtils.java
@@ -18,6 +18,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Ordering;
+import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import java.io.File;
import java.util.Collection;
import java.util.Comparator;
@@ -225,39 +226,50 @@ public static String describeCommand(
}
/**
- * Construct an error message that describes a failed command invocation.
- * Currently this returns a message of the form "error executing command foo
- * bar baz".
+ * Construct an error message that describes a failed command invocation. Currently this returns a
+ * message of the form "error executing command foo bar baz".
*/
public static String describeCommandError(
boolean verbose,
Collection<String> commandLineElements,
Map<String, String> env,
- String cwd) {
+ String cwd,
+ @Nullable PlatformInfo executionPlatform) {
CommandDescriptionForm form = verbose
? CommandDescriptionForm.COMPLETE
: CommandDescriptionForm.ABBREVIATED;
- return "error executing command " + (verbose ? "\n " : "")
- + describeCommand(form, /* prettyPrintArgs= */false, commandLineElements, env, cwd);
+
+ StringBuilder output = new StringBuilder();
+ output.append("error executing command ");
+ if (verbose) {
+ output.append("\n ");
+ }
+ output.append(
+ describeCommand(form, /* prettyPrintArgs= */ false, commandLineElements, env, cwd));
+ if (verbose && executionPlatform != null) {
+ output.append("\n");
+ output.append("Execution platform: ").append(executionPlatform.label());
+ }
+ return output.toString();
}
/**
- * Construct an error message that describes a failed command invocation.
- * Currently this returns a message of the form "foo failed: error executing
- * command /dir/foo bar baz".
+ * Construct an error message that describes a failed command invocation. Currently this returns a
+ * message of the form "foo failed: error executing command /dir/foo bar baz".
*/
public static String describeCommandFailure(
boolean verbose,
Collection<String> commandLineElements,
Map<String, String> env,
- String cwd) {
+ String cwd,
+ @Nullable PlatformInfo executionPlatform) {
String commandName = commandLineElements.iterator().next();
// Extract the part of the command name after the last "/", if any.
String shortCommandName = new File(commandName).getName();
- return shortCommandName + " failed: " +
- describeCommandError(verbose, commandLineElements, env, cwd);
+ return shortCommandName
+ + " failed: "
+ + describeCommandError(verbose, commandLineElements, env, cwd, executionPlatform);
}
-
}
diff --git a/src/main/java/com/google/devtools/build/lib/util/CommandUtils.java b/src/main/java/com/google/devtools/build/lib/util/CommandUtils.java
index ef2d18d1d48c9a..35c5d887d7532c 100644
--- a/src/main/java/com/google/devtools/build/lib/util/CommandUtils.java
+++ b/src/main/java/com/google/devtools/build/lib/util/CommandUtils.java
@@ -18,7 +18,6 @@
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandException;
import com.google.devtools.build.lib.shell.CommandResult;
-
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
@@ -48,8 +47,8 @@ private static String cwd(Command command) {
* bar baz".
*/
public static String describeCommandError(boolean verbose, Command command) {
- return CommandFailureUtils.describeCommandError(verbose, commandLine(command), env(command),
- cwd(command));
+ return CommandFailureUtils.describeCommandError(
+ verbose, commandLine(command), env(command), cwd(command), null);
}
/**
@@ -58,8 +57,8 @@ public static String describeCommandError(boolean verbose, Command command) {
* command /dir/foo bar baz".
*/
public static String describeCommandFailure(boolean verbose, Command command) {
- return CommandFailureUtils.describeCommandFailure(verbose, commandLine(command), env(command),
- cwd(command));
+ return CommandFailureUtils.describeCommandFailure(
+ verbose, commandLine(command), env(command), cwd(command), null);
}
/**
| diff --git a/src/test/java/com/google/devtools/build/lib/BUILD b/src/test/java/com/google/devtools/build/lib/BUILD
index 147f68e698923a..31a9ef2225b561 100644
--- a/src/test/java/com/google/devtools/build/lib/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/BUILD
@@ -318,9 +318,12 @@ java_test(
":guava_junit_truth",
":test_runner",
":testutil",
+ "//src/main/java/com/google/devtools/build/lib:command-utils",
"//src/main/java/com/google/devtools/build/lib:simple-log-handler",
"//src/main/java/com/google/devtools/build/lib:single-line-formatter",
"//src/main/java/com/google/devtools/build/lib:util",
+ "//src/main/java/com/google/devtools/build/lib/analysis/platform",
+ "//src/main/java/com/google/devtools/build/lib/cmdline",
"//src/main/java/com/google/devtools/build/lib/shell",
"//src/main/java/com/google/devtools/build/lib/skyframe/serialization/testutils",
"//src/main/java/com/google/devtools/build/lib/vfs",
diff --git a/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java b/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java
index f13758eecc359b..0ce5b5c423ac15 100644
--- a/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/CommandFailureUtilsTest.java
@@ -15,6 +15,8 @@
import static com.google.common.truth.Truth.assertThat;
+import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
+import com.google.devtools.build.lib.cmdline.Label;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -38,9 +40,14 @@ public void describeCommandError() throws Exception {
env.put("FOO", "foo");
env.put("PATH", "/usr/bin:/bin:/sbin");
String cwd = "/my/working/directory";
- String message = CommandFailureUtils.describeCommandError(false, Arrays.asList(args), env, cwd);
+ PlatformInfo executionPlatform =
+ PlatformInfo.builder().setLabel(Label.parseAbsoluteUnchecked("//platform:exec")).build();
+ String message =
+ CommandFailureUtils.describeCommandError(
+ false, Arrays.asList(args), env, cwd, executionPlatform);
String verboseMessage =
- CommandFailureUtils.describeCommandError(true, Arrays.asList(args), env, cwd);
+ CommandFailureUtils.describeCommandError(
+ true, Arrays.asList(args), env, cwd, executionPlatform);
assertThat(message)
.isEqualTo(
"error executing command some_command arg1 "
@@ -60,7 +67,8 @@ public void describeCommandError() throws Exception {
+ "arg11 arg12 arg13 arg14 arg15 arg16 arg17 arg18 "
+ "arg19 arg20 arg21 arg22 arg23 arg24 arg25 arg26 "
+ "arg27 arg28 arg29 arg30 arg31 arg32 arg33 arg34 "
- + "arg35 arg36 arg37 arg38 arg39)");
+ + "arg35 arg36 arg37 arg38 arg39)\n"
+ + "Execution platform: //platform:exec");
}
@Test
@@ -73,10 +81,14 @@ public void describeCommandFailure() throws Exception {
env.put("FOO", "foo");
env.put("PATH", "/usr/bin:/bin:/sbin");
String cwd = null;
+ PlatformInfo executionPlatform =
+ PlatformInfo.builder().setLabel(Label.parseAbsoluteUnchecked("//platform:exec")).build();
String message =
- CommandFailureUtils.describeCommandFailure(false, Arrays.asList(args), env, cwd);
+ CommandFailureUtils.describeCommandFailure(
+ false, Arrays.asList(args), env, cwd, executionPlatform);
String verboseMessage =
- CommandFailureUtils.describeCommandFailure(true, Arrays.asList(args), env, cwd);
+ CommandFailureUtils.describeCommandFailure(
+ true, Arrays.asList(args), env, cwd, executionPlatform);
assertThat(message)
.isEqualTo(
"sh failed: error executing command "
@@ -87,7 +99,8 @@ public void describeCommandFailure() throws Exception {
+ " (exec env - \\\n"
+ " FOO=foo \\\n"
+ " PATH=/usr/bin:/bin:/sbin \\\n"
- + " /bin/sh -c 'echo Some errors 1>&2; echo Some output; exit 42')");
+ + " /bin/sh -c 'echo Some errors 1>&2; echo Some output; exit 42')\n"
+ + "Execution platform: //platform:exec");
}
@Test
| train | train | 2018-10-17T17:12:26 | "2018-10-11T19:03:06Z" | nlopezgi | test |
bazelbuild/bazel/6405_6609 | bazelbuild/bazel | bazelbuild/bazel/6405 | bazelbuild/bazel/6609 | [
"timestamp(timedelta=1.0, similarity=0.8519683283943104)"
] | 6a30ed637c7d2e4c33edca566d0912a8f9235792 | 2732641bfdd471e2dcff4ebaaf1a290768e34d38 | [] | [] | "2018-11-06T10:56:20Z" | [
"type: bug",
"P2",
"category: misc > testing",
"area-EngProd",
"team-OSS"
] | Bazel CI: not running tests for Singlejar | ### Description of the problem / feature request:
It seems that the Bazel CI does not run tests in `//src/tools/singlejar:*`. | [
".bazelci/postsubmit.yml",
".bazelci/presubmit.yml"
] | [
".bazelci/postsubmit.yml",
".bazelci/presubmit.yml"
] | [] | diff --git a/.bazelci/postsubmit.yml b/.bazelci/postsubmit.yml
index 4ec4608b7ee5f9..e09d58352b38ee 100644
--- a/.bazelci/postsubmit.yml
+++ b/.bazelci/postsubmit.yml
@@ -13,10 +13,9 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
ubuntu1604:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -30,10 +29,9 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
ubuntu1804:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -47,10 +45,9 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
ubuntu1804_nojava:
build_flags:
- "--javabase=@openjdk_linux_archive//:runtime"
@@ -63,6 +60,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
# We can't run Android tests without an installed Android SDK / NDK.
- "-//src/test/java/com/google/devtools/build/android/..."
@@ -102,8 +100,7 @@ platforms:
- "-//src/test/shell/integration:output_filter_test"
- "-//src/test/shell/integration:stub_finds_runfiles_test"
- "-//src/test/shell/integration:test_test"
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
+ - "-//src/tools/singlejar:zip64_test"
ubuntu1804_java9:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -117,10 +114,9 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
ubuntu1804_java10:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -134,10 +130,9 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
macos:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -151,10 +146,9 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
windows:
build_flags:
- "--copt=-w"
@@ -173,8 +167,6 @@ platforms:
test_targets:
- "--"
- "//src:all_windows_tests"
- # Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/6479
- - "-//src/test/shell/bazel:workspace_resolved_test"
rbe_ubuntu1604:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
index 0b28c1e441eaf6..0e49acfbbbfac2 100644
--- a/.bazelci/presubmit.yml
+++ b/.bazelci/presubmit.yml
@@ -13,6 +13,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
# Disable Slow Tests
@@ -32,6 +33,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
# Disable Slow Tests
@@ -51,6 +53,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
# Disable Slow Tests
@@ -69,6 +72,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
# Disable Slow Tests
- "-//src/test/shell/bazel:bazel_determinism_test"
@@ -110,6 +114,7 @@ platforms:
- "-//src/test/shell/integration:output_filter_test"
- "-//src/test/shell/integration:stub_finds_runfiles_test"
- "-//src/test/shell/integration:test_test"
+ - "-//src/tools/singlejar:zip64_test"
ubuntu1804_java9:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -123,6 +128,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
# Disable Slow Tests
@@ -142,6 +148,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
# Disable Slow Tests
@@ -161,6 +168,7 @@ platforms:
- "--"
- "//scripts/..."
- "//src/test/..."
+ - "//src/tools/singlejar/..."
- "//third_party/ijar/..."
- "//tools/android/..."
# Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/4663
| null | train | train | 2018-11-06T11:54:39 | "2018-10-16T12:00:35Z" | laszlocsomor | test |
bazelbuild/bazel/6412_6446 | bazelbuild/bazel | bazelbuild/bazel/6412 | bazelbuild/bazel/6446 | [
"timestamp(timedelta=2.0, similarity=0.8870653956623342)"
] | 021684f61aba4a3f27231f5fbac642f635339e50 | 7a66d27c1eaac0ef8da8f46c71d0fa4c6d9fa689 | [
"I think such PR will be welcome - any objections @philwo ?",
"That would be great, yes. Thanks!"
] | [] | "2018-10-18T21:37:02Z" | [
"type: feature request",
"P2",
"area-EngProd",
"team-OSS"
] | Debian package should only suggest JDK instead of depending on it | Right now the published Debian / Ubuntu package declares a (hard) dependency to a Java SDK. But the bazel version included in the `deb` file is already a standalone one that comes with a bundled Java runtime.
Would you accept a PR which downgrades the `Depends` to a `Suggests`? The [Debian Policy](https://www.debian.org/doc/debian-policy/ch-relationships.html) describes `Suggests` as:
> This is used to declare that one package may be more useful with one or more others. Using this field tells the packaging system and the user that the listed packages are related to this one and can perhaps enhance its usefulness, but that installing this one without them is perfectly reasonable.
Thanks,
Gregor | [
"scripts/packages/debian/BUILD",
"scripts/packages/debian/control"
] | [
"scripts/packages/debian/BUILD",
"scripts/packages/debian/control"
] | [] | diff --git a/scripts/packages/debian/BUILD b/scripts/packages/debian/BUILD
index b809983fab3b15..a54e43cad39027 100644
--- a/scripts/packages/debian/BUILD
+++ b/scripts/packages/debian/BUILD
@@ -9,12 +9,12 @@ load("//tools/build_defs/pkg:pkg.bzl", "pkg_tar", "pkg_deb")
pkg_tar(
name = "bazel-bin",
srcs = [
- "//scripts/packages:without-jdk/bazel",
- "//scripts/packages:without-jdk/bazel-real",
+ "//scripts/packages:with-jdk/bazel",
+ "//scripts/packages:with-jdk/bazel-real",
],
mode = "0755",
package_dir = "/usr/bin",
- strip_prefix = "/scripts/packages/without-jdk",
+ strip_prefix = "/scripts/packages/with-jdk",
)
pkg_tar(
@@ -77,7 +77,6 @@ pkg_deb(
data = ":debian-data",
depends = [
# Keep in sync with Depends section in ./control
- "google-jdk | java8-sdk-headless | java8-jdk | java8-sdk | oracle-java8-installer",
"g++",
"zlib1g-dev",
"bash-completion",
@@ -88,6 +87,10 @@ pkg_deb(
homepage = "http://bazel.build",
maintainer = "The Bazel Authors <[email protected]>",
package = "bazel",
+ suggests = [
+ # Keep in sync with Suggests section in ./control
+ "google-jdk | java8-sdk-headless | java8-jdk | java8-sdk | oracle-java8-installer",
+ ],
version_file = ":version.txt",
visibility = ["//scripts/packages:__pkg__"],
)
diff --git a/scripts/packages/debian/control b/scripts/packages/debian/control
index 851decdfb1e493..19e2b03efaa67f 100644
--- a/scripts/packages/debian/control
+++ b/scripts/packages/debian/control
@@ -10,7 +10,8 @@ Section: contrib/devel
Priority: optional
Architecture: amd64
# Keep in sync with :bazel-debian in ./BUILD
-Depends: google-jdk | java8-sdk-headless | java8-jdk | java8-sdk | oracle-java8-installer, g++, zlib1g-dev, bash-completion, unzip, python
+Depends: g++, zlib1g-dev, bash-completion, unzip, python
+Suggests: google-jdk | java8-sdk-headless | java8-jdk | java8-sdk | oracle-java8-installer
Description: Bazel is a tool that automates software builds and tests.
Supported build tasks include running compilers and linkers to produce
executable programs and libraries, and assembling deployable packages
| null | test | train | 2018-10-24T21:50:51 | "2018-10-16T23:18:14Z" | gjasny | test |
bazelbuild/bazel/6449_6620 | bazelbuild/bazel | bazelbuild/bazel/6449 | bazelbuild/bazel/6620 | [
"timestamp(timedelta=0.0, similarity=0.8461699383865314)"
] | c67dceca77a93646961fc4bb863826e344fda5e0 | d007bc19054e23aaf35d119212cae8036b4042c9 | [
"Confirmed the behavior you're seeing.\r\n\r\nFrom what I can see from the review history, it looks like there was never any design intention to exclude config_setting from aliases. Pinging @lberki for confirmation or rebuttal.\r\n\r\nAs to your deeper goal, that's an interesting use of the feature. It seems like another variant of [OR chaining](https://docs.bazel.build/versions/master/configurable-attributes.html#or-chaining). Do you see this as bringing novel functionality even beyond that?",
"Thanks for the reply.\r\n\r\nOR chaining would work, but what I'm trying to achieve is to define the OR in only one place, and have other places use the result of it. I guess you could probably define a constant or macro and then reuse it, but that's awkward compared to the below, which allows consumers to consider it as any other `config_setting`.\r\n\r\nThe concrete example I added was this:\r\n```python\r\nalias(\r\n name = \"modules_enabled\",\r\n actual = select({\r\n \":java9\": \":java9\",\r\n \":java11\": \":java11\",\r\n # rhs just needs to be anything that won't match\r\n # :java11 will not match if we get to here\r\n \"//conditions:default\": \":java11\",\r\n }),\r\n)\r\n```\r\n\r\nWe have Java runtimes/toolchains controlled by a `--define` flag. Sometimes libraries need to add module-related `javacopts`; this allows them to do:\r\n```python\r\njava_library(\r\n name = \"lib\",\r\n javacopts = select({\r\n \"//tools/java:modules_enabled\": [\"--add-exports=...\"],\r\n \"//conditions:default\": [],\r\n }),\r\n)\r\n```\r\nThis is the cleanest solution I found for this issue. The `alias` itself is kinda hacky as I mentioned, but it's worth it so that all consumers have a single intuitive flag to switch on for this behavior.\r\n\r\nI could be missing a better answer, which I'd be happy to adopt.",
"Without engaging with the meat of the bug report, whether aliasing works is different for each rule you mentioned above:\r\n * `config_setting` should just work, I think it's a documentation bug\r\n * `package_group` may or may not work -- they are regrettably a little different from regular configured targets, so I wouldn't be surprised if there is a bug lurking somewhere that prevents them from working with `alias`, but I see no fundamental reason for them not to. I'd prefer them to be regular rules since they are special mostly for historical reason and then this wouldn't even be a question.\r\n* `test_suite` is special-cased in a few places, so I'd be even less surprised if `alias` did not work for them than for `package_group`. It should, though.",
"This approach doesn't look bad to me at all, and I think probably fits your use case as good as you're going to get.\r\n\r\nRe: the documentation: what wording would you find clearer given the the comment above? Happy to patch or take a patch from you.",
"Sorry, was that last question for me? I'm not sure I have enough context to answer -- I don't know what constitutes a 'regular' rule.\r\n\r\nFrom a little more experimentation, neither `package_group` nor `test_suite` may be aliased. However:\r\n- `package_group` is listed as a function, not a rule, so I'm not sure why there's the expectation that it would work in the first place.\r\n- `test_suite` doesn't error or anything, it just doesn't run the tests. That seems to be covered by the next part of the doc that says \"Tests are not run if their alias is mentioned on the command line.\"\r\n\r\nSo maybe the whole line is redundant and could be removed?",
"Yeah, removing the line sounds easiest. Will do..."
] | [
"Are you sure this works for `package_group` and `test_suite`? Is this functionality tested? `test_suite` rules are (unfortunately) special-cased in a number of ways e.g. in `bazel query` and other places expanding them (unfortunately, we have more than one) and I have no idea whether aliases are taken into account there.",
"For `package_group` and `test_suite` I'm following the thought process described at https://github.com/bazelbuild/bazel/issues/6449#issuecomment-433712899.",
"I think you are technically correct, but the fact that `package_group` is not a proper rule is a very obscure piece of information (except for us who have worked on Bazel since forever) and `test_suite` *is* a rule. Why not call this out explicitly?\r\n\r\n(btw, `package_group` totally should be a rule. Totally my fault that it's not.)",
"Call out what explicitly? Like, don't get into the details that `package_group` and `test_suite` are \"special\" but call them out.. how?\r\n\r\nI don't mind adding some simple tests to check that alias works in a standard build use, but I wouldn't be enthused to check all the corner cases with query and who knows where else. :p",
"Updated to just remove reference to `config_setting`, which is really the point of the bug. There's no evidence the comments on `package_group` and `test_suite` are confusing people, so let's just leave them be."
] | "2018-11-07T02:51:07Z" | [
"type: documentation (cleanup)",
"P3",
"team-Configurability"
] | Documentation/behavior mismatch with alias + config_setting | ### Description of the problem / feature request:
The [documentation](https://docs.bazel.build/versions/master/be/general.html#alias) claims that:
> Aliasing only works for "regular" targets. In particular, package_group, config_setting and test_suite rules cannot be aliased.
However, this does not seem to be accurate, at least for `config_setting`. You can create an `alias` with `actual` set to a `config_setting`, and then the `alias` may be used as a condition itself.
Is this a documentation bug or is this not supposed to work (or does it not work in some subtle way that I'll discover down the line)?
The context is that I would like to turn "raw" `config_setting`s into something more akin to feature flags, where several different possible values for a setting map to a single condition that makes more sense for consumers. Aliasing works for this case although it seems a bit hacky; if there's a better way to achieve the same thing I'd be interested to know.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Full reproducer [here](https://github.com/jfancher/bazel-issues/tree/alias_config_setting).
### What operating system are you running Bazel on?
macOS 10.13.2
### What's the output of `bazel info release`?
`release 0.18.0`
### Have you found anything relevant by searching the web?
No
| [
"src/main/java/com/google/devtools/build/lib/rules/Alias.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/Alias.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/Alias.java b/src/main/java/com/google/devtools/build/lib/rules/Alias.java
index ed8d164f02a61d..806a91199e954d 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/Alias.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/Alias.java
@@ -94,8 +94,8 @@ public Metadata getMetadata() {
</p>
<p>
- Aliasing only works for "regular" targets. In particular, <code>package_group</code>,
- <code>config_setting</code> and <code>test_suite</code> rules cannot be aliased.
+ Aliasing only works for "regular" targets. In particular, <code>package_group</code>
+ and <code>test_suite</code> cannot be aliased.
</p>
<p>
| null | train | train | 2019-01-17T20:26:01 | "2018-10-19T13:41:59Z" | jfancher | test |
bazelbuild/bazel/6462_7666 | bazelbuild/bazel | bazelbuild/bazel/6462 | bazelbuild/bazel/7666 | [
"timestamp(timedelta=0.0, similarity=0.8592612044934141)"
] | de0612ad3ef7cc8c44069261befdeb0d15b97c10 | a8e7a2073ca86039a730b7c0fa13111c886deeac | [
"This is a bad first-time experience. See https://github.com/bazelbuild/bazel/issues/5254",
"@laszlocsomor \r\n\r\nI get the same error: `Bazel on Windows requires MSYS2 Bash, but we could not find it` for every command using the binaries for Bazel provided by the `@bazel/bazel` v0.20.0 npm package.\r\n\r\nSo the only way to run Bazel on Windows is to install MSYS2 bash and disable the path conversion?\r\n\r\nThe doc says to prefer Command Prompt or PowerShell: https://docs.bazel.build/versions/master/windows.html#running-bazel-msys2-shell-vs-command-prompt-vs-powershell",
"@robisim74 : try Bazel 0.21, that should no longer complain about a missing MSYS2 Bash. Please let me know if you still find problems with it!",
"Ok, thanks! I will try to install v0.21 (still not published on npm) and let you know.",
"@laszlocsomor I tried to download version 0.21 directly on my machine in `c:\\bazel`, and run `C:\\> .\\bazel help`, but nothing: same error.\r\n\r\nFor the moment, I installed MSYS2 bash to work.",
"@robisim74 : You're right. I never merged the corresponding PR (https://github.com/bazelbuild/bazel/pull/6582) because it broke some tests.\r\n\r\nInstalling MSYS2 is the best \"workaround\" for now. Sorry about that.",
"Bazel 0.23 still complains about missing MSYS2:\r\n```\r\nC:\\src\\tmp>c:\\Users\\laszlocsomor\\Downloads\\bazel-0.23.0-windows-x86_64.exe info release\r\nERROR: bash.exe not found on PATH\r\nBazel on Windows requires MSYS2 Bash, but we could not find it.\r\nIf you do not have it installed, you can install MSYS2 from\r\n http://repo.msys2.org/distrib/msys2-x86_64-latest.exe\r\n\r\nIf you already have it installed but Bazel cannot find it,\r\nset BAZEL_SH environment variable to its location:\r\n set BAZEL_SH=c:\\path\\to\\msys2\\usr\\bin\\bash.exe\r\n[bazel ERROR src/main/cpp/blaze_util_windows.cc:1462] bash.exe not found on PATH\r\n[bazel INFO src/main/cpp/blaze_util_windows.cc:1477] BAZEL_SH detection took 0 msec, found\r\n```"
] | [] | "2019-03-07T14:15:25Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Windows: Bazel requires MSYS for every command | ### Description of the problem / feature request:
On a fresh Windows 10 installation with only Bazel 0.18.0 and MSVC redistributable DLLs [1] and _without_ MSYS, running any command in a minimal workspace (just an empty WORKSPACE file) requires MSYS bash.
[1] https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
On a fresh Windows 10:
1. download Bazel 0.18.0
2. install the [MSVC redistributable DLLs](https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe)
3. in cmd.exe:
```
C:\>md c:\src\foo
C:\>cd c:\src\foo
C:\src\foo>echo # hello>WORKSPACE
C:\src\foo>bazel info release
Bazel on Windows requires MSYS2 Bash, but we could not find it.
If you do not have it installed, you can install MSYS2 from
http://repo.msys2.org/distrib/msys2-x86_64-latest.exe
If you already have it installed but Bazel cannot find it,
set BAZEL_SH environment variable to its location:
set BAZEL_SH=c:\path\to\msys2\usr\bin\bash.exe
[bazel ERROR src/main/cpp/blaze_util_windows.cc:1453] bash.exe not found on PATH
[bazel INFO src/main/cpp/blaze_util_windows.cc:1473] BAZEL_SH detection took 0 msec, found
```
### What operating system are you running Bazel on?
Windows Server 2016 (v1607) | [
"src/main/cpp/blaze.cc",
"src/main/cpp/blaze_util_platform.h",
"src/main/cpp/blaze_util_windows.cc"
] | [
"src/main/cpp/blaze.cc",
"src/main/cpp/blaze_util_platform.h",
"src/main/cpp/blaze_util_windows.cc"
] | [] | diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index f31155ff0a6cdb..da1dc5ff175c5b 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -1546,7 +1546,7 @@ int Main(int argc, const char *argv[], WorkspaceLayout *workspace_layout,
// Must be done before command line parsing.
// ParseOptions already populate --client_env, so detect bash before it
// happens.
- DetectBashOrDie();
+ (void) DetectBashAndExportBazelSh();
#endif // if defined(_WIN32) || defined(__CYGWIN__)
globals->binary_path = CheckAndGetBinaryPath(argv[0]);
diff --git a/src/main/cpp/blaze_util_platform.h b/src/main/cpp/blaze_util_platform.h
index 832bfe0eca8065..3686aa72c238fb 100644
--- a/src/main/cpp/blaze_util_platform.h
+++ b/src/main/cpp/blaze_util_platform.h
@@ -264,7 +264,6 @@ bool UnlimitCoredumps();
#if defined(_WIN32) || defined(__CYGWIN__)
std::string DetectBashAndExportBazelSh();
-void DetectBashOrDie();
#endif // if defined(_WIN32) || defined(__CYGWIN__)
// This function has no effect on Unix platforms.
diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc
index b113c54dfefd45..a89a9afe5c59d0 100644
--- a/src/main/cpp/blaze_util_windows.cc
+++ b/src/main/cpp/blaze_util_windows.cc
@@ -1452,17 +1452,9 @@ static string GetBinaryFromPath(const string& binary_name) {
return string();
}
-static string LocateBash() {
+static string LocateBashMaybe() {
string msys_bash = GetMsysBash();
- if (!msys_bash.empty()) {
- return msys_bash;
- }
-
- string result = GetBinaryFromPath("bash.exe");
- if (result.empty()) {
- BAZEL_LOG(ERROR) << "bash.exe not found on PATH";
- }
- return result;
+ return msys_bash.empty() ? GetBinaryFromPath("bash.exe") : msys_bash;
}
string DetectBashAndExportBazelSh() {
@@ -1473,33 +1465,19 @@ string DetectBashAndExportBazelSh() {
uint64_t start = blaze::GetMillisecondsMonotonic();
- bash = LocateBash();
+ bash = LocateBashMaybe();
uint64_t end = blaze::GetMillisecondsMonotonic();
- BAZEL_LOG(INFO) << "BAZEL_SH detection took " << end - start
- << " msec, found " << bash.c_str();
-
- if (!bash.empty()) {
+ if (bash.empty()) {
+ BAZEL_LOG(INFO) << "BAZEL_SH detection took " << end - start
+ << " msec, not found";
+ } else {
+ BAZEL_LOG(INFO) << "BAZEL_SH detection took " << end - start
+ << " msec, found " << bash.c_str();
// Set process environment variable.
blaze::SetEnv("BAZEL_SH", bash);
}
- return bash;
-}
-void DetectBashOrDie() {
- string bash = DetectBashAndExportBazelSh();
- if (bash.empty()) {
- // TODO(bazel-team) should this be printed to stderr? If so, it should use
- // BAZEL_LOG(ERROR)
- printf(
- "Bazel on Windows requires MSYS2 Bash, but we could not find it.\n"
- "If you do not have it installed, you can install MSYS2 from\n"
- " http://repo.msys2.org/distrib/msys2-x86_64-latest.exe\n"
- "\n"
- "If you already have it installed but Bazel cannot find it,\n"
- "set BAZEL_SH environment variable to its location:\n"
- " set BAZEL_SH=c:\\path\\to\\msys2\\usr\\bin\\bash.exe\n");
- exit(1);
- }
+ return bash;
}
void EnsurePythonPathOption(std::vector<string>* options) {
| null | test | train | 2019-03-07T15:08:49 | "2018-10-22T13:23:23Z" | laszlocsomor | test |
bazelbuild/bazel/6463_6466 | bazelbuild/bazel | bazelbuild/bazel/6463 | bazelbuild/bazel/6466 | [
"timestamp(timedelta=0.0, similarity=0.843525691914465)"
] | 2087584e6085c72bbbd63f108b09773b75306314 | 623f8a41190d703b39bba4a52b1c3c0640fffddb | [
"This is a bad first-time experience. See https://github.com/bazelbuild/bazel/issues/5254"
] | [] | "2018-10-22T14:28:43Z" | [
"type: bug",
"P3",
"area-Windows",
"team-OSS"
] | Windows: Bazel ostensibly requires Python for every command | ### Description of the problem / feature request:
Bazel complains if it cannot find Python on that PATH, for every command. However, it also carries out the commands successfully.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
On a fresh Windows 10:
1. download Bazel 0.18.0
2. install the [MSVC redistributable DLLs](https://download.microsoft.com/download/9/3/F/93FCF1E7-E6A4-478B-96E7-D4B285925B00/vc_redist.x64.exe)
3. in cmd.exe:
```
C:\>md c:\src\foo
C:\>cd c:\src\foo
C:\src\foo>echo # hello>WORKSPACE
C:\src\foo>md c:\src\foo\fake-msys\usr\bin
C:\src\tmp>echo @exit /B 1 > c:\src\tmp\fake-msys\usr\bin\bash.bat
C:\src\tmp>set BAZEL_SH=c:\src\tmp\fake-msys\usr\bin\bash.bat
C:\src\tmp>bazel info release
ERROR: python.exe not found on PATH
release 0.18.0
```
### What operating system are you running Bazel on?
Windows Server 2016 (v1607) | [
"src/main/cpp/blaze_util_windows.cc"
] | [
"src/main/cpp/blaze_util_windows.cc"
] | [
"src/test/py/bazel/BUILD",
"src/test/py/bazel/first_time_use_test.py"
] | diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc
index 3f3f8bfbb935e1..8d57784d3f8ff0 100644
--- a/src/main/cpp/blaze_util_windows.cc
+++ b/src/main/cpp/blaze_util_windows.cc
@@ -1437,7 +1437,6 @@ static string GetBinaryFromPath(const string& binary_name) {
start = end + 1;
} while (true);
- BAZEL_LOG(ERROR) << binary_name.c_str() << " not found on PATH";
return string();
}
@@ -1447,7 +1446,11 @@ static string LocateBash() {
return msys_bash;
}
- return GetBinaryFromPath("bash.exe");
+ string result = GetBinaryFromPath("bash.exe");
+ if (result.empty()) {
+ BAZEL_LOG(ERROR) << "bash.exe not found on PATH";
+ }
+ return result;
}
void DetectBashOrDie() {
| diff --git a/src/test/py/bazel/BUILD b/src/test/py/bazel/BUILD
index 1116e039c247ff..d5f59d680c4530 100644
--- a/src/test/py/bazel/BUILD
+++ b/src/test/py/bazel/BUILD
@@ -166,6 +166,12 @@ py_test(
}),
)
+py_test(
+ name = "first_time_use_test",
+ srcs = ["first_time_use_test.py"],
+ deps = [":test_base"],
+)
+
py_test(
name = "query_test",
size = "medium",
diff --git a/src/test/py/bazel/first_time_use_test.py b/src/test/py/bazel/first_time_use_test.py
new file mode 100644
index 00000000000000..5fc2033ad8e6e8
--- /dev/null
+++ b/src/test/py/bazel/first_time_use_test.py
@@ -0,0 +1,37 @@
+# Copyright 2018 The Bazel Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import unittest
+
+from src.test.py.bazel import test_base
+
+
+class FirstTimeUseTest(test_base.TestBase):
+
+ def _FailWithOutput(self, output):
+ self.fail('FAIL:\n | %s\n---' % '\n | '.join(output))
+
+ def testNoPythonRequirement(self):
+ """Regression test for https://github.com/bazelbuild/bazel/issues/6463"""
+ self.ScratchFile('WORKSPACE')
+ exit_code, stdout, stderr = self.RunBazel(['info', 'release'])
+ self.AssertExitCode(exit_code, 0, stderr)
+ for line in stdout + stderr:
+ if 'python' in line and 'not found on PATH' in line:
+ self._FailWithOutput(stdout + stderr)
+
+
+if __name__ == '__main__':
+ unittest.main()
| train | train | 2018-10-22T14:28:20 | "2018-10-22T13:29:09Z" | laszlocsomor | test |
bazelbuild/bazel/6469_6910 | bazelbuild/bazel | bazelbuild/bazel/6469 | bazelbuild/bazel/6910 | [
"timestamp(timedelta=25713.0, similarity=0.851142177143935)"
] | c10468878027305d9b1ccc1a9dfbde956b788dc6 | 5a062b974a1421bad2e4c4424fc1a232c9c0f7f9 | [
"cc @katre, since this is new in `0.19` (#6116), but probably not a release blocker.",
"This is a small enough use-case that I don't want to risk a breakage due to cherrypick. We should try and address it for 0.20, however.",
"I'm getting the same error message for **non-symlinks** on Windows with Bazel 0.19.0:\r\n```\r\nD:\\src\\codebase>bazel build //...\r\nWARNING: The following rc files are no longer being read, please transfer their contents or import their path into one of the standard rc files:\r\nd:\\src\\codebase/.bazelrc\r\n```",
"Same as @baskus. Can somebody please confirm this is not the intended behaviour?",
"Assigning to @dslomov to decide if this is a blocker for 0.20",
"/sub, this is causing confusing issues on the Mac too. The system_rc is `/etc/bazel.bazelrc` on the Mac, but `/etc` is a symlink to `/private/etc`. This results in confusing warning messages like:\r\n\r\n```\r\n$ cat /etc/bazel.bazelrc\r\nbuild --jobs=4\r\n$ bazel version\r\nWARNING: The following rc files are no longer being read, please transfer\r\ntheir contents or import their path into one of the standard rc files:\r\n/etc/bazel.bazelrc\r\n```",
"Thanks @excitoon for linking to #6138! That might indeed be the same issue.\r\n\r\n~Someone with a Mac at hand, could you please Bazel built at https://github.com/bazelbuild/bazel/commit/e9a908560133770614eca89ef64681bdf3f04b3e and see if that commit fixes this issue?~ Oh wait, never mind, it happens on Linux too I see.",
"Confirming that https://github.com/bazelbuild/bazel/commit/e9a908560133770614eca89ef64681bdf3f04b3e fixes this issue too, so I'll say this is a duplicate of https://github.com/bazelbuild/bazel/issues/6138."
] | [
"nit: not that this is very important, but can you maybe get away with `$TEST_TMPDIR` instead? It's kinda confusing because `$HOME` usually means, well, the home directory of some user.",
"nit: DedupeBazelRcPaths? (it's not a getter)\r\n\r\nAlso, why \"Existing\"? It doesn't check existence, does it?",
"On Linux we do the same: https://github.com/bazelbuild/bazel/blob/420b9533534951b82c1e13e6d83fa67390e95778/src/main/cpp/blaze_util_posix.cc#L205\r\n\r\nBazel actually sets a mock $HOME for the test.",
"The canonical path can only be computed of existing paths, so the paths indeed exist.\r\n\r\nRenamed the method to its old name."
] | "2018-12-13T10:03:16Z" | [
"untriaged",
"team-Bazel"
] | Bazel shows bogus WARNING for the rc files, if they are symlinks. | ### Description of the problem / feature request:
Bazel shows bogus `WARNING` for the rc files, if they are symlinks:
```
WARNING: The following rc files are no longer being read, please transfer their contents or import their path into one of the standard rc files:
/tmp/workspace/.bazelrc
```
But the rc file is correctly processed, as seen in the reproduction below.
Note that this is new in `0.19rc6` and there is no warning in `0.18`.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
mkdir -p /tmp/workspace/tools
cd /tmp/workspace
touch WORKSPACE
touch BUILD
echo "build:test --copt=-DTEST" > tools/bazel.rc
ln -s tools/bazel.rc .bazelrc
bazel build --config=test :all
```
```
WARNING: The following rc files are no longer being read, please transfer their contents or import their path into one of the standard rc files:
/tmp/workspace/.bazelrc
Starting local Bazel server and connecting to it...
INFO: Analysed 0 targets (3 packages loaded, 0 targets configured).
INFO: Found 0 targets...
INFO: Elapsed time: 1.298s, Critical Path: 0.02s, Remote (0.00% of the time): [queue: 0.00%, setup: 0.00%, process: 0.00%]
INFO: 0 processes.
INFO: Build completed successfully, 1 total action
```
### What operating system are you running Bazel on?
Linux.
### What's the output of `bazel info release`?
```
release 0.19.0rc6
```
### Any other information, logs, or outputs that you want to share?
Backstory (mostly irrelevant to the actual issue):
The `.bazelrc` symlink to `tools/bazel.rc` was added to ease the migration instead of `import %workspace%/tools/bazel.rc` suggested in #6319, since we have projects (e.g. https://github.com/envoyproxy/envoy-filter-example) importing the main project (https://github.com/envoyproxy/envoy) as a submodule and linking to its [`tools/bazel.rc`](https://github.com/envoyproxy/envoy/blob/master/tools/bazel.rc), so `import` breaks, because workspace-relative location changes. | [
"src/main/cpp/blaze_util.cc",
"src/main/cpp/blaze_util.h",
"src/main/cpp/blaze_util_windows.cc",
"src/main/cpp/option_processor-internal.h",
"src/main/cpp/option_processor.cc",
"src/main/cpp/rc_file.cc",
"src/main/cpp/rc_file.h",
"src/main/cpp/startup_options.cc"
] | [
"src/main/cpp/blaze_util.cc",
"src/main/cpp/blaze_util.h",
"src/main/cpp/blaze_util_windows.cc",
"src/main/cpp/option_processor-internal.h",
"src/main/cpp/option_processor.cc",
"src/main/cpp/rc_file.cc",
"src/main/cpp/rc_file.h",
"src/main/cpp/startup_options.cc"
] | [
"src/test/cpp/rc_file_test.cc"
] | diff --git a/src/main/cpp/blaze_util.cc b/src/main/cpp/blaze_util.cc
index d8ec359515f779..858ac4e73ad1e5 100644
--- a/src/main/cpp/blaze_util.cc
+++ b/src/main/cpp/blaze_util.cc
@@ -181,6 +181,10 @@ void SetDebugLog(bool enabled) {
}
}
+bool IsRunningWithinTest() {
+ return !GetEnv("TEST_TMPDIR").empty();
+}
+
void WithEnvVars::SetEnvVars(const map<string, EnvVarValue>& vars) {
for (const auto& var : vars) {
switch (var.second.action) {
diff --git a/src/main/cpp/blaze_util.h b/src/main/cpp/blaze_util.h
index b9f5a518e6b4c9..b0b55385e78542 100644
--- a/src/main/cpp/blaze_util.h
+++ b/src/main/cpp/blaze_util.h
@@ -104,6 +104,10 @@ std::string ToString(const T &value) {
// Revisit once client logging is fixed (b/32939567).
void SetDebugLog(bool enabled);
+// Returns true if this Bazel instance is running inside of a Bazel test.
+// This method observes the TEST_TMPDIR envvar.
+bool IsRunningWithinTest();
+
// What WithEnvVar should do with an environment variable
enum EnvVarAction { UNSET, SET };
diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc
index 3319faf37e3420..1483dfb9b76a22 100644
--- a/src/main/cpp/blaze_util_windows.cc
+++ b/src/main/cpp/blaze_util_windows.cc
@@ -406,6 +406,12 @@ string GetOutputRoot() {
}
string GetHomeDir() {
+ if (IsRunningWithinTest()) {
+ // Bazel is running inside of a test. Respect $HOME that the test setup has
+ // set instead of using the actual home directory of the current user.
+ return GetEnv("HOME");
+ }
+
PWSTR wpath;
// Look up the user's home directory. The default value of "FOLDERID_Profile"
// is the same as %USERPROFILE%, but it does not require the envvar to be set.
diff --git a/src/main/cpp/option_processor-internal.h b/src/main/cpp/option_processor-internal.h
index b25db9c92996c6..72fab91392edb5 100644
--- a/src/main/cpp/option_processor-internal.h
+++ b/src/main/cpp/option_processor-internal.h
@@ -26,8 +26,10 @@ namespace blaze {
namespace internal {
// Returns the deduped set of bazelrc paths (with respect to its canonical form)
-// preserving the original order. The paths that cannot be resolved are
-// omitted.
+// preserving the original order.
+// All paths in the result have been verified to exist (otherwise their
+// canonical form couldn't have been computed).The paths that cannot be resolved
+// are omitted.
std::vector<std::string> DedupeBlazercPaths(
const std::vector<std::string>& paths);
diff --git a/src/main/cpp/option_processor.cc b/src/main/cpp/option_processor.cc
index 1298ea1f359abe..b1621956bfe6ac 100644
--- a/src/main/cpp/option_processor.cc
+++ b/src/main/cpp/option_processor.cc
@@ -185,18 +185,22 @@ std::set<std::string> GetOldRcPaths(
internal::FindRcAlongsideBinary(cwd, path_to_binary);
candidate_bazelrc_paths = {workspace_rc, binary_rc, system_bazelrc_path};
}
- const std::vector<std::string> deduped_blazerc_paths =
- internal::DedupeBlazercPaths(candidate_bazelrc_paths);
- std::set<std::string> old_rc_paths(deduped_blazerc_paths.begin(),
- deduped_blazerc_paths.end());
string user_bazelrc_path = internal::FindLegacyUserBazelrc(
SearchUnaryOption(startup_args, "--bazelrc"), workspace);
if (!user_bazelrc_path.empty()) {
- old_rc_paths.insert(user_bazelrc_path);
+ candidate_bazelrc_paths.push_back(user_bazelrc_path);
}
- return old_rc_paths;
+ // DedupeBlazercPaths returns paths whose canonical path could be computed,
+ // therefore these paths must exist.
+ const std::vector<std::string> deduped_existing_blazerc_paths =
+ internal::DedupeBlazercPaths(candidate_bazelrc_paths);
+ return std::set<std::string>(deduped_existing_blazerc_paths.begin(),
+ deduped_existing_blazerc_paths.end());
}
+// Deduplicates the given paths based on their canonical form.
+// Computes the canonical form using blaze_util::MakeCanonical.
+// Returns the unique paths in their original form (not the canonical one).
std::vector<std::string> DedupeBlazercPaths(
const std::vector<std::string>& paths) {
std::set<std::string> canonical_paths;
@@ -291,6 +295,20 @@ void WarnAboutDuplicateRcFiles(const std::set<std::string>& read_files,
}
}
+std::vector<std::string> GetLostFiles(
+ const std::set<std::string>& old_files,
+ const std::set<std::string>& read_files_canon) {
+ std::vector<std::string> result;
+ for (const auto& old : old_files) {
+ std::string old_canon = blaze_util::MakeCanonical(old.c_str());
+ if (!old_canon.empty() &&
+ read_files_canon.find(old_canon) == read_files_canon.end()) {
+ result.push_back(old);
+ }
+ }
+ return result;
+}
+
} // namespace internal
// TODO(#4502) Consider simplifying result_rc_files to a vector of RcFiles, no
@@ -366,7 +384,7 @@ blaze_exit_code::ExitCode OptionProcessor::GetRcFiles(
// that don't point to real files.
rc_files = internal::DedupeBlazercPaths(rc_files);
- std::set<std::string> read_files;
+ std::set<std::string> read_files_canonical_paths;
// Parse these potential files, in priority order;
for (const std::string& top_level_bazelrc_path : rc_files) {
std::unique_ptr<RcFile> parsed_rc;
@@ -377,9 +395,9 @@ blaze_exit_code::ExitCode OptionProcessor::GetRcFiles(
}
// Check that none of the rc files loaded this time are duplicate.
- const std::deque<std::string>& sources = parsed_rc->sources();
- internal::WarnAboutDuplicateRcFiles(read_files, sources);
- read_files.insert(sources.begin(), sources.end());
+ const std::deque<std::string>& sources = parsed_rc->canonical_source_paths();
+ internal::WarnAboutDuplicateRcFiles(read_files_canonical_paths, sources);
+ read_files_canonical_paths.insert(sources.begin(), sources.end());
result_rc_files->push_back(std::move(parsed_rc));
}
@@ -394,16 +412,8 @@ blaze_exit_code::ExitCode OptionProcessor::GetRcFiles(
workspace_layout, workspace, cwd, cmd_line->path_to_binary,
cmd_line->startup_args, internal::FindSystemWideRc(system_bazelrc_path_));
- // std::vector<std::string> old_files = internal::GetOldRcPathsInOrder(
- // workspace_layout, workspace, cwd, cmd_line->path_to_binary,
- // cmd_line->startup_args);
- //
- // std::sort(old_files.begin(), old_files.end());
- std::vector<std::string> lost_files(old_files.size());
- std::vector<std::string>::iterator end_iter = std::set_difference(
- old_files.begin(), old_files.end(), read_files.begin(), read_files.end(),
- lost_files.begin());
- lost_files.resize(end_iter - lost_files.begin());
+ std::vector<std::string> lost_files =
+ internal::GetLostFiles(old_files, read_files_canonical_paths);
if (!lost_files.empty()) {
std::string joined_lost_rcs;
blaze_util::JoinStrings(lost_files, '\n', &joined_lost_rcs);
@@ -625,7 +635,7 @@ std::vector<std::string> OptionProcessor::GetBlazercAndEnvCommandArgs(
int cur_index = 1;
std::map<std::string, int> rcfile_indexes;
for (const auto& blazerc : blazercs) {
- for (const std::string& source_path : blazerc->sources()) {
+ for (const std::string& source_path : blazerc->canonical_source_paths()) {
// Deduplicate the rc_source list because the same file might be included
// from multiple places.
if (rcfile_indexes.find(source_path) != rcfile_indexes.end()) continue;
diff --git a/src/main/cpp/rc_file.cc b/src/main/cpp/rc_file.cc
index e356ca690d161d..1a0f8429952d93 100644
--- a/src/main/cpp/rc_file.cc
+++ b/src/main/cpp/rc_file.cc
@@ -63,10 +63,10 @@ RcFile::ParseError RcFile::ParseFile(const string& filename,
const std::string canonical_filename =
blaze_util::MakeCanonical(filename.c_str());
- rcfile_paths_.push_back(canonical_filename);
- // Keep a pointer to the canonical_filename string in rcfile_paths_ for the
- // RcOptions.
- string* filename_ptr = &rcfile_paths_.back();
+ canonical_rcfile_paths_.push_back(canonical_filename);
+ // Keep a pointer to the canonical_filename string in canonical_rcfile_paths_
+ // for the RcOptions.
+ string* filename_ptr = &canonical_rcfile_paths_.back();
// A '\' at the end of a line continues the line.
blaze_util::Replace("\\\r\n", "", &contents);
diff --git a/src/main/cpp/rc_file.h b/src/main/cpp/rc_file.h
index 0d462dcc4bca7a..5f1eee7ceaf9a4 100644
--- a/src/main/cpp/rc_file.h
+++ b/src/main/cpp/rc_file.h
@@ -42,7 +42,9 @@ class RcFile {
std::string workspace, ParseError* error, std::string* error_text);
// Returns all relevant rc sources for this file (including itself).
- const std::deque<std::string>& sources() const { return rcfile_paths_; }
+ const std::deque<std::string>& canonical_source_paths() const {
+ return canonical_rcfile_paths_;
+ }
// Command -> all options for that command (in order of appearance).
using OptionMap = std::unordered_map<std::string, std::vector<RcOption>>;
@@ -68,9 +70,12 @@ class RcFile {
const std::string workspace_;
// Full closure of rcfile paths imported from this file (including itself).
+ // These are all canonical paths, created with blaze_util::MakeCanonical.
+ // This also means all of these paths should exist.
+ //
// The RcOption structs point to the strings in here so they need to be stored
// in a container that offers stable pointers, like a deque (and not vector).
- std::deque<std::string> rcfile_paths_;
+ std::deque<std::string> canonical_rcfile_paths_;
// All options parsed from the file.
OptionMap options_;
};
diff --git a/src/main/cpp/startup_options.cc b/src/main/cpp/startup_options.cc
index 12673846210f14..c343db94d12c94 100644
--- a/src/main/cpp/startup_options.cc
+++ b/src/main/cpp/startup_options.cc
@@ -98,8 +98,7 @@ StartupOptions::StartupOptions(const string &product_name,
idle_server_tasks(true),
original_startup_options_(std::vector<RcStartupFlag>()),
unlimit_coredumps(false) {
- bool testing = !blaze::GetEnv("TEST_TMPDIR").empty();
- if (testing) {
+ if (blaze::IsRunningWithinTest()) {
output_root = blaze_util::MakeAbsolute(blaze::GetEnv("TEST_TMPDIR"));
max_idle_secs = 15;
BAZEL_LOG(USER) << "$TEST_TMPDIR defined: output root default is '"
| diff --git a/src/test/cpp/rc_file_test.cc b/src/test/cpp/rc_file_test.cc
index 01a4d5aecd37f4..a358ba712f2c0b 100644
--- a/src/test/cpp/rc_file_test.cc
+++ b/src/test/cpp/rc_file_test.cc
@@ -173,8 +173,8 @@ TEST_F(GetRcFileTest, GetRcFilesLoadsAllDefaultBazelrcs) {
ASSERT_EQ(2, parsed_rcs.size());
const std::deque<std::string> expected_system_rc_que = {system_rc};
const std::deque<std::string> expected_workspace_rc_que = {workspace_rc};
- EXPECT_EQ(expected_system_rc_que, parsed_rcs[0].get()->sources());
- EXPECT_EQ(expected_workspace_rc_que, parsed_rcs[1].get()->sources());
+ EXPECT_EQ(expected_system_rc_que, parsed_rcs[0].get()->canonical_source_paths());
+ EXPECT_EQ(expected_workspace_rc_que, parsed_rcs[1].get()->canonical_source_paths());
}
TEST_F(GetRcFileTest, GetRcFilesRespectsNoSystemRc) {
@@ -195,7 +195,7 @@ TEST_F(GetRcFileTest, GetRcFilesRespectsNoSystemRc) {
ASSERT_EQ(1, parsed_rcs.size());
const std::deque<std::string> expected_workspace_rc_que = {workspace_rc};
- EXPECT_EQ(expected_workspace_rc_que, parsed_rcs[0].get()->sources());
+ EXPECT_EQ(expected_workspace_rc_que, parsed_rcs[0].get()->canonical_source_paths());
}
TEST_F(GetRcFileTest, GetRcFilesRespectsNoWorkspaceRc) {
@@ -216,7 +216,7 @@ TEST_F(GetRcFileTest, GetRcFilesRespectsNoWorkspaceRc) {
ASSERT_EQ(1, parsed_rcs.size());
const std::deque<std::string> expected_system_rc_que = {system_rc};
- EXPECT_EQ(expected_system_rc_que, parsed_rcs[0].get()->sources());
+ EXPECT_EQ(expected_system_rc_que, parsed_rcs[0].get()->canonical_source_paths());
}
TEST_F(GetRcFileTest, GetRcFilesRespectsNoWorkspaceRcAndNoSystemCombined) {
@@ -317,8 +317,8 @@ TEST_F(GetRcFileTest, GetRcFilesReadsCommandLineRc) {
// Because of the variety of path representations in windows, this
// equality test does not attempt to check the entire path.
ASSERT_EQ(1, parsed_rcs.size());
- ASSERT_EQ(1, parsed_rcs[0].get()->sources().size());
- EXPECT_THAT(parsed_rcs[0].get()->sources().front(), HasSubstr("mybazelrc"));
+ ASSERT_EQ(1, parsed_rcs[0].get()->canonical_source_paths().size());
+ EXPECT_THAT(parsed_rcs[0].get()->canonical_source_paths().front(), HasSubstr("mybazelrc"));
}
TEST_F(GetRcFileTest, GetRcFilesAcceptsNullCommandLineRc) {
@@ -338,7 +338,7 @@ TEST_F(GetRcFileTest, GetRcFilesAcceptsNullCommandLineRc) {
// but it does technically count as a file
ASSERT_EQ(1, parsed_rcs.size());
const std::deque<std::string> expected_rc_que = {kNullDevice};
- EXPECT_EQ(expected_rc_que, parsed_rcs[0].get()->sources());
+ EXPECT_EQ(expected_rc_que, parsed_rcs[0].get()->canonical_source_paths());
}
class ParseOptionsTest : public RcFileTest {
| test | train | 2018-12-13T01:31:06 | "2018-10-23T00:13:25Z" | PiotrSikora | test |
bazelbuild/bazel/6474_6497 | bazelbuild/bazel | bazelbuild/bazel/6474 | bazelbuild/bazel/6497 | [
"timestamp(timedelta=1.0, similarity=0.9130243255272305)"
] | 6c17197df37533b179cbe2e239e2e10b9f01b746 | 3f2efb99cb6af46c127f2340813b188c3f80f120 | [
"This is a bad first-time user experience: MSYS is required just to run `bazel info`. (And also to build C++ without any genrule dependencies.) See https://github.com/bazelbuild/bazel/issues/5254",
"The reason I care about this scenario, even though the repro requires commenting out code, is because I'd like to fix https://github.com/bazelbuild/bazel/issues/6462 by not erroring out if Bash is missing.",
"Understand, I will fix this."
] | [
"2018?",
"don't you have to enable extensions to use `::` for comments?",
"stale comment?",
"`exit /b 1` ?",
"Flipping the branches to get `if [condition] then [action] else [alternative]` is easier to read than `if not [condition] then [alternative] else [action]`.",
"Done",
"No, `::` is just like `#` in python",
"Thanks!",
"Sounds good",
"Indeed!"
] | "2018-10-24T11:55:47Z" | [
"type: bug",
"area-Windows",
"team-OSS"
] | Windows, C++: windows_cc_configure.bzl requires BAZEL_SH | ### Description of the problem / feature request:
`windows_cc_configure.bzl` breaks if `BAZEL_SH` is unset.
Setting `BAZEL_SH` to point to a fake Bash (`c:\src\fake-msys\usr\bin\bash.exe` -- a binary I wrote that just dumps its arguments and exits with 1) works around the problem.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
1. Check out Bazel's sources at https://github.com/bazelbuild/bazel/commit/2fda17d46088f2bb07b049fa35759002ea1dd5db
2. Comment out the line https://github.com/bazelbuild/bazel/blob/2fda17d46088f2bb07b049fa35759002ea1dd5db/src/main/cpp/blaze.cc#L1543
3. Build Bazel
4. Unset `BAZEL_SH` (with `set BAZEL_SH=`)
5. Run `bazel info` with the Bazel you built.
```
C:\src\tmp>c:\src\bazel\bazel-bin\src\bazel.exe info
WARNING: The following rc files are no longer being read, please transfer their contents or import their path into one of the standard rc files:
C:\Users\laszlocsomor/.bazelrc
Extracting Bazel installation...
Starting local Bazel server and connecting to it...
INFO: Invocation ID: baac9c71-b583-4c1a-9429-3ee26164b0f4
ERROR: in target '//external:cc_toolchain': no such package '@local_config_cc//': Traceback (most recent call last):
File "C:/_bazel/zovul4l7/external/bazel_tools/tools/cpp/cc_configure.bzl", line 51
configure_windows_toolchain(repository_ctx)
File "C:/_bazel/zovul4l7/external/bazel_tools/tools/cpp/windows_cc_configure.bzl", line 344, in configure_windows_toolchain
repository_ctx.template("CROSSTOOL", paths["@bazel_tools//..."], ...}": ""})
File "C:/_bazel/zovul4l7/external/bazel_tools/tools/cpp/windows_cc_configure.bzl", line 361, in repository_ctx.template
_get_escaped_windows_msys_crosstool_content(repository_ctx)
File "C:/_bazel/zovul4l7/external/bazel_tools/tools/cpp/windows_cc_configure.bzl", line 35, in _get_escaped_windows_msys_crosstool_content
get_env_var(repository_ctx, "BAZEL_SH")
File "C:/_bazel/zovul4l7/external/bazel_tools/tools/cpp/lib_cc_configure.bzl", line 125, in get_env_var
auto_configure_fail(("'%s' environment variable is n...))
File "C:/_bazel/zovul4l7/external/bazel_tools/tools/cpp/lib_cc_configure.bzl", line 109, in auto_configure_fail
fail(("\n%sAuto-Configuration Error:%...)))
Auto-Configuration Error: 'BAZEL_SH' environment variable is not set
```
### What operating system are you running Bazel on?
Windows 10
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
See repro instructions above. | [
"tools/cpp/vc_installation_error.bat.tpl",
"tools/cpp/windows_cc_configure.bzl"
] | [
"tools/cpp/msys_gcc_installation_error.bat",
"tools/cpp/vc_installation_error.bat.tpl",
"tools/cpp/windows_cc_configure.bzl"
] | [] | diff --git a/tools/cpp/msys_gcc_installation_error.bat b/tools/cpp/msys_gcc_installation_error.bat
new file mode 100644
index 00000000000000..25c35534f97533
--- /dev/null
+++ b/tools/cpp/msys_gcc_installation_error.bat
@@ -0,0 +1,23 @@
+:: Copyright 2018 The Bazel Authors. All rights reserved.
+::
+:: Licensed under the Apache License, Version 2.0 (the "License");
+:: you may not use this file except in compliance with the License.
+:: You may obtain a copy of the License at
+::
+:: http://www.apache.org/licenses/LICENSE-2.0
+::
+:: Unless required by applicable law or agreed to in writing, software
+:: distributed under the License is distributed on an "AS IS" BASIS,
+:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+:: See the License for the specific language governing permissions and
+:: limitations under the License.
+
+@echo OFF
+
+echo. 1>&2
+echo The target you are compiling requires MSYS gcc / MINGW gcc. 1>&2
+echo Bazel couldn't find gcc installation on your machine. 1>&2
+echo Please install MSYS gcc / MINGW gcc and set BAZEL_SH environment variable 1>&2
+echo. 1>&2
+
+exit /b 1
diff --git a/tools/cpp/vc_installation_error.bat.tpl b/tools/cpp/vc_installation_error.bat.tpl
index cb44b1413f77d7..b7965856cc9221 100644
--- a/tools/cpp/vc_installation_error.bat.tpl
+++ b/tools/cpp/vc_installation_error.bat.tpl
@@ -12,7 +12,6 @@
:: See the License for the specific language governing permissions and
:: limitations under the License.
-:: Invoke the python script under pydir with the same basename
@echo OFF
echo. 1>&2
@@ -22,4 +21,4 @@ echo Bazel couldn't find a valid Visual C++ build tools installation on your mac
echo Please check your installation following https://docs.bazel.build/versions/master/windows.html#using 1>&2
echo. 1>&2
-exit -1
+exit /b 1
diff --git a/tools/cpp/windows_cc_configure.bzl b/tools/cpp/windows_cc_configure.bzl
index 77d901fe533ab9..1beca5727eaf97 100644
--- a/tools/cpp/windows_cc_configure.bzl
+++ b/tools/cpp/windows_cc_configure.bzl
@@ -31,20 +31,24 @@ def _auto_configure_warning_maybe(repository_ctx, msg):
auto_configure_warning(msg)
def _get_escaped_windows_msys_crosstool_content(repository_ctx, use_mingw = False):
- """Return the content of msys crosstool which is still the default CROSSTOOL on Windows."""
- bazel_sh = get_env_var(repository_ctx, "BAZEL_SH").replace("\\", "/").lower()
+ """Return the content of msys crosstool."""
+ bazel_sh = get_env_var(repository_ctx, "BAZEL_SH", "", False).replace("\\", "/").lower()
tokens = bazel_sh.rsplit("/", 1)
- prefix = "mingw64" if use_mingw else "usr"
- msys_root = None
+ msys_root = ""
if tokens[0].endswith("/usr/bin"):
msys_root = tokens[0][:len(tokens[0]) - len("usr/bin")]
elif tokens[0].endswith("/bin"):
msys_root = tokens[0][:len(tokens[0]) - len("bin")]
- if not msys_root:
- auto_configure_fail(
- "Could not determine MSYS/Cygwin root from BAZEL_SH (%s)" % bazel_sh,
- )
- escaped_msys_root = escape_string(msys_root)
+ prefix = "mingw64" if use_mingw else "usr"
+ tool_path_prefix = escape_string(msys_root) + prefix
+ tool_path = {}
+
+ for tool in ["ar", "compat-ld", "cpp", "dwp", "gcc", "gcov", "ld", "nm", "objcopy", "objdump", "strip"]:
+ if msys_root:
+ tool_path[tool] = tool_path_prefix + "/bin/" + tool
+ else:
+ tool_path[tool] = "msys_gcc_installation_error.bat"
+
return (((
' abi_version: "local"\n' +
' abi_libc_version: "local"\n' +
@@ -56,23 +60,23 @@ def _get_escaped_windows_msys_crosstool_content(repository_ctx, use_mingw = Fals
' target_cpu: "x64_windows"\n' +
' target_system_name: "local"\n'
) if not use_mingw else "") +
- ' tool_path { name: "ar" path: "%s%s/bin/ar" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "compat-ld" path: "%s%s/bin/ld" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "cpp" path: "%s%s/bin/cpp" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "dwp" path: "%s%s/bin/dwp" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "gcc" path: "%s%s/bin/gcc" }\n' % (escaped_msys_root, prefix) +
+ ' tool_path { name: "ar" path: "%s" }\n' % tool_path["ar"] +
+ ' tool_path { name: "compat-ld" path: "%s" }\n' % tool_path["ld"] +
+ ' tool_path { name: "cpp" path: "%s" }\n' % tool_path["cpp"] +
+ ' tool_path { name: "dwp" path: "%s" }\n' % tool_path["dwp"] +
+ ' tool_path { name: "gcc" path: "%s" }\n' % tool_path["gcc"] +
+ ' tool_path { name: "gcov" path: "%s" }\n' % tool_path["gcov"] +
+ ' tool_path { name: "ld" path: "%s" }\n' % tool_path["ld"] +
+ ' tool_path { name: "nm" path: "%s" }\n' % tool_path["nm"] +
+ ' tool_path { name: "objcopy" path: "%s" }\n' % tool_path["objcopy"] +
+ ' tool_path { name: "objdump" path: "%s" }\n' % tool_path["objdump"] +
+ ' tool_path { name: "strip" path: "%s" }\n' % tool_path["strip"] +
+ ((' cxx_builtin_include_directory: "%s/include"\n' % tool_path_prefix) if msys_root else "") +
' artifact_name_pattern { category_name: "executable" prefix: "" extension: ".exe"}\n' +
' cxx_flag: "-std=gnu++0x"\n' +
' linker_flag: "-lstdc++"\n' +
- ' cxx_builtin_include_directory: "%s%s/"\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "gcov" path: "%s%s/bin/gcov" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "ld" path: "%s%s/bin/ld" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "nm" path: "%s%s/bin/nm" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "objcopy" path: "%s%s/bin/objcopy" }\n' % (escaped_msys_root, prefix) +
' objcopy_embed_flag: "-I"\n' +
' objcopy_embed_flag: "binary"\n' +
- ' tool_path { name: "objdump" path: "%s%s/bin/objdump" }\n' % (escaped_msys_root, prefix) +
- ' tool_path { name: "strip" path: "%s%s/bin/strip" }' % (escaped_msys_root, prefix) +
' feature { name: "targets_windows" implies: "copy_dynamic_libraries_to_binary" enabled: true }' +
' feature { name: "copy_dynamic_libraries_to_binary" }')
@@ -264,9 +268,12 @@ def configure_windows_toolchain(repository_ctx):
"@bazel_tools//tools/cpp:CROSSTOOL",
"@bazel_tools//tools/cpp:CROSSTOOL.tpl",
"@bazel_tools//tools/cpp:vc_installation_error.bat.tpl",
+ "@bazel_tools//tools/cpp:msys_gcc_installation_error.bat",
])
repository_ctx.symlink(paths["@bazel_tools//tools/cpp:BUILD.static.windows"], "BUILD")
+ repository_ctx.symlink(paths["@bazel_tools//tools/cpp:msys_gcc_installation_error.bat"],
+ "msys_gcc_installation_error.bat")
vc_path = find_vc_path(repository_ctx)
missing_tools = None
| null | test | train | 2018-10-24T13:43:30 | "2018-10-23T12:20:12Z" | laszlocsomor | test |
bazelbuild/bazel/6544_6562 | bazelbuild/bazel | bazelbuild/bazel/6544 | bazelbuild/bazel/6562 | [
"timestamp(timedelta=0.0, similarity=0.9244399942700263)"
] | 5e5832cc7d258dbdbcc2123d58fa6835a7f21333 | bde6c0fd57f9d5d9651cf0c06814c681a302ed25 | [
"A small enhancement: discovering the issue(s) the contributor's commit(s) closes, and linking to those issues too.\r\n\r\ne.g.\r\n\r\n```\r\nThis release contains contributions from many people at Google, as well as:\r\n\r\n* Jane Doe: #1234 Fixes foo bug, #1235 Added bar feature\r\n* John Doe: #1236 Improved baz performance\r\n```",
"@jin Currently we're not linking individual contributors to single issues, just listing everyone who contributed. I'm not sure trying to do that is going to be useful in the release notes: anyone who is interested can check the Git history themselves."
] | [] | "2018-10-31T15:01:34Z" | [
"type: feature request",
"P2",
"area-EngProd",
"team-OSS"
] | Release note generator should add contributors list | Currently, we're manually adding the list of contributors to thank to the release notes: we should instead be generating this.
Current script:
```
git log <previous version baseline>..<current version baseline> --format="%aN <%aE>" | sort | uniq | grep -v 'google\.com' | cut -d '<' -f 1
``` | [
"scripts/release/relnotes.sh"
] | [
"scripts/release/relnotes.sh"
] | [] | diff --git a/scripts/release/relnotes.sh b/scripts/release/relnotes.sh
index c1598c6f50aec6..6557cefe23c214 100755
--- a/scripts/release/relnotes.sh
+++ b/scripts/release/relnotes.sh
@@ -124,8 +124,9 @@ function __format_release_notes() {
# Create the release notes since commit $1 ($2...${[#]} are the cherry-picks,
# so the commits to ignore.
function __release_notes() {
+ local last_release=$1
local i
- local commits=$(__get_release_notes_commits $@)
+ local commits=$(__get_release_notes_commits $last_release)
local length="${#RELNOTES_TYPES[@]}"
__generate_release_notes "$commits"
for (( i=0; $i < $length; i=$i+1 )); do
@@ -140,6 +141,17 @@ function __release_notes() {
echo
fi
done
+
+ # Add a list of contributors to thank.
+ local external_authors=$(git log $last_release..HEAD --format="%aN <%aE>" \
+ | sort \
+ | uniq \
+ | grep -v "google.com" \
+ | sed -e 's/[[:space:]]$//' \
+ | tr '\n' ',' \
+ | sed -e 's/,$/\n/' \
+ | sed -e 's/,/, /g')
+ echo "This release contains contributions from many people at Google, as well as ${external_authors}."
}
# A wrapper around all the previous function, using the CHANGELOG.md
| null | train | train | 2018-10-31T15:53:37 | "2018-10-29T17:07:38Z" | katre | test |
bazelbuild/bazel/6558_6564 | bazelbuild/bazel | bazelbuild/bazel/6558 | bazelbuild/bazel/6564 | [
"timestamp(timedelta=0.0, similarity=0.944254643173867)"
] | 2126d94b7c415aeed2343175aa60410626edd6c3 | 0cb92d09fe44a04283d3bbd11a6d81f0d8ad5486 | [
"@spomorski, we have https://docs.bazel.build/versions/master/be/common-definitions.html, where should the `exec_compatible_with` attribute be documented? It can currently be used with any test rule, and shell rule, or genrule, but we may expand that set in the future.",
"I think that page is fine. You didn't mention build rules, does it work\nwith just test/shell/genrules (I might just be misunderstanding\nshell/genrules)? If it works for build rules, let's just stick it in\n\"Attributes common to all build rules.\"\n\nOn Tue, Oct 30, 2018 at 3:24 PM katre <[email protected]> wrote:\n\n> @spomorski <https://github.com/spomorski>, we have\n> https://docs.bazel.build/versions/master/be/common-definitions.html,\n> where should the exec_compatible_with attribute be documented? It can\n> currently be used with any test rule, and shell rule, or genrule, but we\n> may expand that set in the future.\n>\n> —\n> You are receiving this because you were mentioned.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/bazelbuild/bazel/issues/6558#issuecomment-434434630>,\n> or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AbdI8hfZz5YpyVNoQ1Ya7B5uzkbzbDRCks5uqKd7gaJpZM4YCrC7>\n> .\n>\n",
"Sorry, by shell rules I mean sh_library, sh_binary, and sh_test.\r\n\r\nI'll start adding some documentation to the common definitions."
] | [
"\"The\" -> \"A\" and mention they're not the only ones. How about:\r\n\r\n> A list of <...>constraint_values</...> that must be present in the execution platform for this target. This is in addition to any constraints already imposed by the rule type. Constraints are used to restrict the list of available execution platforms during <...>toolchain resolution</...>.",
"I'd remove \"being configured\", it's clear from context what target we're talking about. Even rule authors don't always know exactly what's entailed by the configuration phase or think in terms of \"configured targets\".",
"\"that do not match these constraints\" -- Arguably it's not just \"the target's\" constraints if we're talking about constraints specified by the rule as well.",
"Done.",
"Done.",
"Done."
] | "2018-10-31T16:51:11Z" | [
"type: documentation (cleanup)",
"P1",
"team-Configurability"
] | Document the exec_compatible_with attribute | We should document the `exec_compatible_with` attribute that can be used to influence the execution platform for a specific target. | [
"site/docs/platforms.md",
"site/docs/toolchains.md",
"src/main/java/com/google/devtools/build/docgen/PredefinedAttributes.java"
] | [
"site/docs/platforms.md",
"site/docs/toolchains.md",
"src/main/java/com/google/devtools/build/docgen/PredefinedAttributes.java",
"src/main/java/com/google/devtools/build/docgen/templates/attributes/common/exec_compatible_with.html"
] | [] | diff --git a/site/docs/platforms.md b/site/docs/platforms.md
index 8935ebbff69e1d..4c3079e2b59e52 100644
--- a/site/docs/platforms.md
+++ b/site/docs/platforms.md
@@ -27,8 +27,7 @@ appropriate
for build actions. Platforms can also be used in combination with the
[config_setting](be/general.html#config_setting)
rule to write
- <a href="https://docs.bazel.build/versions/master/configurable-attributes.html">
- configurable attributes</a>.
+<a href="configurable-attributes.html"> configurable attributes</a>.
Bazel recognizes three roles that a platform may serve:
diff --git a/site/docs/toolchains.md b/site/docs/toolchains.md
index ac0e57b2f564af..94bab12b16097c 100644
--- a/site/docs/toolchains.md
+++ b/site/docs/toolchains.md
@@ -98,7 +98,7 @@ bar_binary(
```
We can improve on this solution by using `select` to choose the `compiler`
-[based on the platform](https://docs.bazel.build/versions/master/configurable-attributes.html):
+[based on the platform](configurable-attributes.html):
```python
config_setting(
@@ -207,7 +207,7 @@ To define some toolchains for a given toolchain type, we need three things:
suite for different platforms.
3. For each such target, an associated target of the generic
-[`toolchain`](https://docs.bazel.build/versions/master/be/platform.html#toolchain)
+[`toolchain`](be/platform.html#toolchain)
rule, to provide metadata used by the toolchain framework.
For our running example, here's a definition for a `bar_toolchain` rule. Our
@@ -361,33 +361,39 @@ This will end up building `//bar_tools:barc_linux` but not
**Note:** Some Bazel rules do not yet support toolchain resolution.
For each target that uses toolchains, Bazel's toolchain resolution procedure
-determines the target's concrete dependencies. The procedure takes as input a
-set of required toolchain types, the target platform, a list of available
-execution platforms, and a list of available toolchains. Its outputs are a
+determines the target's concrete toolchain dependencies. The procedure takes as input a
+set of required toolchain types, the target platform, the list of available
+execution platforms, and the list of available toolchains. Its outputs are a
selected toolchain for each toolchain type as well as a selected execution
platform for the current target.
The available execution platforms and toolchains are gathered from the
`WORKSPACE` file via
-[`register_execution_platforms`](https://docs.bazel.build/versions/master/skylark/lib/globals.html#register_execution_platforms)
+[`register_execution_platforms`](skylark/lib/globals.html#register_execution_platforms)
and
-[`register_toolchains`](https://docs.bazel.build/versions/master/skylark/lib/globals.html#register_toolchains).
+[`register_toolchains`](skylark/lib/globals.html#register_toolchains).
Additional execution platforms and toolchains may also be specified on the
command line via
-[`--extra_execution_platforms`](https://docs.bazel.build/versions/master/command-line-reference.html#flag--extra_execution_platforms)
+[`--extra_execution_platforms`](command-line-reference.html#flag--extra_execution_platforms)
and
-[`--extra_toolchains`](https://docs.bazel.build/versions/master/command-line-reference.html#flag--extra_toolchains).
+[`--extra_toolchains`](command-line-reference.html#flag--extra_toolchains).
The host platform is automatically included as an available execution platform.
Available platforms and toolchains are tracked as ordered lists for determinism,
-with preference given to earlier items in the list.
The resolution steps are as follows.
-1. For each available execution platform, we associate each toolchain type with
+1. If the target specifies the
+ [`exec_compatible_with` attribute](be/common-definitions.html#common.exec_compatible_with)
+ (or the rule specifies the
+ [`exec_compatible_with` argument](skylark/lib/globals.html#rule.exec_compatible_with),
+ the list of available execution platforms is filtered to remove
+ any that do not match the execution constraints.
+
+2. For each available execution platform, we associate each toolchain type with
the first available toolchain, if any, that is compatible with this execution
platform and the target platform.
-2. Any execution platform that failed to find a compatible toolchain for one of
+3. Any execution platform that failed to find a compatible toolchain for one of
its toolchain types is ruled out. Of the remaining platforms, the first one
becomes the current target's execution platform, and its associated
toolchains become dependencies of the target.
diff --git a/src/main/java/com/google/devtools/build/docgen/PredefinedAttributes.java b/src/main/java/com/google/devtools/build/docgen/PredefinedAttributes.java
index 03e711ebde9725..1ba093511c2c4c 100644
--- a/src/main/java/com/google/devtools/build/docgen/PredefinedAttributes.java
+++ b/src/main/java/com/google/devtools/build/docgen/PredefinedAttributes.java
@@ -48,6 +48,7 @@ public class PredefinedAttributes {
"templates/attributes/common/deprecation.html",
"templates/attributes/common/deps.html",
"templates/attributes/common/distribs.html",
+ "templates/attributes/common/exec_compatible_with.html",
"templates/attributes/common/features.html",
"templates/attributes/common/licenses.html",
"templates/attributes/common/restricted_to.html",
diff --git a/src/main/java/com/google/devtools/build/docgen/templates/attributes/common/exec_compatible_with.html b/src/main/java/com/google/devtools/build/docgen/templates/attributes/common/exec_compatible_with.html
new file mode 100644
index 00000000000000..081830f21f4b15
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/docgen/templates/attributes/common/exec_compatible_with.html
@@ -0,0 +1,16 @@
+<p><code>List of <a href="../build-ref.html#labels">labels</a>; optional</code></p>
+
+<p>
+A list of
+<code><a href="platform.html#constraint_value">constraint_values</a></code>
+that must be present in the execution platform for this target. This is in
+addition to any constraints already set by the rule type. Constraints are used
+to restrict the list of available execution platforms, see the description of
+<a href="../toolchains.html#toolchain-resolution">toolchain resolution</a> for
+details.
+</p>
+
+<p>
+This attribute is available only on <code><a href="general.html#genrule">genrule</a></code>,
+<a href="shell.html">shell rules</a>, and all test rules (*_test).
+</p>
| null | train | train | 2018-10-31T17:14:43 | "2018-10-30T19:18:19Z" | katre | test |
bazelbuild/bazel/6589_6599 | bazelbuild/bazel | bazelbuild/bazel/6589 | bazelbuild/bazel/6599 | [
"timestamp(timedelta=6128.0, similarity=0.8487044611062099)"
] | a8e2c2e2dbc7e5db02ab08c1077f31a2f9873e56 | 6b9f2aa65849f4a115a0135a00934e433fcdeec3 | [
"Thanks for the detailed bug report! :) I agree that this should be cleaned up.\r\nI think your suggestion to guard this #define with an #ifndef block is fine.\r\n\r\nI'll fix this right now."
] | [] | "2018-11-05T18:50:29Z" | [
"type: bug",
"P2",
"category: misc > misc",
"area-EngProd",
"team-OSS"
] | __STDC_FORMAT_MACROS warning when bootstrapping on macOS | ### Description of the problem / feature request:
When building Bazel "from scratch" on macOS, the following warning is emitted:
```
INFO: From Compiling src/tools/singlejar/output_jar.cc:
In file included from src/tools/singlejar/output_jar.cc:18:
In file included from ./src/tools/singlejar/output_jar.h:31:
In file included from ./src/tools/singlejar/combiners.h:24:
./src/tools/singlejar/transient_bytes.h:17:9: warning: '__STDC_FORMAT_MACROS' macro redefined [-Wmacro-redefined]
#define __STDC_FORMAT_MACROS 1
^
/Applications/Xcode-10.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/inttypes.h:244:12: note: previous definition is here
# define __STDC_FORMAT_MACROS
^
1 warning generated.
```
Is there an issue here? Or perhaps the `#define __STDC_FORMAT_MACROS 1` should be guarded with an `#ifndef __STDC_FORMAT_MACROS`, just to avoid the warning? I'm no C expert, so I don't know if it's appropriate for this to be unconditionally defined here.
This does not break the build or affect functionality as far as I can tell; it's just a warning to clean up.
### Feature requests: what underlying problem are you trying to solve with this feature?
I'm trying to eliminate a warning during the Bazel build. It would be nice if Bazel built warning-free, so new users can be confident it built correctly.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
This is on:
* macOS 10.13.6
* Xcode 10
* Oracle JDK 7, 8, 9, 10; OpenJDK 11 installed; at the system level
Also happens under Xcode 9.4.
Procedure to build:
```
wget https://github.com/bazelbuild/bazel/releases/download/0.19.0/bazel-0.19.0-dist.zip
unzip bazel-0.19.0-dist.zip
mv bazel-0.19.0-dist.zip ..
./compile.sh
```
The warning is emitted during the `./compile.sh` run.
### What operating system are you running Bazel on?
macOS 10.13.6
### What's the output of `bazel info release`?
```
$ bazel info release
zsh: command not found: bazel
```
This is expected; I do not have Bazel installed, and am building it "from scratch".
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
```
$ git remote get-url origin ; git rev-parse master ; git rev-parse HEAD
fatal: not a git repository (or any of the parent directories): .git
fatal: not a git repository (or any of the parent directories): .git
fatal: not a git repository (or any of the parent directories): .git
```
This is expected; I'm building it from scratch from a release tarball.
### Have you found anything relevant by searching the web?
* It looks like this was introduced in: https://github.com/bazelbuild/bazel/commit/070859a55d7b04f1afe7f46c5b714c8d267bde59
* Which looks like it was to fix: https://github.com/bazelbuild/bazel/issues/3455
* Looks like the same thing is done in input_jar.h at: https://github.com/bazelbuild/bazel/blob/f8be43cebfe5d9ee80e838c883fb305969ece743/src/tools/singlejar/input_jar.h#L18
Most of the other Google results I found were instances of using `__STDC_FORMAT_MACROS` as a compiler command line option via `-D__STDC_FORMAT_MACROS`, instead of defining it in a header file, which makes me wonder if it's being used in quite the conventional manner here?
### Any other information, logs, or outputs that you want to share?
I am a Bazel newbie. I first encountered this while building Bazel to test for https://github.com/Homebrew/homebrew-core/pull/33484. Sorry if this is an obvious issue or inappropriate for this forum.
| [
"src/tools/singlejar/transient_bytes.h"
] | [
"src/tools/singlejar/transient_bytes.h"
] | [] | diff --git a/src/tools/singlejar/transient_bytes.h b/src/tools/singlejar/transient_bytes.h
index c7577aeee3294d..fb239620e39740 100644
--- a/src/tools/singlejar/transient_bytes.h
+++ b/src/tools/singlejar/transient_bytes.h
@@ -14,6 +14,7 @@
#ifndef SRC_TOOLS_SINGLEJAR_TRANSIENT_BYTES_H_
#define SRC_TOOLS_SINGLEJAR_TRANSIENT_BYTES_H_
+#undef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS 1
#include <inttypes.h>
| null | train | train | 2018-11-05T19:44:50 | "2018-11-04T04:26:54Z" | apjanke | test |
bazelbuild/bazel/6592_7335 | bazelbuild/bazel | bazelbuild/bazel/6592 | bazelbuild/bazel/7335 | [
"timestamp(timedelta=46216.0, similarity=0.8406726706695553)"
] | 9b1fe14802fbf74c2ad1257d0a614d663d7818bd | c5856c75ff754061b80385f8da1b5309c8c1ef30 | [
"Cc @lberki @iirina ",
"Related: #6661.",
"@Monnoroch There's no requirement anymore to have the same embedded JDK version as we use for the host javabase so #6661 is talking about updating the JDK version, it's a different JDK.\r\n\r\nIndependently, we also plan to upgrade the embedded JDK after we have submitted some other changes and hopefully it'll land before we cut 0.22.\r\n\r\nIf I understand the new java container support correctly, you probably still want to set a JVM flag in the container. The JVM uses by default 1/4 of the physical available memory for the heap. In a container, you may have less memory available than what's physically in your machine. Now, if the heap grows too large, Bazel gets killed. With the new container support, the \"physical available memory\" is limited to the memory available in the container. Thus, the heap will not grow too large, but it's using 1/4 of the available memory. That may not be enough and you might want to set MaxRamFraction in your CI environment.\r\n",
"> Independently, we also plan to upgrade the embedded JDK after we have submitted some other changes and hopefully it'll land before we cut 0.22.\r\n\r\nI tried 0.22rc2 yesterday and it is still using JDK 9.",
"David, that's correct. I wasn't able to properly test and land the changes mostly because of holidays. I'll definitely do it before 0.23.",
"@meisterT Thanks. Let me know, if you have a commit somewhere. I would be happy to build Bazel from scratch and test it against Gerrit Code Review and related projects."
] | [] | "2019-02-02T23:24:52Z" | [
"type: feature request",
"P2",
"area-EngProd",
"team-Rules-Java",
"team-OSS"
] | Update embedded JDK to 11 to fix a host of docker related issues | ### Description of the problem / feature request:
As far as I can tell bazel is currently coming embedded with openjdk 9 and it is having issues with easily running out of memory in docker containers (most prominently CircleCI it seems), or more generically not respecting cgroups for resource limits.
issues I could find that seem releated:
https://github.com/bazelbuild/bazel/issues/3886
https://github.com/bazelbuild/bazel/issues/4616
https://github.com/bazelbuild/bazel/issues/5180
https://github.com/bazelbuild/bazel/issues/3645
https://github.com/bazelbuild/bazel/issues/5389
https://github.com/bazelbuild/rules_docker/issues/520
### Feature requests: what underlying problem are you trying to solve with this feature?
It turns out OpenJDK 10 comes with a host of fixes that would improve that situation and for us also just seemed to have solved an issue with using CircleCI. I installed bazel pointing at jdk 11 using `startup --server_javabase /usr/lib/jvm/java-11-openjdk-amd64/"` in the bazelrc, removed any flags around `local_resources` and builds that would continuously fail before are now working, in fact I had a build that would even fail with `local_resources` and `-Xmx3072m` set, but pointing bazel to use jdk 11 fixed that.
Here the links to the openjdk issues:
https://bugs.openjdk.java.net/browse/JDK-8196595
https://bugs.openjdk.java.net/browse/JDK-8146115
https://bugs.openjdk.java.net/browse/JDK-8170888
https://bugs.openjdk.java.net/browse/JDK-8140793
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Probably not that easy to reproduce, but I know rules_nodejs use circleci and had similar issues in the past that where solved with setting the same flags here: https://github.com/bazelbuild/rules_nodejs/blob/master/.circleci/bazel.rc#L17
So maybe they would be a good test case, trying to remove the flags and see if the situation improves. cc @alexeagle
### What operating system are you running Bazel on?
Ubuntu 18.04, the docker images are running on debian stretch
### What's the output of `bazel info release`?
release 0.19.0
### Have you found anything relevant by searching the web?
Yep, see issues linked above. | [
"WORKSPACE"
] | [
"WORKSPACE"
] | [] | diff --git a/WORKSPACE b/WORKSPACE
index 7f4b66eb29a675..1b8f7685255a43 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -131,9 +131,9 @@ http_file(
http_file(
name = "openjdk_linux_vanilla",
downloaded_file_path = "zulu-linux-vanilla.tar.gz",
- sha256 = "232b1c3511f0d26e92582b7c3cc363be7ac633e371854ca2f2e9f2b50eb72a75",
+ sha256 = "f3f44b6235508e87b760bf37a49e186cc1fa4e9cd28384c4dbf5a33991921e08",
urls = [
- "https://mirror.bazel.build/openjdk/azul-zulu11.2.3-jdk11.0.1/zulu11.2.3-jdk11.0.1-linux_x64.tar.gz",
+ "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-linux_x64.tar.gz",
],
)
@@ -170,9 +170,9 @@ http_file(
http_file(
name = "openjdk_macos_vanilla",
downloaded_file_path = "zulu-macos-vanilla.tar.gz",
- sha256 = "1edf366ee821e5db8e348152fcb337b28dfd6bf0f97943c270dcc6747cedb6cb",
+ sha256 = "059f8e3484bf07b63a8f2820d5f528f473eff1befdb1896ee4f8ff06be3b8d8f",
urls = [
- "https://mirror.bazel.build/openjdk/azul-zulu11.2.3-jdk11.0.1/zulu11.2.3-jdk11.0.1-macosx_x64.tar.gz",
+ "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-macosx_x64.zip",
],
)
@@ -197,9 +197,9 @@ http_file(
http_file(
name = "openjdk_win_vanilla",
downloaded_file_path = "zulu-win-vanilla.zip",
- sha256 = "8e1e2b8347de6746f3fd1538840dd643201533ab113abc4ed93678e342d28aa3",
+ sha256 = "e1f5b4ce1b9148140fae2fcfb8a96d1c9b7eac5b8df0e13fbcad9b8561284880",
urls = [
- "https://mirror.bazel.build/openjdk/azul-zulu11.2.3-jdk11.0.1/zulu11.2.3-jdk11.0.1-win_x64.zip",
+ "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-win_x64.zip",
],
)
@@ -282,6 +282,9 @@ distdir_tar(
"zulu11.2.3-jdk11.0.1-linux_x64.tar.gz",
"zulu11.2.3-jdk11.0.1-macosx_x64.tar.gz",
"zulu11.2.3-jdk11.0.1-win_x64.zip",
+ "zulu11.29.3-ca-jdk11.0.2-linux_x64.tar.gz",
+ "zulu11.29.3-ca-jdk11.0.2-macosx_x64.zip",
+ "zulu11.29.3-ca-jdk11.0.2-win_x64.zip",
],
dirname = "jdk_WORKSPACE/distdir",
sha256 = {
@@ -297,6 +300,9 @@ distdir_tar(
"zulu11.2.3-jdk11.0.1-linux_x64.tar.gz": "232b1c3511f0d26e92582b7c3cc363be7ac633e371854ca2f2e9f2b50eb72a75",
"zulu11.2.3-jdk11.0.1-macosx_x64.tar.gz": "1edf366ee821e5db8e348152fcb337b28dfd6bf0f97943c270dcc6747cedb6cb",
"zulu11.2.3-jdk11.0.1-win_x64.zip": "8e1e2b8347de6746f3fd1538840dd643201533ab113abc4ed93678e342d28aa3",
+ "zulu11.29.3-ca-jdk11.0.2-linux_x64.tar.gz": "f3f44b6235508e87b760bf37a49e186cc1fa4e9cd28384c4dbf5a33991921e08",
+ "zulu11.29.3-ca-jdk11.0.2-macosx_x64.zip": "059f8e3484bf07b63a8f2820d5f528f473eff1befdb1896ee4f8ff06be3b8d8f",
+ "zulu11.29.3-ca-jdk11.0.2-win_x64.zip": "e1f5b4ce1b9148140fae2fcfb8a96d1c9b7eac5b8df0e13fbcad9b8561284880",
},
urls = {
"zulu9.0.7.1-jdk9.0.7-linux_x64-allmodules.tar.gz": ["https://mirror.bazel.build/openjdk/azul-zulu-9.0.7.1-jdk9.0.7/zulu9.0.7.1-jdk9.0.7-linux_x64-allmodules.tar.gz"],
@@ -311,6 +317,9 @@ distdir_tar(
"zulu11.2.3-jdk11.0.1-linux_x64.tar.gz": ["https://mirror.bazel.build/openjdk/azul-zulu11.2.3-jdk11.0.1/zulu11.2.3-jdk11.0.1-linux_x64.tar.gz"],
"zulu11.2.3-jdk11.0.1-macosx_x64.tar.gz": ["https://mirror.bazel.build/openjdk/azul-zulu11.2.3-jdk11.0.1/zulu11.2.3-jdk11.0.1-macosx_x64.tar.gz"],
"zulu11.2.3-jdk11.0.1-win_x64.zip": ["https://mirror.bazel.build/openjdk/azul-zulu11.2.3-jdk11.0.1/zulu11.2.3-jdk11.0.1-win_x64.zip"],
+ "zulu11.29.3-ca-jdk11.0.2-linux_x64.tar.gz": ["https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-linux_x64.tar.gz"],
+ "zulu11.29.3-ca-jdk11.0.2-macosx_x64.zip": ["https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-macosx_x64.zip"],
+ "zulu11.29.3-ca-jdk11.0.2-win_x64.zip": ["https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-win_x64.zip"],
},
)
| null | train | train | 2019-02-02T17:40:48 | "2018-11-05T08:28:52Z" | Globegitter | test |
bazelbuild/bazel/6613_6616 | bazelbuild/bazel | bazelbuild/bazel/6613 | bazelbuild/bazel/6616 | [
"timestamp(timedelta=73717.0, similarity=0.845320405934995)"
] | ee28af4f86783fa84cc1c0d96ca0eca9bb7bf1d0 | 57bb91e794eb89f2989f6b7bffca09333305e011 | [
"After some debugging, the problem is much simpler: the `--extra_toolchains` flag was not allowing multiple uses, so the last value passed was replacing the previous ones.\r\n\r\nI'll send a patch to fix that, until that is released you can use the multiple value format:\r\n```\r\nbazel build --extra_toolchains=//toolchains/docker:default_linux_toolchain,//toolchains/docker:default_windows_toolchain,//toolchains/docker:default_osx_toolchain\r\n```\r\nOr, even use the target pattern version:\r\n```\r\nbazel build --extra_toolchains=//toolchains/docker:all\r\n```\r\n"
] | [] | "2018-11-06T19:33:39Z" | [
"type: bug",
"P2",
"team-Configurability"
] | Multiple toolchain rules unable to use same implementation | ### Description of the problem / feature request:
Look at the toolchain rules added by https://github.com/bazelbuild/rules_docker/pull/559 in //toolchains/docker/BUILD. There are three toolchains of //toolchains/docker:toolchain_type using the same implementation function. Bazel appears to arbitrarily pick one of these toolchains during toolchain resolution
### Feature requests: what underlying problem are you trying to solve with this feature?
Reuse the toolchain implementation with multiple toolchain rules
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Not entirely sure. I reproduced the issue with blaze. @katre has more context
### What operating system are you running Bazel on?
Linux
| [
"src/main/java/com/google/devtools/build/lib/analysis/ToolchainContext.java",
"src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionValue.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/ToolchainContext.java",
"src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunction.java",
"src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionValue.java"
] | [
"src/test/java/com/google/devtools/build/lib/BUILD",
"src/test/java/com/google/devtools/build/lib/analysis/ToolchainResolverTest.java",
"src/test/java/com/google/devtools/build/lib/rules/platform/ToolchainTestCase.java",
"src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunctionTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/ToolchainContext.java b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainContext.java
index 35c70054e8a508..368b53f4140407 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/ToolchainContext.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainContext.java
@@ -22,6 +22,7 @@
import com.google.common.collect.ImmutableSet;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.analysis.platform.ToolchainInfo;
+import com.google.devtools.build.lib.analysis.platform.ToolchainTypeInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
@@ -31,6 +32,7 @@
import com.google.devtools.build.lib.skylarkinterface.SkylarkPrinter;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.EvalUtils;
+import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
@@ -57,10 +59,10 @@ interface Builder {
Builder setTargetPlatform(PlatformInfo targetPlatform);
/** Sets the toolchain types that were requested. */
- Builder setRequiredToolchainTypes(Set<Label> requiredToolchainTypes);
+ Builder setRequiredToolchainTypes(Set<ToolchainTypeInfo> requiredToolchainTypes);
/** Sets the map from toolchain type to toolchain provider. */
- Builder setToolchains(ImmutableMap<Label, ToolchainInfo> toolchains);
+ Builder setToolchains(ImmutableMap<ToolchainTypeInfo, ToolchainInfo> toolchains);
/** Sets the template variables that these toolchains provide. */
Builder setTemplateVariableProviders(ImmutableList<TemplateVariableInfo> providers);
@@ -82,9 +84,9 @@ interface Builder {
public abstract PlatformInfo targetPlatform();
/** Returns the toolchain types that were requested. */
- public abstract ImmutableSet<Label> requiredToolchainTypes();
+ public abstract ImmutableSet<ToolchainTypeInfo> requiredToolchainTypes();
- abstract ImmutableMap<Label, ToolchainInfo> toolchains();
+ abstract ImmutableMap<ToolchainTypeInfo, ToolchainInfo> toolchains();
/** Returns the template variables that these toolchains provide. */
public abstract ImmutableList<TemplateVariableInfo> templateVariableProviders();
@@ -97,7 +99,20 @@ interface Builder {
* required in this context.
*/
@Nullable
- public ToolchainInfo forToolchainType(Label toolchainType) {
+ public ToolchainInfo forToolchainType(Label toolchainTypeLabel) {
+ Optional<ToolchainTypeInfo> toolchainType =
+ toolchains().keySet().stream()
+ .filter(info -> info.typeLabel().equals(toolchainTypeLabel))
+ .findFirst();
+ if (toolchainType.isPresent()) {
+ return forToolchainType(toolchainType.get());
+ } else {
+ return null;
+ }
+ }
+
+ @Nullable
+ public ToolchainInfo forToolchainType(ToolchainTypeInfo toolchainType) {
return toolchains().get(toolchainType);
}
@@ -109,13 +124,19 @@ public boolean isImmutable() {
@Override
public void repr(SkylarkPrinter printer) {
printer.append("<toolchain_context.resolved_labels: ");
- printer.append(toolchains().keySet().stream().map(Label::toString).collect(joining(", ")));
+ printer.append(
+ toolchains().keySet().stream()
+ .map(ToolchainTypeInfo::typeLabel)
+ .map(Label::toString)
+ .collect(joining(", ")));
printer.append(">");
}
private Label transformKey(Object key, Location loc) throws EvalException {
if (key instanceof Label) {
return (Label) key;
+ } else if (key instanceof ToolchainTypeInfo) {
+ return ((ToolchainTypeInfo) key).typeLabel();
} else if (key instanceof String) {
Label toolchainType;
String rawLabel = (String) key;
@@ -137,23 +158,31 @@ private Label transformKey(Object key, Location loc) throws EvalException {
@Override
public ToolchainInfo getIndex(Object key, Location loc) throws EvalException {
- Label toolchainType = transformKey(key, loc);
+ Label toolchainTypeLabel = transformKey(key, loc);
- if (!requiredToolchainTypes().contains(toolchainType)) {
+ if (!containsKey(key, loc)) {
throw new EvalException(
loc,
String.format(
"In %s, toolchain type %s was requested but only types [%s] are configured",
targetDescription(),
- toolchainType,
- requiredToolchainTypes().stream().map(Label::toString).collect(joining())));
+ toolchainTypeLabel,
+ requiredToolchainTypes().stream()
+ .map(ToolchainTypeInfo::typeLabel)
+ .map(Label::toString)
+ .collect(joining(", "))));
}
- return forToolchainType(toolchainType);
+ return forToolchainType(toolchainTypeLabel);
}
@Override
public boolean containsKey(Object key, Location loc) throws EvalException {
- Label toolchainType = transformKey(key, loc);
- return toolchains().containsKey(toolchainType);
+ Label toolchainTypeLabel = transformKey(key, loc);
+ Optional<Label> matching =
+ toolchains().keySet().stream()
+ .map(ToolchainTypeInfo::typeLabel)
+ .filter(label -> label.equals(toolchainTypeLabel))
+ .findAny();
+ return matching.isPresent();
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java
index c2f3819b4c9d49..e8c5c5dcafc818 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java
@@ -19,7 +19,6 @@
import static java.util.stream.Collectors.joining;
import com.google.auto.value.AutoValue;
-import com.google.common.base.Joiner;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
@@ -31,6 +30,7 @@
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
import com.google.devtools.build.lib.analysis.platform.PlatformProviderUtils;
import com.google.devtools.build.lib.analysis.platform.ToolchainInfo;
+import com.google.devtools.build.lib.analysis.platform.ToolchainTypeInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.packages.Attribute;
@@ -71,7 +71,7 @@ public class ToolchainResolver {
// Optional data.
private String targetDescription = "";
- private ImmutableSet<Label> requiredToolchainTypes = ImmutableSet.of();
+ private ImmutableSet<Label> requiredToolchainTypeLabels = ImmutableSet.of();
private ImmutableSet<Label> execConstraintLabels = ImmutableSet.of();
// Determined during execution.
@@ -98,9 +98,12 @@ public ToolchainResolver setTargetDescription(String targetDescription) {
return this;
}
- /** Sets the required toolchain types that this resolver needs to find toolchains for. */
- public ToolchainResolver setRequiredToolchainTypes(Set<Label> requiredToolchainTypes) {
- this.requiredToolchainTypes = ImmutableSet.copyOf(requiredToolchainTypes);
+ /**
+ * Sets the labels of the required toolchain types that this resolver needs to find toolchains
+ * for.
+ */
+ public ToolchainResolver setRequiredToolchainTypes(Set<Label> requiredToolchainTypeLabels) {
+ this.requiredToolchainTypeLabels = ImmutableSet.copyOf(requiredToolchainTypeLabels);
return this;
}
@@ -137,9 +140,7 @@ public UnloadedToolchainContext resolve() throws InterruptedException, Toolchain
try {
UnloadedToolchainContext.Builder unloadedToolchainContext =
UnloadedToolchainContext.builder();
- unloadedToolchainContext
- .setTargetDescription(targetDescription)
- .setRequiredToolchainTypes(requiredToolchainTypes);
+ unloadedToolchainContext.setTargetDescription(targetDescription);
// Determine the configuration being used.
BuildConfigurationValue value =
@@ -307,11 +308,11 @@ private void determineToolchainImplementations(
// Find the toolchains for the required toolchain types.
List<ToolchainResolutionValue.Key> registeredToolchainKeys = new ArrayList<>();
- for (Label toolchainType : requiredToolchainTypes) {
+ for (Label toolchainTypeLabel : requiredToolchainTypeLabels) {
registeredToolchainKeys.add(
ToolchainResolutionValue.key(
configurationKey,
- toolchainType,
+ toolchainTypeLabel,
platformKeys.targetPlatformKey(),
platformKeys.executionPlatformKeys()));
}
@@ -325,14 +326,14 @@ private void determineToolchainImplementations(
boolean valuesMissing = false;
// Determine the potential set of toolchains.
- Table<ConfiguredTargetKey, Label, Label> resolvedToolchains = HashBasedTable.create();
+ Table<ConfiguredTargetKey, ToolchainTypeInfo, Label> resolvedToolchains =
+ HashBasedTable.create();
+ ImmutableSet.Builder<ToolchainTypeInfo> requiredToolchainTypesBuilder = ImmutableSet.builder();
List<Label> missingToolchains = new ArrayList<>();
for (Map.Entry<
SkyKey, ValueOrException2<NoToolchainFoundException, InvalidToolchainLabelException>>
entry : results.entrySet()) {
try {
- Label requiredToolchainType =
- ((ToolchainResolutionValue.Key) entry.getKey().argument()).toolchainType();
ValueOrException2<NoToolchainFoundException, InvalidToolchainLabelException>
valueOrException = entry.getValue();
ToolchainResolutionValue toolchainResolutionValue =
@@ -342,11 +343,13 @@ private void determineToolchainImplementations(
continue;
}
+ ToolchainTypeInfo requiredToolchainType = toolchainResolutionValue.toolchainType();
+ requiredToolchainTypesBuilder.add(requiredToolchainType);
resolvedToolchains.putAll(
findPlatformsAndLabels(requiredToolchainType, toolchainResolutionValue));
} catch (NoToolchainFoundException e) {
// Save the missing type and continue looping to check for more.
- missingToolchains.add(e.missingToolchainType());
+ missingToolchains.add(e.missingToolchainTypeLabel());
}
}
@@ -358,9 +361,11 @@ private void determineToolchainImplementations(
throw new ValueMissingException();
}
+ ImmutableSet<ToolchainTypeInfo> requiredToolchainTypes = requiredToolchainTypesBuilder.build();
+
// Find and return the first execution platform which has all required toolchains.
Optional<ConfiguredTargetKey> selectedExecutionPlatformKey;
- if (requiredToolchainTypes.isEmpty()
+ if (requiredToolchainTypeLabels.isEmpty()
&& platformKeys.executionPlatformKeys().contains(platformKeys.hostPlatformKey())) {
// Fall back to the legacy behavior: use the host platform if it's available, otherwise the
// first execution platform.
@@ -369,12 +374,12 @@ private void determineToolchainImplementations(
// If there are no toolchains, this will return the first execution platform.
selectedExecutionPlatformKey =
findExecutionPlatformForToolchains(
- platformKeys.executionPlatformKeys(), resolvedToolchains);
+ requiredToolchainTypes, platformKeys.executionPlatformKeys(), resolvedToolchains);
}
if (!selectedExecutionPlatformKey.isPresent()) {
throw new NoMatchingPlatformException(
- requiredToolchainTypes,
+ requiredToolchainTypeLabels,
platformKeys.executionPlatformKeys(),
platformKeys.targetPlatformKey());
}
@@ -387,11 +392,13 @@ private void determineToolchainImplementations(
throw new ValueMissingException();
}
+ unloadedToolchainContext.setRequiredToolchainTypes(requiredToolchainTypes);
unloadedToolchainContext.setExecutionPlatform(
platforms.get(selectedExecutionPlatformKey.get()));
unloadedToolchainContext.setTargetPlatform(platforms.get(platformKeys.targetPlatformKey()));
- Map<Label, Label> toolchains = resolvedToolchains.row(selectedExecutionPlatformKey.get());
+ Map<ToolchainTypeInfo, Label> toolchains =
+ resolvedToolchains.row(selectedExecutionPlatformKey.get());
unloadedToolchainContext.setToolchainTypeToResolved(ImmutableBiMap.copyOf(toolchains));
}
@@ -399,10 +406,11 @@ private void determineToolchainImplementations(
* Adds all of toolchain labels from{@code toolchainResolutionValue} to {@code
* resolvedToolchains}.
*/
- private static Table<ConfiguredTargetKey, Label, Label> findPlatformsAndLabels(
- Label requiredToolchainType, ToolchainResolutionValue toolchainResolutionValue) {
+ private static Table<ConfiguredTargetKey, ToolchainTypeInfo, Label> findPlatformsAndLabels(
+ ToolchainTypeInfo requiredToolchainType, ToolchainResolutionValue toolchainResolutionValue) {
- Table<ConfiguredTargetKey, Label, Label> resolvedToolchains = HashBasedTable.create();
+ Table<ConfiguredTargetKey, ToolchainTypeInfo, Label> resolvedToolchains =
+ HashBasedTable.create();
for (Map.Entry<ConfiguredTargetKey, Label> entry :
toolchainResolutionValue.availableToolchainLabels().entrySet()) {
resolvedToolchains.put(entry.getKey(), requiredToolchainType, entry.getValue());
@@ -415,10 +423,12 @@ private static Table<ConfiguredTargetKey, Label, Label> findPlatformsAndLabels(
* resolvedToolchains} and has all required toolchain types.
*/
private Optional<ConfiguredTargetKey> findExecutionPlatformForToolchains(
+ ImmutableSet<ToolchainTypeInfo> requiredToolchainTypes,
ImmutableList<ConfiguredTargetKey> availableExecutionPlatformKeys,
- Table<ConfiguredTargetKey, Label, Label> resolvedToolchains) {
+ Table<ConfiguredTargetKey, ToolchainTypeInfo, Label> resolvedToolchains) {
for (ConfiguredTargetKey executionPlatformKey : availableExecutionPlatformKeys) {
- Map<Label, Label> toolchains = resolvedToolchains.row(executionPlatformKey);
+ Map<ToolchainTypeInfo, Label> toolchains = resolvedToolchains.row(executionPlatformKey);
+
if (!toolchains.keySet().containsAll(requiredToolchainTypes)) {
// Not all toolchains are present, keep going
continue;
@@ -427,7 +437,10 @@ private Optional<ConfiguredTargetKey> findExecutionPlatformForToolchains(
if (debug) {
String selectedToolchains =
toolchains.entrySet().stream()
- .map(e -> String.format("type %s -> toolchain %s", e.getKey(), e.getValue()))
+ .map(
+ e ->
+ String.format(
+ "type %s -> toolchain %s", e.getKey().typeLabel(), e.getValue()))
.collect(joining(", "));
environment
.getListener()
@@ -467,9 +480,10 @@ public interface Builder {
Builder setTargetPlatform(PlatformInfo targetPlatform);
/** Sets the toolchain types that were requested. */
- Builder setRequiredToolchainTypes(Set<Label> requiredToolchainTypes);
+ Builder setRequiredToolchainTypes(Set<ToolchainTypeInfo> requiredToolchainTypes);
- Builder setToolchainTypeToResolved(ImmutableBiMap<Label, Label> toolchainTypeToResolved);
+ Builder setToolchainTypeToResolved(
+ ImmutableBiMap<ToolchainTypeInfo, Label> toolchainTypeToResolved);
UnloadedToolchainContext build();
}
@@ -484,10 +498,10 @@ public interface Builder {
abstract PlatformInfo targetPlatform();
/** Returns the toolchain types that were requested. */
- abstract ImmutableSet<Label> requiredToolchainTypes();
+ abstract ImmutableSet<ToolchainTypeInfo> requiredToolchainTypes();
/** The map of toolchain type to resolved toolchain to be used. */
- abstract ImmutableBiMap<Label, Label> toolchainTypeToResolved();
+ abstract ImmutableBiMap<ToolchainTypeInfo, Label> toolchainTypeToResolved();
/** Returns the labels of the specific toolchains being used. */
public ImmutableSet<Label> resolvedToolchainLabels() {
@@ -517,13 +531,15 @@ public ToolchainContext load(
attribute ->
attribute.getName().equals(PlatformSemantics.RESOLVED_TOOLCHAINS_ATTR))
.findFirst();
- ImmutableMap.Builder<Label, ToolchainInfo> toolchains = new ImmutableMap.Builder<>();
+ ImmutableMap.Builder<ToolchainTypeInfo, ToolchainInfo> toolchains =
+ new ImmutableMap.Builder<>();
ImmutableList.Builder<TemplateVariableInfo> templateVariableProviders =
new ImmutableList.Builder<>();
if (toolchainAttribute.isPresent()) {
for (ConfiguredTargetAndData target : prerequisiteMap.get(toolchainAttribute.get())) {
Label discoveredLabel = target.getTarget().getLabel();
- Label toolchainType = toolchainTypeToResolved().inverse().get(discoveredLabel);
+ ToolchainTypeInfo toolchainType =
+ toolchainTypeToResolved().inverse().get(discoveredLabel);
// If the toolchainType hadn't been resolved to an actual toolchain, resolution would have
// failed with an error much earlier. This null check is just for safety.
@@ -560,17 +576,19 @@ private ValueMissingException() {
/** Exception used when no execution platform can be found. */
static final class NoMatchingPlatformException extends ToolchainException {
NoMatchingPlatformException(
- Set<Label> requiredToolchains,
+ Set<Label> requiredToolchainTypeLabels,
ImmutableList<ConfiguredTargetKey> availableExecutionPlatformKeys,
ConfiguredTargetKey targetPlatformKey) {
- super(formatError(requiredToolchains, availableExecutionPlatformKeys, targetPlatformKey));
+ super(
+ formatError(
+ requiredToolchainTypeLabels, availableExecutionPlatformKeys, targetPlatformKey));
}
private static String formatError(
- Set<Label> requiredToolchains,
+ Set<Label> requiredToolchainTypeLabels,
ImmutableList<ConfiguredTargetKey> availableExecutionPlatformKeys,
ConfiguredTargetKey targetPlatformKey) {
- if (requiredToolchains.isEmpty()) {
+ if (requiredToolchainTypeLabels.isEmpty()) {
return String.format(
"Unable to find an execution platform for target platform %s"
+ " from available execution platforms [%s]",
@@ -582,7 +600,7 @@ private static String formatError(
return String.format(
"Unable to find an execution platform for toolchains [%s] and target platform %s"
+ " from available execution platforms [%s]",
- Joiner.on(", ").join(requiredToolchains),
+ requiredToolchainTypeLabels.stream().map(Label::toString).collect(joining(", ")),
targetPlatformKey.getLabel(),
availableExecutionPlatformKeys.stream()
.map(key -> key.getLabel().toString())
@@ -596,7 +614,7 @@ static final class UnresolvedToolchainsException extends ToolchainException {
super(
String.format(
"no matching toolchains found for types %s",
- Joiner.on(", ").join(missingToolchainTypes)));
+ missingToolchainTypes.stream().map(Label::toString).collect(joining(", "))));
}
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunction.java b/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunction.java
index 427ca6168578e3..61d3f259b35829 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunction.java
@@ -26,6 +26,7 @@
import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
import com.google.devtools.build.lib.analysis.platform.DeclaredToolchainInfo;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
+import com.google.devtools.build.lib.analysis.platform.ToolchainTypeInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
@@ -76,24 +77,13 @@ public SkyValue compute(SkyKey skyKey, Environment env)
// Find the right one.
boolean debug = configuration.getOptions().get(PlatformOptions.class).toolchainResolutionDebug;
- ImmutableMap<ConfiguredTargetKey, Label> resolvedToolchainLabels =
- resolveConstraints(
- key.toolchainType(),
- key.availableExecutionPlatformKeys(),
- key.targetPlatformKey(),
- toolchains.registeredToolchains(),
- env,
- debug ? env.getListener() : null);
- if (resolvedToolchainLabels == null) {
- return null;
- }
-
- if (resolvedToolchainLabels.isEmpty()) {
- throw new ToolchainResolutionFunctionException(
- new NoToolchainFoundException(key.toolchainType()));
- }
-
- return ToolchainResolutionValue.create(resolvedToolchainLabels);
+ return resolveConstraints(
+ key.toolchainTypeLabel(),
+ key.availableExecutionPlatformKeys(),
+ key.targetPlatformKey(),
+ toolchains.registeredToolchains(),
+ env,
+ debug ? env.getListener() : null);
}
/**
@@ -102,8 +92,8 @@ public SkyValue compute(SkyKey skyKey, Environment env)
* platform.
*/
@Nullable
- private static ImmutableMap<ConfiguredTargetKey, Label> resolveConstraints(
- Label toolchainType,
+ private static ToolchainResolutionValue resolveConstraints(
+ Label toolchainTypeLabel,
List<ConfiguredTargetKey> availableExecutionPlatformKeys,
ConfiguredTargetKey targetPlatformKey,
ImmutableList<DeclaredToolchainInfo> toolchains,
@@ -135,11 +125,12 @@ private static ImmutableMap<ConfiguredTargetKey, Label> resolveConstraints(
// check whether a platform has already been seen during processing.
Set<ConfiguredTargetKey> platformKeysSeen = new HashSet<>();
ImmutableMap.Builder<ConfiguredTargetKey, Label> builder = ImmutableMap.builder();
+ ToolchainTypeInfo toolchainType = null;
- debugMessage(eventHandler, "Looking for toolchain of type %s...", toolchainType);
+ debugMessage(eventHandler, "Looking for toolchain of type %s...", toolchainTypeLabel);
for (DeclaredToolchainInfo toolchain : toolchains) {
// Make sure the type matches.
- if (!toolchain.toolchainType().typeLabel().equals(toolchainType)) {
+ if (!toolchain.toolchainType().typeLabel().equals(toolchainTypeLabel)) {
continue;
}
debugMessage(eventHandler, " Considering toolchain %s...", toolchain.toolchainLabel());
@@ -164,6 +155,7 @@ private static ImmutableMap<ConfiguredTargetKey, Label> resolveConstraints(
// Only add the toolchains if this is a new platform.
if (!platformKeysSeen.contains(executionPlatformKey)) {
+ toolchainType = toolchain.toolchainType();
builder.put(executionPlatformKey, toolchain.toolchainLabel());
platformKeysSeen.add(executionPlatformKey);
}
@@ -177,15 +169,18 @@ private static ImmutableMap<ConfiguredTargetKey, Label> resolveConstraints(
debugMessage(
eventHandler,
" For toolchain type %s, possible execution platforms and toolchains: {%s}",
- toolchainType,
- resolvedToolchainLabels
- .entrySet()
- .stream()
+ toolchainTypeLabel,
+ resolvedToolchainLabels.entrySet().stream()
.map(e -> String.format("%s -> %s", e.getKey().getLabel(), e.getValue()))
.collect(joining(", ")));
}
- return resolvedToolchainLabels;
+ if (toolchainType == null || resolvedToolchainLabels.isEmpty()) {
+ throw new ToolchainResolutionFunctionException(
+ new NoToolchainFoundException(toolchainTypeLabel));
+ }
+
+ return ToolchainResolutionValue.create(toolchainType, resolvedToolchainLabels);
}
/**
@@ -247,15 +242,15 @@ public String extractTag(SkyKey skyKey) {
/** Used to indicate that a toolchain was not found for the current request. */
public static final class NoToolchainFoundException extends NoSuchThingException {
- private final Label missingToolchainType;
+ private final Label missingToolchainTypeLabel;
- public NoToolchainFoundException(Label missingToolchainType) {
- super(String.format("no matching toolchain found for %s", missingToolchainType));
- this.missingToolchainType = missingToolchainType;
+ public NoToolchainFoundException(Label missingToolchainTypeLabel) {
+ super(String.format("no matching toolchain found for %s", missingToolchainTypeLabel));
+ this.missingToolchainTypeLabel = missingToolchainTypeLabel;
}
- public Label missingToolchainType() {
- return missingToolchainType;
+ public Label missingToolchainTypeLabel() {
+ return missingToolchainTypeLabel;
}
}
diff --git a/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionValue.java b/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionValue.java
index 341be5acefa345..128269c499e991 100644
--- a/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionValue.java
+++ b/src/main/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionValue.java
@@ -17,6 +17,7 @@
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.analysis.platform.ToolchainTypeInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.skyframe.SkyFunctionName;
@@ -37,11 +38,11 @@ public abstract class ToolchainResolutionValue implements SkyValue {
// A key representing the input data.
public static Key key(
BuildConfigurationValue.Key configurationKey,
- Label toolchainType,
+ Label toolchainTypeLabel,
ConfiguredTargetKey targetPlatformKey,
List<ConfiguredTargetKey> availableExecutionPlatformKeys) {
return Key.create(
- configurationKey, toolchainType, targetPlatformKey, availableExecutionPlatformKeys);
+ configurationKey, toolchainTypeLabel, targetPlatformKey, availableExecutionPlatformKeys);
}
/** {@link SkyKey} implementation used for {@link ToolchainResolutionFunction}. */
@@ -57,7 +58,7 @@ public SkyFunctionName functionName() {
abstract BuildConfigurationValue.Key configurationKey();
- public abstract Label toolchainType();
+ public abstract Label toolchainTypeLabel();
abstract ConfiguredTargetKey targetPlatformKey();
@@ -66,12 +67,12 @@ public SkyFunctionName functionName() {
@AutoCodec.Instantiator
static Key create(
BuildConfigurationValue.Key configurationKey,
- Label toolchainType,
+ Label toolchainTypeLabel,
ConfiguredTargetKey targetPlatformKey,
List<ConfiguredTargetKey> availableExecutionPlatformKeys) {
return new AutoValue_ToolchainResolutionValue_Key(
configurationKey,
- toolchainType,
+ toolchainTypeLabel,
targetPlatformKey,
ImmutableList.copyOf(availableExecutionPlatformKeys));
}
@@ -79,10 +80,14 @@ static Key create(
@AutoCodec.Instantiator
public static ToolchainResolutionValue create(
+ ToolchainTypeInfo toolchainType,
ImmutableMap<ConfiguredTargetKey, Label> availableToolchainLabels) {
- return new AutoValue_ToolchainResolutionValue(availableToolchainLabels);
+ return new AutoValue_ToolchainResolutionValue(toolchainType, availableToolchainLabels);
}
+ /** Returns the resolved details about the requested toolchain type. */
+ public abstract ToolchainTypeInfo toolchainType();
+
/**
* Returns the resolved set of toolchain labels (as {@link Label}) for the requested toolchain
* type, keyed by the execution platforms (as {@link ConfiguredTargetKey}). Ordering is not
| diff --git a/src/test/java/com/google/devtools/build/lib/BUILD b/src/test/java/com/google/devtools/build/lib/BUILD
index 4a2b649c335f24..d29b4a78684b04 100644
--- a/src/test/java/com/google/devtools/build/lib/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/BUILD
@@ -812,6 +812,7 @@ java_test(
"//src/main/java/com/google/devtools/build/lib:skylarkinterface",
"//src/main/java/com/google/devtools/build/lib:util",
"//src/main/java/com/google/devtools/build/lib/actions",
+ "//src/main/java/com/google/devtools/build/lib/analysis/platform",
"//src/main/java/com/google/devtools/build/lib/buildeventstream",
"//src/main/java/com/google/devtools/build/lib/buildeventstream/proto:build_event_stream_java_proto",
"//src/main/java/com/google/devtools/build/lib/causes",
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/ToolchainResolverTest.java b/src/test/java/com/google/devtools/build/lib/analysis/ToolchainResolverTest.java
index f518354ade9a34..5ceade08b983c9 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/ToolchainResolverTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/ToolchainResolverTest.java
@@ -25,6 +25,7 @@
import com.google.devtools.build.lib.analysis.ToolchainResolver.NoMatchingPlatformException;
import com.google.devtools.build.lib.analysis.ToolchainResolver.UnloadedToolchainContext;
import com.google.devtools.build.lib.analysis.ToolchainResolver.UnresolvedToolchainsException;
+import com.google.devtools.build.lib.analysis.platform.ToolchainTypeInfo;
import com.google.devtools.build.lib.analysis.util.AnalysisMock;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.packages.Attribute;
@@ -97,7 +98,8 @@ public void resolve() throws Exception {
useConfiguration("--platforms=//platforms:linux");
ResolveToolchainsKey key =
- ResolveToolchainsKey.create("test", ImmutableSet.of(testToolchainType), targetConfigKey);
+ ResolveToolchainsKey.create(
+ "test", ImmutableSet.of(testToolchainTypeLabel), targetConfigKey);
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
@@ -196,7 +198,7 @@ public void resolve_unavailableToolchainType_single() throws Exception {
ResolveToolchainsKey.create(
"test",
ImmutableSet.of(
- testToolchainType, Label.parseAbsoluteUnchecked("//fake/toolchain:type_1")),
+ testToolchainTypeLabel, Label.parseAbsoluteUnchecked("//fake/toolchain:type_1")),
targetConfigKey);
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
@@ -219,7 +221,7 @@ public void resolve_unavailableToolchainType_multiple() throws Exception {
ResolveToolchainsKey.create(
"test",
ImmutableSet.of(
- testToolchainType,
+ testToolchainTypeLabel,
Label.parseAbsoluteUnchecked("//fake/toolchain:type_1"),
Label.parseAbsoluteUnchecked("//fake/toolchain:type_2")),
targetConfigKey);
@@ -238,7 +240,8 @@ public void resolve_invalidTargetPlatform_badTarget() throws Exception {
scratch.file("invalid/BUILD", "filegroup(name = 'not_a_platform')");
useConfiguration("--platforms=//invalid:not_a_platform");
ResolveToolchainsKey key =
- ResolveToolchainsKey.create("test", ImmutableSet.of(testToolchainType), targetConfigKey);
+ ResolveToolchainsKey.create(
+ "test", ImmutableSet.of(testToolchainTypeLabel), targetConfigKey);
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
@@ -261,7 +264,8 @@ public void resolve_invalidTargetPlatform_badPackage() throws Exception {
scratch.resolve("invalid").delete();
useConfiguration("--platforms=//invalid:not_a_platform");
ResolveToolchainsKey key =
- ResolveToolchainsKey.create("test", ImmutableSet.of(testToolchainType), targetConfigKey);
+ ResolveToolchainsKey.create(
+ "test", ImmutableSet.of(testToolchainTypeLabel), targetConfigKey);
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
@@ -282,7 +286,8 @@ public void resolve_invalidHostPlatform() throws Exception {
scratch.file("invalid/BUILD", "filegroup(name = 'not_a_platform')");
useConfiguration("--host_platform=//invalid:not_a_platform");
ResolveToolchainsKey key =
- ResolveToolchainsKey.create("test", ImmutableSet.of(testToolchainType), targetConfigKey);
+ ResolveToolchainsKey.create(
+ "test", ImmutableSet.of(testToolchainTypeLabel), targetConfigKey);
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
@@ -303,7 +308,8 @@ public void resolve_invalidExecutionPlatform() throws Exception {
scratch.file("invalid/BUILD", "filegroup(name = 'not_a_platform')");
useConfiguration("--extra_execution_platforms=//invalid:not_a_platform");
ResolveToolchainsKey key =
- ResolveToolchainsKey.create("test", ImmutableSet.of(testToolchainType), targetConfigKey);
+ ResolveToolchainsKey.create(
+ "test", ImmutableSet.of(testToolchainTypeLabel), targetConfigKey);
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
@@ -343,7 +349,7 @@ public void resolve_execConstraints() throws Exception {
ResolveToolchainsKey key =
ResolveToolchainsKey.create(
"test",
- ImmutableSet.of(testToolchainType),
+ ImmutableSet.of(testToolchainTypeLabel),
ImmutableSet.of(Label.parseAbsoluteUnchecked("//constraints:linux")),
targetConfigKey);
@@ -372,7 +378,7 @@ public void resolve_execConstraints_invalid() throws Exception {
ResolveToolchainsKey key =
ResolveToolchainsKey.create(
"test",
- ImmutableSet.of(testToolchainType),
+ ImmutableSet.of(testToolchainTypeLabel),
ImmutableSet.of(Label.parseAbsoluteUnchecked("//platforms:linux")),
targetConfigKey);
@@ -451,7 +457,8 @@ public void unloadedToolchainContext_load() throws Exception {
useConfiguration("--platforms=//platforms:linux");
ResolveToolchainsKey key =
- ResolveToolchainsKey.create("test", ImmutableSet.of(testToolchainType), targetConfigKey);
+ ResolveToolchainsKey.create(
+ "test", ImmutableSet.of(testToolchainTypeLabel), targetConfigKey);
// Create the UnloadedToolchainContext.
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
@@ -479,8 +486,9 @@ public void unloadedToolchainContext_load() throws Exception {
@Test
public void unloadedToolchainContext_load_withTemplateVariables() throws Exception {
// Add new toolchain rule that provides template variables.
- Label variableToolchainType =
+ Label variableToolchainTypeLabel =
Label.parseAbsoluteUnchecked("//variable:variable_toolchain_type");
+ ToolchainTypeInfo variableToolchainType = ToolchainTypeInfo.create(variableToolchainTypeLabel);
scratch.file(
"variable/variable_toolchain_def.bzl",
"def _impl(ctx):",
@@ -512,7 +520,7 @@ public void unloadedToolchainContext_load_withTemplateVariables() throws Excepti
ResolveToolchainsKey key =
ResolveToolchainsKey.create(
- "test", ImmutableSet.of(variableToolchainType), targetConfigKey);
+ "test", ImmutableSet.of(variableToolchainTypeLabel), targetConfigKey);
// Create the UnloadedToolchainContext.
EvaluationResult<ResolveToolchainsValue> result = createToolchainContextBuilder(key);
diff --git a/src/test/java/com/google/devtools/build/lib/rules/platform/ToolchainTestCase.java b/src/test/java/com/google/devtools/build/lib/rules/platform/ToolchainTestCase.java
index 43750e0b3c135b..7349164fe28851 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/platform/ToolchainTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/platform/ToolchainTestCase.java
@@ -23,6 +23,7 @@
import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
import com.google.devtools.build.lib.analysis.platform.DeclaredToolchainInfo;
import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
+import com.google.devtools.build.lib.analysis.platform.ToolchainTypeInfo;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.skyframe.RegisteredToolchainsValue;
@@ -46,7 +47,8 @@ public abstract class ToolchainTestCase extends SkylarkTestCase {
public ConstraintValueInfo linuxConstraint;
public ConstraintValueInfo macConstraint;
- public Label testToolchainType;
+ public Label testToolchainTypeLabel;
+ public ToolchainTypeInfo testToolchainType;
protected static IterableSubject assertToolchainLabels(
RegisteredToolchainsValue registeredToolchainsValue) {
@@ -174,7 +176,8 @@ public void createToolchains() throws Exception {
ImmutableList.of("//constraints:linux"),
"bar");
- testToolchainType = makeLabel("//toolchain:test_toolchain");
+ testToolchainTypeLabel = makeLabel("//toolchain:test_toolchain");
+ testToolchainType = ToolchainTypeInfo.create(testToolchainTypeLabel);
}
protected EvaluationResult<RegisteredToolchainsValue> requestToolchainsFromSkyframe(
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java
index b7aa26e1715527..d1e1c7c1939f1d 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/RegisteredToolchainsFunctionTest.java
@@ -49,7 +49,8 @@ public void testRegisteredToolchains() throws Exception {
assertThat(
value.registeredToolchains().stream()
.filter(
- toolchain -> toolchain.toolchainType().typeLabel().equals(testToolchainType))
+ toolchain ->
+ toolchain.toolchainType().equals(testToolchainType))
.collect(Collectors.toList()))
.hasSize(2);
@@ -57,7 +58,7 @@ public void testRegisteredToolchains() throws Exception {
value.registeredToolchains().stream()
.anyMatch(
toolchain ->
- toolchain.toolchainType().typeLabel().equals(testToolchainType)
+ toolchain.toolchainType().equals(testToolchainType)
&& toolchain.execConstraints().get(setting).equals(linuxConstraint)
&& toolchain.targetConstraints().get(setting).equals(macConstraint)
&& toolchain
@@ -69,7 +70,7 @@ public void testRegisteredToolchains() throws Exception {
value.registeredToolchains().stream()
.anyMatch(
toolchain ->
- toolchain.toolchainType().typeLabel().equals(testToolchainType)
+ toolchain.toolchainType().equals(testToolchainType)
&& toolchain.execConstraints().get(setting).equals(macConstraint)
&& toolchain.targetConstraints().get(setting).equals(linuxConstraint)
&& toolchain
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunctionTest.java
index 70267492bd8728..126224a6377785 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/ToolchainResolutionFunctionTest.java
@@ -89,7 +89,7 @@ private EvaluationResult<ToolchainResolutionValue> invokeToolchainResolution(Sky
public void testResolution_singleExecutionPlatform() throws Exception {
SkyKey key =
ToolchainResolutionValue.key(
- targetConfigKey, testToolchainType, LINUX_CTKEY, ImmutableList.of(MAC_CTKEY));
+ targetConfigKey, testToolchainTypeLabel, LINUX_CTKEY, ImmutableList.of(MAC_CTKEY));
EvaluationResult<ToolchainResolutionValue> result = invokeToolchainResolution(key);
assertThatEvaluationResult(result).hasNoError();
@@ -116,7 +116,7 @@ public void testResolution_multipleExecutionPlatforms() throws Exception {
SkyKey key =
ToolchainResolutionValue.key(
targetConfigKey,
- testToolchainType,
+ testToolchainTypeLabel,
LINUX_CTKEY,
ImmutableList.of(LINUX_CTKEY, MAC_CTKEY));
EvaluationResult<ToolchainResolutionValue> result = invokeToolchainResolution(key);
@@ -139,7 +139,7 @@ public void testResolution_noneFound() throws Exception {
SkyKey key =
ToolchainResolutionValue.key(
- targetConfigKey, testToolchainType, LINUX_CTKEY, ImmutableList.of(MAC_CTKEY));
+ targetConfigKey, testToolchainTypeLabel, LINUX_CTKEY, ImmutableList.of(MAC_CTKEY));
EvaluationResult<ToolchainResolutionValue> result = invokeToolchainResolution(key);
assertThatEvaluationResult(result)
@@ -154,24 +154,30 @@ public void testToolchainResolutionValue_equalsAndHashCode() {
new EqualsTester()
.addEqualityGroup(
ToolchainResolutionValue.create(
+ testToolchainType,
ImmutableMap.of(LINUX_CTKEY, makeLabel("//test:toolchain_impl_1"))),
ToolchainResolutionValue.create(
+ testToolchainType,
ImmutableMap.of(LINUX_CTKEY, makeLabel("//test:toolchain_impl_1"))))
// Different execution platform, same label.
.addEqualityGroup(
ToolchainResolutionValue.create(
+ testToolchainType,
ImmutableMap.of(MAC_CTKEY, makeLabel("//test:toolchain_impl_1"))))
// Same execution platform, different label.
.addEqualityGroup(
ToolchainResolutionValue.create(
+ testToolchainType,
ImmutableMap.of(LINUX_CTKEY, makeLabel("//test:toolchain_impl_2"))))
// Different execution platform, different label.
.addEqualityGroup(
ToolchainResolutionValue.create(
+ testToolchainType,
ImmutableMap.of(MAC_CTKEY, makeLabel("//test:toolchain_impl_2"))))
// Multiple execution platforms.
.addEqualityGroup(
ToolchainResolutionValue.create(
+ testToolchainType,
ImmutableMap.<ConfiguredTargetKey, Label>builder()
.put(LINUX_CTKEY, makeLabel("//test:toolchain_impl_1"))
.put(MAC_CTKEY, makeLabel("//test:toolchain_impl_1"))
| val | train | 2018-11-06T20:30:11 | "2018-11-06T16:36:37Z" | smukherj1 | test |
bazelbuild/bazel/6619_7061 | bazelbuild/bazel | bazelbuild/bazel/6619 | bazelbuild/bazel/7061 | [
"timestamp(timedelta=0.0, similarity=0.916451556493324)"
] | bb3989bfe2f3bc824d4c3cddd044db91d6d19662 | e037f6930224fcdf958563d0ae5732bb86332de6 | [
"cc @lberki ",
"Doc for java_import is also broken:\r\n\r\n0.20.0: https://docs.bazel.build/versions/0.20.0/be/java.html#java_import \r\n\r\njava_import(name, deps, data, compatible_with, constraints, deprecation, distribs, exports, features, jars, licenses, neverlink, proguard_specs, restricted_to, runtime_deps, srcjar, tags, testonly, visibility)\r\n\r\n0.21.0: https://docs.bazel.build/versions/0.21.0/be/java.html#java_import\r\n\r\njava_import(name, deps, data, compatible_with, deprecation, distribs, exports, features, licenses, restricted_to, runtime_deps, tags, testonly, visibility)",
"cc @iirina @buchgr @fweikert ",
"Please fix this, not finding this rule in the documentation cost me a considerable amount of time. :cry: \r\nWriting docs for implemented code is not all that that much work compared to writing the code in the first place.",
"Bisected to https://github.com/bazelbuild/bazel/commit/c1d7672707a4d8898b0cd37b5695804ca047d0b8.\r\n\r\n```\r\njingwen@jingwen:/tmp\r\n$ curl http://localhost:12345/versions/master/be/overview.html | grep java_runtime\r\n % Total % Received % Xferd Average Speed Time Time Time Current\r\n Dload Upload Total Spent Left Speed\r\n 0 0 0 0 0 0 0 0 --:--100 37307 100 37307 0 0 2602k 0 --:--:-- --:--:-- --:--:-- 2802k\r\n```\r\n\r\nAt 1db9e66b3d3666eeed37db286ece0f227c45e47b, the commit before c1d7672707a4d8898b0cd37b5695804ca047d0b8\r\n\r\n```\r\njingwen@jingwen:/tmp\r\n$ curl http://localhost:12345/versions/master/be/overview.html | grep java_runtime\r\n % Total % Received % Xferd Average Speed Time Time Time Current\r\n Dload Upload Total Spent Left Speed\r\n 0 0 0 0 0 0 0 0 --:--100 37666 100 37666 0 0 2627k 0 --:--:- <a href=\" java.html#java_runtime\">\r\n- java_runtime\r\n--:--:-- --:--:-- 2627k\r\n```\r\n",
"cc @cushon ",
"Fix: https://github.com/bazelbuild/bazel/pull/7061"
] | [] | "2019-01-08T22:29:36Z" | [
"type: documentation (cleanup)",
"P1",
"team-Rules-Java"
] | Documentation for certain rules is missing | ### Description of the problem / feature request:
Documentation for certain rules (for example `java_toolchain`) is missing on latest docs.build.bazel.
### Feature requests: what underlying problem are you trying to solve with this feature?
Read the docs.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
https://docs.bazel.build/versions/master/be/java.html
<img width="359" alt="screen shot 2018-11-07 at 1 32 02 pm" src="https://user-images.githubusercontent.com/33242106/48106906-91db3e00-e291-11e8-8eaf-d2b19662cbb5.png">
Note the missing `java_toolchain`, compare with:
https://web.archive.org/web/20181021162843/https://docs.bazel.build/versions/master/be/java.html
<img width="438" alt="screen shot 2018-11-07 at 1 32 10 pm" src="https://user-images.githubusercontent.com/33242106/48106927-a6b7d180-e291-11e8-9b61-5b0cbc64e8e4.png">
The source of the docs still exists on current master, so I don't think it's been removed intentionally: https://github.com/bazelbuild/bazel/blob/91e0bae6143e39f60e9d62e8b61854cbc8d7a4f4/src/main/java/com/google/devtools/build/lib/rules/java/JavaToolchainRule.java#L269 | [
"src/main/java/com/google/devtools/build/lib/BUILD"
] | [
"src/main/java/com/google/devtools/build/lib/BUILD"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/BUILD b/src/main/java/com/google/devtools/build/lib/BUILD
index 72ceb6e411f4b3..d8ca8af2c5dadc 100644
--- a/src/main/java/com/google/devtools/build/lib/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/BUILD
@@ -1385,6 +1385,7 @@ filegroup(
"//src/main/java/com/google/devtools/build/lib/rules/apple/cpp:srcs",
"//src/main/java/com/google/devtools/build/lib/rules/config:srcs",
"//src/main/java/com/google/devtools/build/lib/rules/cpp:srcs",
+ "//src/main/java/com/google/devtools/build/lib/rules/java:srcs",
"//src/main/java/com/google/devtools/build/lib/rules/cpp/proto:srcs",
"//src/main/java/com/google/devtools/build/lib/rules/genquery:srcs",
"//src/main/java/com/google/devtools/build/lib/rules/genrule:srcs",
| null | train | train | 2019-01-08T23:12:32 | "2018-11-07T02:34:18Z" | uri-canva | test |
bazelbuild/bazel/6626_6629 | bazelbuild/bazel | bazelbuild/bazel/6626 | bazelbuild/bazel/6629 | [
"timestamp(timedelta=21022.0, similarity=0.8786289929358719)"
] | 250da1022b34c31d562246a0ca3760a7bde8f07e | 5c84ee1b77c5b12f9a0ce3b0bc4149df5f0ec63a | [
"@laurentlb, is this possibly related to ea4840042b0c087685ab4faffab58ba6906b06f5?",
"Testing locally, the docs render correctly.",
"Actually, no, they just break differently. Still investigating.",
"There are two issues, I think.\r\n\r\n- The HTML is broken. I'm fixing it. With the fix, page should render correctly when testing locally.\r\n- Syntax highlighting is broken on the site since my update. I suspect we need to update Jekyll or Rouge (cc @philwo).",
"Now that 4616fdd0e2f567ae2395803e4404054a79787b22 is in, should I close this, or keep it open and re-assign for the syntax highlighting part?",
"Asking @laurentlb whether to keep this open or not.",
"Note that all multi-line code blocks are also broken currently, on the website itself:\r\nhttps://docs.bazel.build/versions/master/skylark/aspects.html",
"Documentation using multi-line code blocks are severely broken (https://docs.bazel.build/versions/master/android-instrumentation-test.html), I will submit a rollback to use redcarpet first. ",
"The rollback (rollforward?) worked. Closing this for now."
] | [] | "2018-11-07T19:20:32Z" | [
"type: bug",
"type: documentation (cleanup)",
"P1",
"team-Bazel"
] | Broken formatting for packaging rules | See [packaging rules docs](https://docs.bazel.build/versions/master/be/pkg.html#pkg_tar).
Formatting is very broken, tables render correctly but headers do not, italics start and stop at various places.

| [
"tools/build_defs/pkg/README.md"
] | [
"tools/build_defs/pkg/README.md"
] | [] | diff --git a/tools/build_defs/pkg/README.md b/tools/build_defs/pkg/README.md
index b1b962fc42136b..445e38602f82c5 100644
--- a/tools/build_defs/pkg/README.md
+++ b/tools/build_defs/pkg/README.md
@@ -118,7 +118,7 @@ Creates a tar file from a list of inputs.
<code>String, default to 'tar'</code>
<p>
The extension for the resulting tarball. The output
- file will be '<i>name<i>.<i>extension<i>'. This extension
+ file will be '<i>name</i>.<i>extension</i>'. This extension
also decide on the compression: if set to <code>tar.gz</code>
or <code>tgz</code> then gzip compression will be used and
if set to <code>tar.bz2</code> or <code>tar.bzip2</code> then
@@ -284,7 +284,6 @@ Creates a tar file from a list of inputs.
</td>
</tr>
</tbody>
- </tbody>
</table>
<a name="pkg_deb"></a>
@@ -448,7 +447,6 @@ for more details on this.
</td>
</tr>
</tbody>
- </tbody>
</table>
<a name="pkg_rpm"></a>
@@ -517,5 +515,4 @@ for more details on this.
</td>
</tr>
</tbody>
- </tbody>
</table>
| null | val | train | 2018-11-07T20:18:09 | "2018-11-07T18:36:12Z" | katre | test |
bazelbuild/bazel/6685_7023 | bazelbuild/bazel | bazelbuild/bazel/6685 | bazelbuild/bazel/7023 | [
"timestamp(timedelta=0.0, similarity=0.8540919667945694)"
] | 40d1dc94dbd1c86acda8d0632445da1a42054506 | 08f53c26313d2eeca0617072b87af6aa9f0de749 | [
"I also had this issue with Chrome. I have no idea why this error exists but you could just add in a DisplayName with the registry editor. I went into regedit to: `Computer\\HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Google Chrome` and added in a new `String Value` and called it \"DisplayName\". That appears to silence the error.\r\n\r\nFor the sake of having logs, here's my log output with a similar error message for the DisplayName:\r\n\r\n```\r\nD:\\src>bazel version\r\nERROR: Failed to query DisplayName of HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Google Chrome\r\nWARNING: --batch mode is deprecated. Please instead explicitly shut down your Bazel server using the command \"bazel shutdown\".\r\nINFO: Invocation ID: ee818f56-b420-4910-a9fe-b54b73650abe\r\nBuild label: 0.20.0\r\nBuild target: bazel-out/x64_windows-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar\r\nBuild time: Fri Nov 30 14:38:51 2018 (1543588731)\r\nBuild timestamp: 1543588731\r\nBuild timestamp as int: 1543588731\r\n\r\n```",
"Thanks @cnishina ! If I'm not mistaken the error is non-fatal. Is that correct?\r\nI'll fix the code not to show even the error. Bazel should just acknowledge that it can't read some registry key and carry on silently.\r\n\r\n(And for the record, that warning about \"--batch mode\" is also benign, it just indicates that you are not running Bazel from a workspace, i.e. `d:\\src` directory has no WORKSPACE file in it, nor do any of its parent directories.)",
"That is correct, it is not a fatal error. I just commented on how I resolved the registry problem."
] | [] | "2019-01-02T12:37:00Z" | [
"type: bug",
"P3",
"area-Windows",
"team-OSS"
] | Windows: "Failed to query DisplayName of" in Bazel client | ### Description of the problem / feature request:
Bazel displays:
```
ERROR: Failed to query DisplayName of HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\Free mp3 Wma Converter
```
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
https://stackoverflow.com/q/53307267/7778502
Culprit seems to be an unhandled error opening a registry subkey here:
https://github.com/bazelbuild/bazel/blob/cd2a036ffff99087be125253157d16d60289e33a/src/main/cpp/blaze_util_windows.cc#L1359
### What operating system are you running Bazel on?
Windows
### What's the output of `bazel info release`?
```
Build label: 0.18.0- (@non-git)
Build target: bazel-out/x64_windows-opt/bin/src/main/java/com/google/devtools/bu ild/lib/bazel/BazelServer_deploy.jar
Build time: Sun Oct 28 04:25:08 2018 (1540700708)
Build timestamp: 1540700708
Build timestamp as int: 1540700708
``` | [
"src/main/cpp/blaze_util_windows.cc"
] | [
"src/main/cpp/blaze_util_windows.cc"
] | [] | diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc
index 1483dfb9b76a22..a8ccacba1096e9 100644
--- a/src/main/cpp/blaze_util_windows.cc
+++ b/src/main/cpp/blaze_util_windows.cc
@@ -1358,9 +1358,9 @@ static string GetMsysBash() {
value, // _Out_opt_ LPBYTE lpData,
&value_length // _Inout_opt_ LPDWORD lpcbData
)) {
- BAZEL_LOG(ERROR) << "Failed to query DisplayName of HKCU\\" << key << "\\"
- << subkey_name;
- continue; // try next subkey
+ // This registry key has no DisplayName subkey, so it cannot be MSYS2, or
+ // it cannot be a version of MSYS2 that we are looking for.
+ continue;
}
if (value_type == REG_SZ &&
@@ -1378,16 +1378,17 @@ static string GetMsysBash() {
path, // _Out_opt_ LPBYTE lpData,
&path_length // _Inout_opt_ LPDWORD lpcbData
)) {
- BAZEL_LOG(ERROR) << "Failed to query InstallLocation of HKCU\\" << key
- << "\\" << subkey_name;
+ // This version of MSYS2 does not seem to create a "InstallLocation"
+ // subkey. Let's ignore this registry key to avoid picking up an MSYS2
+ // version that may be different from what Bazel expects.
continue; // try next subkey
}
if (path_length == 0 || path_type != REG_SZ) {
- BAZEL_LOG(ERROR) << "Zero-length (" << path_length
- << ") install location or wrong type (" << path_type
- << ")";
- continue; // try next subkey
+ // This version of MSYS2 seem to have recorded an empty installation
+ // location, or the registry key was modified. Either way, let's ignore
+ // this registry key and keep looking at the next subkey.
+ continue;
}
BAZEL_LOG(INFO) << "Install location of HKCU\\" << key << "\\"
@@ -1395,11 +1396,13 @@ static string GetMsysBash() {
string path_as_string(path, path + path_length - 1);
string bash_exe = path_as_string + "\\usr\\bin\\bash.exe";
if (!blaze_util::PathExists(bash_exe)) {
- BAZEL_LOG(INFO) << bash_exe.c_str() << " does not exist";
- continue; // try next subkey
+ // The supposed bash.exe does not exist. Maybe MSYS2 was deleted but not
+ // uninstalled? We can't tell, but for all we care, this MSYS2 path is
+ // not what we need, so ignore this registry key.
+ continue;
}
- BAZEL_LOG(INFO) << "Detected msys bash at " << bash_exe.c_str();
+ BAZEL_LOG(INFO) << "Detected MSYS2 Bash at " << bash_exe.c_str();
return bash_exe;
}
}
| null | val | train | 2019-01-02T10:47:59 | "2018-11-15T11:15:56Z" | laszlocsomor | test |
bazelbuild/bazel/6769_6774 | bazelbuild/bazel | bazelbuild/bazel/6769 | bazelbuild/bazel/6774 | [
"timestamp(timedelta=0.0, similarity=0.8694351320346887)"
] | 453edb5e876659cbb3b978bd0fbe0ed20f1be5b7 | 2583f1f288fe73a8105c4af7acd321a1fe3a0964 | [] | [
"This accesses the same information via a provider rather than via attribute (deprecated way to do that?).\r\nDocumentation says `default_runfiles` may return `None` so I've added a check.\r\nhttps://docs.bazel.build/versions/master/skylark/lib/DefaultInfo.html#default_runfiles",
"Attribute `files_map` does not exist",
"It seems there is no need to wrap the invocation in shell?",
"These are default values",
"Executable file is a single file",
"This is the default"
] | "2018-11-27T12:03:57Z" | [
"team-Rules-Server",
"untriaged"
] | pkg_tar duplicate files with include_runfiles=True | ### Description of the problem / feature request:
I'd like to use pkg_tar and have it package runfiles for my targets. I tried using the undocumented (should be documented?) flag `include_runfiles` but it turns out the implementation (https://github.com/bazelbuild/bazel/pull/5044) is buggy and it includes runfiles twice. Perhaps it should be building a depset and then turning it into a list to pass to the underlying tool.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Declare an `sh_binary(data = ["some_file"])` with a data dependency and then try to use `pkg_tar` to tar it with `include_runfiles=True`.
### What operating system are you running Bazel on?
macOS
### What's the output of `bazel info release`?
`release 0.19.2`
### Any other information, logs, or outputs that you want to share?
I can see that `bazel-bin/<path>/<target name>.args` contains duplicate `--file=` lines. | [
"tools/build_defs/pkg/pkg.bzl"
] | [
"tools/build_defs/pkg/pkg.bzl"
] | [] | diff --git a/tools/build_defs/pkg/pkg.bzl b/tools/build_defs/pkg/pkg.bzl
index 7c98838e69745a..d3bd88517be8f5 100644
--- a/tools/build_defs/pkg/pkg.bzl
+++ b/tools/build_defs/pkg/pkg.bzl
@@ -40,7 +40,6 @@ def _pkg_tar_impl(ctx):
remap_paths = ctx.attr.remap_paths
# Start building the arguments.
- build_tar = ctx.executable.build_tar
args = [
"--output=" + ctx.outputs.out.path,
"--directory=" + ctx.attr.package_dir,
@@ -49,14 +48,19 @@ def _pkg_tar_impl(ctx):
"--owner_name=" + ctx.attr.ownername,
]
- file_inputs = ctx.files.srcs[:]
-
# Add runfiles if requested
+ file_inputs = []
if ctx.attr.include_runfiles:
+ runfiles_depsets = []
for f in ctx.attr.srcs:
- if hasattr(f, "default_runfiles"):
- run_files = f.default_runfiles.files.to_list()
- file_inputs += run_files
+ default_runfiles = f[DefaultInfo].default_runfiles
+ if default_runfiles != None:
+ runfiles_depsets.append(default_runfiles.files)
+
+ # deduplicates files in srcs attribute and their runfiles
+ file_inputs = depset(ctx.files.srcs, transitive = runfiles_depsets).to_list()
+ else:
+ file_inputs = ctx.files.srcs[:]
args += [
"--file=%s=%s" % (_quote(f.path), _remap(remap_paths, dest_path(f, data_path)))
@@ -65,8 +69,8 @@ def _pkg_tar_impl(ctx):
for target, f_dest_path in ctx.attr.files.items():
target_files = target.files.to_list()
if len(target_files) != 1:
- fail("Inputs to pkg_tar.files_map must describe exactly one file.")
- file_inputs += [target_files[0]]
+ fail("Each input must describe exactly one file.", attr = "files")
+ file_inputs += target_files
args += ["--file=%s=%s" % (_quote(target_files[0].path), f_dest_path)]
if ctx.attr.modes:
args += [
@@ -100,10 +104,10 @@ def _pkg_tar_impl(ctx):
arg_file = ctx.actions.declare_file(ctx.label.name + ".args")
ctx.actions.write(arg_file, "\n".join(args))
- ctx.actions.run_shell(
- command = "%s --flagfile=%s" % (build_tar.path, arg_file.path),
+ ctx.actions.run(
inputs = file_inputs + ctx.files.deps + [arg_file],
- tools = [build_tar],
+ executable = ctx.executable.build_tar,
+ arguments = ["--flagfile", arg_file.path],
outputs = [ctx.outputs.out],
mnemonic = "PackageTar",
use_default_shell_env = True,
@@ -219,7 +223,7 @@ _real_pkg_tar = rule(
"extension": attr.string(default = "tar"),
"symlinks": attr.string_dict(),
"empty_files": attr.string_list(),
- "include_runfiles": attr.bool(default = False, mandatory = False),
+ "include_runfiles": attr.bool(),
"empty_dirs": attr.string_list(),
"remap_paths": attr.string_dict(),
# Implicit dependencies.
@@ -233,7 +237,6 @@ _real_pkg_tar = rule(
outputs = {
"out": "%{name}.%{extension}",
},
- executable = False,
)
def pkg_tar(**kwargs):
@@ -293,5 +296,4 @@ pkg_deb = rule(
"deb": "%{package}_%{version}_%{architecture}.deb",
"changes": "%{package}_%{version}_%{architecture}.changes",
},
- executable = False,
)
| null | train | train | 2018-12-03T22:05:34 | "2018-11-27T03:44:43Z" | ash2k | test |
bazelbuild/bazel/6820_6822 | bazelbuild/bazel | bazelbuild/bazel/6820 | bazelbuild/bazel/6822 | [
"timestamp(timedelta=0.0, similarity=0.8793758775672843)"
] | 7fc967c4d6435de2bb4e34aac00ca2e499f55fca | f63b0e158101e7414bbfa740b7d41a7c8a668827 | [
"Thanks for the report!\r\n\r\nThe error comes from here:\r\nhttps://github.com/bazelbuild/bazel/blob/7fc967c4d6435de2bb4e34aac00ca2e499f55fca/src/tools/singlejar/mapped_file_windows.inc#L66\r\n\r\nThe caller is here:\r\nhttps://github.com/bazelbuild/bazel/blob/7fc967c4d6435de2bb4e34aac00ca2e499f55fca/src/tools/singlejar/output_jar.cc#L909\r\n\r\nThe comment above the failing line in `mapped_file_windows.inc` explains that empty files are not supported. I think the caller should handle empty files instead of attempting to map them.\r\n\r\nI'll try to fix this."
] | [] | "2018-12-03T11:41:03Z" | [
"type: bug",
"P2",
"platform: windows",
"area-Windows",
"team-OSS"
] | C++ SingleJar on Windows can't deal with empty files | > ATTENTION! Please read and follow:
> - if this is a _question_ about how to build / test / query / deploy using Bazel, ask it on StackOverflow instead: https://stackoverflow.com/questions/tagged/bazel
> - if this is a _discussion starter_, send it to [email protected]
> - if this is a _bug_ or _feature request_, fill the form below as best as you can.
### Description of the problem / feature request:
It seems like C++ SingleJar on Windows crashes when it encounters an empty file as an input:
```
WARNING: C:\users\philwo\_bazel_philwo\i3dsexk6\execroot\io_bazel\src/tools/singlejar/mapped_file_windows.inc:66: Windows MappedFile cannot handle empty file (bazel-out/x64_windows-fastbuild/genfiles/src/main/java/com/google/devtools/build/lib/runtime/commands/LICENSE)
ERROR: src/tools/singlejar/output_jar.cc:922: bazel-out/x64_windows-fastbuild/genfiles/src/main/java/com/google/devtools/build/lib/runtime/commands/LICENSE
Target //src:bazel.exe failed to build
```
You can easily repro this by changing this line:
https://source.bazel.build/bazel/+/cb9b2afbba3f8d3a1db8bf68e65d06f1b36902f5:src/main/java/com/google/devtools/build/lib/BUILD;l=1273
to just
```
cmd = "touch \"$@\"",
```
and then build Bazel as usual:
```
bazel build //src:bazel.exe
```
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
I can repro this at Bazel HEAD
| [
"src/tools/singlejar/mapped_file_windows.inc",
"src/tools/singlejar/output_jar_shell_test.sh"
] | [
"src/tools/singlejar/mapped_file_windows.inc",
"src/tools/singlejar/output_jar_shell_test.sh"
] | [] | diff --git a/src/tools/singlejar/mapped_file_windows.inc b/src/tools/singlejar/mapped_file_windows.inc
index 43e524ae12302a..a35702874baffa 100644
--- a/src/tools/singlejar/mapped_file_windows.inc
+++ b/src/tools/singlejar/mapped_file_windows.inc
@@ -50,8 +50,7 @@ bool MappedFile::Open(const std::string& path) {
size_t fileSize = temp.QuadPart;
if (fileSize == 0) {
- // This is where Windows implementation differs from POSIX's.
- // CreateFileMapping cannot map empty file:
+ // Handle empty files specially, because CreateFileMapping cannot map them:
//
// From
// https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-createfilemappinga
@@ -59,14 +58,10 @@ bool MappedFile::Open(const std::string& path) {
// An attempt to map a file with a length of 0 (zero) fails with an error
// code of ERROR_FILE_INVALID. Applications should test for files with a
// length of 0 (zero) and reject those files.
- //
- // Since the test at //src/tools/singlerjar/input_jar_bad_jar_test expects
- // empty file to fail anyway, returning error here shouldn't be a problem.
- diag_warn("%s:%d: Windows MappedFile cannot handle empty file (%s)",
- __FILE__, __LINE__, path.c_str());
- _close(fd_);
- fd_ = -1;
- return false;
+ mapped_start_ = nullptr;
+ mapped_end_ = nullptr;
+ hMapFile_ = INVALID_HANDLE_VALUE;
+ return true;
}
hMapFile_ = ::CreateFileMapping(
@@ -107,13 +102,17 @@ bool MappedFile::Open(const std::string& path) {
void MappedFile::Close() {
if (is_open()) {
- ::UnmapViewOfFile(mapped_start_);
- ::CloseHandle(hMapFile_);
+ if (mapped_start_) {
+ ::UnmapViewOfFile(mapped_start_);
+ }
+ if (hMapFile_ != INVALID_HANDLE_VALUE) {
+ ::CloseHandle(hMapFile_);
+ hMapFile_ = INVALID_HANDLE_VALUE;
+ }
_close(fd_);
- hMapFile_ = INVALID_HANDLE_VALUE;
fd_ = -1;
mapped_start_ = mapped_end_ = nullptr;
}
}
-#endif // BAZEL_SRC_TOOLS_SINGLEJAR_MAPPED_FILE_WINDOWS_H_
\ No newline at end of file
+#endif // BAZEL_SRC_TOOLS_SINGLEJAR_MAPPED_FILE_WINDOWS_H_
diff --git a/src/tools/singlejar/output_jar_shell_test.sh b/src/tools/singlejar/output_jar_shell_test.sh
index 961dc10181cd00..9ce549774e72ad 100755
--- a/src/tools/singlejar/output_jar_shell_test.sh
+++ b/src/tools/singlejar/output_jar_shell_test.sh
@@ -66,6 +66,14 @@ function test_new_entries() {
{ echo "build-data.properties is not readable" >&2; exit 1; }
}
+# Regression test https://github.com/bazelbuild/bazel/issues/6820
+function test_empty_resource_file() {
+ local -r out_jar="${TEST_TMPDIR}/out.jar"
+ local -r empty="${TEST_TMPDIR}/empty"
+ echo -n > "$empty"
+ "$singlejar" --output "$out_jar" --resources $empty
+}
+
run_suite "Misc shell tests"
#!/bin/bash
| null | train | train | 2018-12-03T11:12:38 | "2018-12-03T10:36:35Z" | philwo | test |
bazelbuild/bazel/6949_6967 | bazelbuild/bazel | bazelbuild/bazel/6949 | bazelbuild/bazel/6967 | [
"timestamp(timedelta=169092.0, similarity=0.8650940885209347)"
] | d0e6e06be3adbf625b065b787db2053e630be5f1 | 86b8204af1ecfb84994e34f97e40cc9715c2c510 | [
"Closing this as a dupe of https://github.com/bazelbuild/bazel/issues/1707"
] | [] | "2018-12-19T16:53:27Z" | [
"type: documentation (cleanup)",
"P2",
"team-Bazel"
] | Document the build processes of the Bazel websites | This impacts {www, docs, blog}.bazel.build.
The three web assets share a significant part of their build processes. These processes are lightly documented in the [READMEs](https://github.com/bazelbuild/bazel-website#bazel-website) or in code themselves.
It would be useful to document how the Bazel web assets are built and deployed, and identify areas where we can decouple and reuse commonly shared libraries, like CSS, JS, and header/footer/layout includes. | [
"scripts/docs/doc_versions.bzl",
"site/_config.yml"
] | [
"scripts/docs/doc_versions.bzl",
"site/_config.yml"
] | [] | diff --git a/scripts/docs/doc_versions.bzl b/scripts/docs/doc_versions.bzl
index 4e4b76a5ffc52e..09f2c80aacfdd9 100644
--- a/scripts/docs/doc_versions.bzl
+++ b/scripts/docs/doc_versions.bzl
@@ -22,6 +22,10 @@
"""This module contains the versions and hashes of Bazel's documentation tarballs."""
DOC_VERSIONS = [
+ {
+ "version": "0.21.0",
+ "sha256": "23ec39c0138d358c544151e5c81586716d5d1c6124f10a742bead70516e6eb93",
+ },
{
"version": "0.20.0",
"sha256": "bb79a63810bf1b0aa1f89bd3bbbeb4a547a30ab9af70c9be656cc6866f4b015b",
diff --git a/site/_config.yml b/site/_config.yml
index 00f82998f49c69..9e82fe02e149d8 100644
--- a/site/_config.yml
+++ b/site/_config.yml
@@ -15,6 +15,7 @@ version: "master"
# This must be kept in sync with //site/script/docs:versions.bzl
doc_versions:
- master
+ - 0.21.0
- 0.20.0
- 0.19.2
- 0.19.1
| null | test | train | 2018-12-19T17:29:59 | "2018-12-17T18:12:21Z" | jin | test |
bazelbuild/bazel/6988_8935 | bazelbuild/bazel | bazelbuild/bazel/6988 | bazelbuild/bazel/8935 | [
"timestamp(timedelta=0.0, similarity=0.840598533354835)"
] | 46fb33c1ce3b4526611882e7b266f141fe3a4efd | fd4403830e2d6f300c71e53fb6558d340db1a917 | [] | [] | "2019-07-19T10:11:52Z" | [
"type: documentation (cleanup)",
"P3"
] | Starlark language docs link to list instead of tuple | On https://docs.bazel.build/versions/master/skylark/lib/string.html#endswith the link to "tuple" in "tuple of strings" actually points at the list documentation. Which then gave me a syntax error because I needed the "tuple" syntax with parentheses instead of square brackets. I'm also not sure where this documentation lives in Github... presumably it's autogenerated, and therefore this problem might affect other documentation pages? | [
"src/main/java/com/google/devtools/build/docgen/skylark/SkylarkDoc.java"
] | [
"src/main/java/com/google/devtools/build/docgen/skylark/SkylarkDoc.java"
] | [
"src/test/java/com/google/devtools/build/docgen/SkylarkDocumentationTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/docgen/skylark/SkylarkDoc.java b/src/main/java/com/google/devtools/build/docgen/skylark/SkylarkDoc.java
index 95f740e002ee79..f2a38819fa84d0 100644
--- a/src/main/java/com/google/devtools/build/docgen/skylark/SkylarkDoc.java
+++ b/src/main/java/com/google/devtools/build/docgen/skylark/SkylarkDoc.java
@@ -61,7 +61,7 @@ protected String getTypeAnchor(Class<?> type) {
} else if (Map.class.isAssignableFrom(type)) {
return "<a class=\"anchor\" href=\"dict.html\">dict</a>";
} else if (type.equals(Tuple.class)) {
- return "<a class=\"anchor\" href=\"list.html\">tuple</a>";
+ return "<a class=\"anchor\" href=\"tuple.html\">tuple</a>";
} else if (type.equals(MutableList.class) || type.equals(ImmutableList.class)) {
return "<a class=\"anchor\" href=\"list.html\">list</a>";
} else if (type.equals(SkylarkList.class)) {
| diff --git a/src/test/java/com/google/devtools/build/docgen/SkylarkDocumentationTest.java b/src/test/java/com/google/devtools/build/docgen/SkylarkDocumentationTest.java
index 07c684f73d714c..7796c5d8cbdb23 100644
--- a/src/test/java/com/google/devtools/build/docgen/SkylarkDocumentationTest.java
+++ b/src/test/java/com/google/devtools/build/docgen/SkylarkDocumentationTest.java
@@ -442,7 +442,7 @@ public void testSkylarkContainerReturnTypesWithoutAnnotations() throws Exception
+ "MockClassWithContainerReturnValues.depset()");
assertThat(signatures)
.contains(
- "<a class=\"anchor\" href=\"list.html\">tuple</a> "
+ "<a class=\"anchor\" href=\"tuple.html\">tuple</a> "
+ "MockClassWithContainerReturnValues.tuple()");
assertThat(signatures)
.contains(
| test | train | 2019-07-19T12:25:23 | "2018-12-21T17:34:28Z" | LStAmour | test |
bazelbuild/bazel/7063_7076 | bazelbuild/bazel | bazelbuild/bazel/7063 | bazelbuild/bazel/7076 | [
"timestamp(timedelta=0.0, similarity=0.8635947801373915)"
] | 94e50162088bd788c9f4e18f9a1a79987398b213 | 0665cf2589c2285c5f3243376017b572ca1ee8c8 | [
"Workaround: call `bazel shutdown` then `bazel run //src:foo` again.",
"I bet this is some symlink-related issue. I suspect Bazel on Windows copies files in the roots of external repositories instead of symlinking them, and that's why it doesn't notice the change.\r\n\r\nI'll proceed to check this theory.",
"My theory is correct:\r\n- moving `gen_cc.bzl` to a subdirectory `sub` in under `repo1` will result in correct behavior, because `<output_base>/external/repo1/sub` is a junction pointing to the real `sub` directory\r\n- adding a file to or removing a file from the root of repo1 between builds is picked up, but modifying a file is not; to see this, check the contents of `<output_base>/external/repo1`\r\n- changing `new_local_repository` to `local_repository` and adding a BUILD file to `repo1` will result in correct behavior, even when the bzl file is in repo1's root; therefore this is a bug with `new_local_repository`, ~and this bug might actually be a duplicate of #3908~",
"Could be the same bug as https://github.com/bazelbuild/bazel/issues/6351"
] | [] | "2019-01-10T12:02:09Z" | [
"type: bug",
"P1",
"area-Windows",
"team-OSS"
] | Windows, external repositories: correctness bug with Starlark rule in external repo | ### Description of the problem / feature request:
On Windows, if `//src:foo` depends on `@repo2//:gen`, which is a Starlark rule whose definition is in `@repo1//:gen_cc.bzl`, then changing `gen_cc.bzl` does not trigger a rebuild of `//src:foo` even though it should.
On Linux, the same thing works correctly.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
https://github.com/laszlocsomor/projects/tree/81325c41c015dfe02d7639ab8940f52d72da8093/bazel/starlark-rule-change-no-picked-up-from-repo
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
`release 0.21.0` | [
"src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryDirectoryValue.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryFunction.java",
"src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryDirectoryValue.java"
] | [
"src/test/py/bazel/bazel_external_repository_test.py"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryFunction.java b/src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryFunction.java
index 5c164c7d807ddc..9c4c4aa3c325ce 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryFunction.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/repository/NewLocalRepositoryFunction.java
@@ -15,6 +15,7 @@
package com.google.devtools.build.lib.rules.repository;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.FileValue;
import com.google.devtools.build.lib.actions.InconsistentFilesystemException;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
@@ -24,6 +25,7 @@
import com.google.devtools.build.lib.skyframe.DirectoryListingValue;
import com.google.devtools.build.lib.syntax.Printer;
import com.google.devtools.build.lib.vfs.FileSystem;
+import com.google.devtools.build.lib.vfs.Dirent;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
@@ -32,6 +34,7 @@
import com.google.devtools.build.skyframe.SkyFunctionException;
import com.google.devtools.build.skyframe.SkyFunctionException.Transience;
import com.google.devtools.build.skyframe.SkyKey;
+import com.google.devtools.build.skyframe.SkyValue;
import java.io.IOException;
import java.util.Map;
@@ -90,10 +93,19 @@ public RepositoryDirectoryValue.Builder fetch(Rule rule, Path outputDirectory,
throw new RepositoryFunctionException(e, Transience.PERSISTENT);
}
- // fetch() creates symlinks to each child under 'path' and DiffAwareness handles checking all
- // of these files and directories for changes. However, if a new file/directory is added
- // directly under 'path', Bazel doesn't know that this has to be symlinked in. Thus, this
- // creates a dependency on the contents of the 'path' directory.
+ // fetch() creates symlinks to each child under 'path'.
+ //
+ // On Linux/macOS (i.e. where file symlinks are supported), DiffAwareness handles checking all
+ // of these files and directories for changes.
+ //
+ // On Windows (when file symlinks are disabled), the supposed symlinks are actually copies and
+ // DiffAwareness doesn't pick up changes of the "symlink" targets. To rectify that, we request
+ // FileValues for each child of 'path'.
+ // See https://github.com/bazelbuild/bazel/issues/7063
+ //
+ // Furthermore, if a new file/directory is added directly under 'path', Bazel doesn't know that
+ // this has to be symlinked in. So we also create a dependency on the contents of the 'path'
+ // directory.
SkyKey dirKey = DirectoryListingValue.key(dirPath);
DirectoryListingValue directoryValue;
try {
@@ -106,6 +118,20 @@ public RepositoryDirectoryValue.Builder fetch(Rule rule, Path outputDirectory,
return null;
}
+ Map<SkyKey, SkyValue> fileValues =
+ env.getValues(
+ Iterables.transform(
+ directoryValue.getDirents(),
+ e -> (SkyKey) FileValue.key(
+ RootedPath.toRootedPath(
+ dirPath.getRoot(),
+ dirPath.getRootRelativePath().getRelative(e.getName())))));
+ for (Map.Entry<?, ?> m : fileValues.entrySet()) {
+ if (m.getValue() == null) {
+ return null;
+ }
+ }
+
// Link x/y/z to /some/path/to/y/z.
if (!symlinkLocalRepositoryContents(outputDirectory, path)) {
return null;
@@ -114,7 +140,8 @@ public RepositoryDirectoryValue.Builder fetch(Rule rule, Path outputDirectory,
fileHandler.finishFile(rule, outputDirectory, markerData);
env.getListener().post(resolve(rule, directories));
- return RepositoryDirectoryValue.builder().setPath(outputDirectory).setSourceDir(directoryValue);
+ return RepositoryDirectoryValue.builder().setPath(outputDirectory).setSourceDir(directoryValue)
+ .setFileValues(fileValues);
}
@Override
diff --git a/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryDirectoryValue.java b/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryDirectoryValue.java
index c2ce139864e83c..68323a517e57e1 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryDirectoryValue.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/repository/RepositoryDirectoryValue.java
@@ -17,6 +17,7 @@
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Interner;
+import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.concurrent.BlazeInterners;
import com.google.devtools.build.lib.skyframe.DirectoryListingValue;
@@ -25,8 +26,10 @@
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.skyframe.AbstractSkyKey;
import com.google.devtools.build.skyframe.SkyFunctionName;
+import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import java.util.Arrays;
+import java.util.Map;
import javax.annotation.Nullable;
/** A local view of an external repository. */
@@ -53,13 +56,16 @@ public static final class SuccessfulRepositoryDirectoryValue extends RepositoryD
private final boolean fetchingDelayed;
@Nullable private final byte[] digest;
@Nullable private final DirectoryListingValue sourceDir;
+ private final ImmutableMap<SkyKey, SkyValue> fileValues;
private SuccessfulRepositoryDirectoryValue(
- Path path, boolean fetchingDelayed, DirectoryListingValue sourceDir, byte[] digest) {
+ Path path, boolean fetchingDelayed, DirectoryListingValue sourceDir, byte[] digest,
+ ImmutableMap<SkyKey, SkyValue> fileValues) {
this.path = path;
this.fetchingDelayed = fetchingDelayed;
this.sourceDir = sourceDir;
this.digest = digest;
+ this.fileValues = fileValues;
}
@Override
@@ -87,14 +93,15 @@ public boolean equals(Object other) {
SuccessfulRepositoryDirectoryValue otherValue = (SuccessfulRepositoryDirectoryValue) other;
return Objects.equal(path, otherValue.path)
&& Objects.equal(sourceDir, otherValue.sourceDir)
- && Arrays.equals(digest, otherValue.digest);
+ && Arrays.equals(digest, otherValue.digest)
+ && Objects.equal(fileValues, otherValue.fileValues);
}
return false;
}
@Override
public int hashCode() {
- return Objects.hashCode(path, sourceDir, Arrays.hashCode(digest));
+ return Objects.hashCode(path, sourceDir, Arrays.hashCode(digest), fileValues);
}
@Override
@@ -162,6 +169,7 @@ public static class Builder {
private boolean fetchingDelayed = false;
private byte[] digest = null;
private DirectoryListingValue sourceDir = null;
+ private Map<SkyKey, SkyValue> fileValues = ImmutableMap.of();
private Builder() {}
@@ -185,13 +193,19 @@ public Builder setSourceDir(DirectoryListingValue sourceDir) {
return this;
}
+ public Builder setFileValues(Map<SkyKey, SkyValue> fileValues) {
+ this.fileValues = fileValues;
+ return this;
+ }
+
public SuccessfulRepositoryDirectoryValue build() {
Preconditions.checkNotNull(path, "Repository path must be specified!");
// Only if fetching is delayed then we are allowed to have a null digest.
if (!this.fetchingDelayed) {
Preconditions.checkNotNull(digest, "Repository marker digest must be specified!");
}
- return new SuccessfulRepositoryDirectoryValue(path, fetchingDelayed, sourceDir, digest);
+ return new SuccessfulRepositoryDirectoryValue(path, fetchingDelayed, sourceDir, digest,
+ ImmutableMap.copyOf(fileValues));
}
}
}
| diff --git a/src/test/py/bazel/bazel_external_repository_test.py b/src/test/py/bazel/bazel_external_repository_test.py
index 3ed67f9b264802..2950ade954ea82 100644
--- a/src/test/py/bazel/bazel_external_repository_test.py
+++ b/src/test/py/bazel/bazel_external_repository_test.py
@@ -131,5 +131,50 @@ def testNewHttpArchiveWithSymlinks(self):
])
self.assertEqual(exit_code, 0, os.linesep.join(stderr))
+ def _CreatePyWritingStarlarkRule(self, print_string):
+ self.ScratchFile('repo/foo.bzl', [
+ "def _impl(ctx):",
+ " ctx.actions.write(",
+ " output = ctx.outputs.out,",
+ " content = \"\"\"from __future__ import print_function",
+ "print('%s')\"\"\"," % print_string,
+ " )",
+ " return [DefaultInfo(files = depset(direct = [ctx.outputs.out]))]",
+ "",
+ "gen_py = rule(",
+ " implementation = _impl,",
+ " outputs = {'out': '%{name}.py'},",
+ ")",
+ ])
+
+ def testNewLocalRepositoryNoticesFileChangeInRepoRoot(self):
+ """Regression test for https://github.com/bazelbuild/bazel/issues/7063."""
+ self.ScratchFile('WORKSPACE', [
+ 'new_local_repository(',
+ ' name = "r",',
+ ' path = "./repo",',
+ ' build_file_content = "exports_files([\'foo.bzl\'])",',
+ ')',
+ ])
+ self.ScratchFile('repo/WORKSPACE')
+ self._CreatePyWritingStarlarkRule('hello!')
+ self.ScratchFile('BUILD', [
+ 'load("@r//:foo.bzl", "gen_py")',
+ 'gen_py(name = "gen")',
+ 'py_binary(name = "bin", srcs = [":gen"], main = "gen.py")',
+ ])
+
+ exit_code, stdout, stderr = self.RunBazel(['run', '//:bin'])
+ self.assertEqual(exit_code, 0, os.linesep.join(stderr))
+ self.assertIn('hello!', os.linesep.join(stdout))
+
+ # Modify the definition of the Starlark rule in the external repository.
+ # The py_binary rule should notice this and rebuild.
+ self._CreatePyWritingStarlarkRule('world')
+ exit_code, stdout, stderr = self.RunBazel(['run', '//:bin'])
+ self.assertEqual(exit_code, 0, os.linesep.join(stderr))
+ self.assertNotIn('hello!', os.linesep.join(stdout))
+ self.assertIn('world', os.linesep.join(stdout))
+
if __name__ == '__main__':
unittest.main()
| train | train | 2019-01-10T12:28:06 | "2019-01-09T08:32:10Z" | laszlocsomor | test |
bazelbuild/bazel/7079_7185 | bazelbuild/bazel | bazelbuild/bazel/7079 | bazelbuild/bazel/7185 | [
"timestamp(timedelta=0.0, similarity=0.8615181094211928)"
] | 94078453f8f13a124e72d18093a5518ddc9fe9b3 | 4b24ab520d92b5b36d8b801201d16a8fcdd5d559 | [
"/sub",
"Debugging so far (by running tests in parallel and debugging linux vs windows:\r\nThe location of the bazel_tools repo is different in the Windows tests: on Linux it is (correctly) bazel_tools_workspace (set via /workspace/WORKSPACE). On windows, the default value from /DEFAULT.WORKSPACE (which is /usr/local/.../embedded_tools) is being used.\r\n\r\nI can see that on Windows, the Package.Builder is seeing both versions of the rule added, but for some reason in this test the /workspace/WORKSPACE version isn't overwriting.\r\n\r\nMore debugging to come.",
"Wow, that was painful.\r\n\r\nSource of the issue: the test sets OS to LINUX for purposes of the test, but the in-memory-filesystem checks the current value of OS to decide about things like drive strings and whether or not the filesystem is case-insensitive. If this is wrong, on Windows, when BazelAnalysisMock tries to re-write the WORKSPACE, it can't read the old value and instead overwrites it.\r\n\r\nI still don't know why that happens, though.",
"Root cause: when the in-memory VFS wrote the file /workspace/WORKSPACE, the OS was Windows, so the written hash code was \"WORKSPACE\".toLowerCase().hashCode().\r\nWhen it re-wrote the WORKSPACE, the OS was Linux, so the hash code was \"WORKSPACE\".hashCode().\r\n\r\nThis lead to the effective WORKSPACE file being replaced, instead of appended, and so the test value of \"/bazel_tools_workspace\" for @bazel_tools was dropped.\r\n\r\nSheesh.",
"Ugh.. Nice debugging @katre !"
] | [] | "2019-01-18T20:43:55Z" | [
"type: bug",
"P2",
"team-Configurability"
] | Enable LocalConfigPlatformFunctionTest on Windows | Currently it fails with the error:
```
1) generateConfigRepository(com.google.devtools.build.lib.bazel.repository.LocalConfigPlatformFunctionPosixTest$FunctionTest)
java.lang.AssertionError: ERROR /usr/local/google/_blaze_jrluser/FAKEMD5/external/local_config_platform_test/BUILD.bazel:3:1: no such package '@bazel_tools//platforms': /usr/local/google/_blaze_jrluser/FAKEMD5/external/bazel_tools must be an existing directory and referenced by '@local_config_platform_test//:host'
```
which seems to indicate a problem with the test environment setup. | [
"src/main/java/com/google/devtools/build/lib/util/CPU.java",
"src/main/java/com/google/devtools/build/lib/util/OS.java"
] | [
"src/main/java/com/google/devtools/build/lib/util/CPU.java",
"src/main/java/com/google/devtools/build/lib/util/OS.java"
] | [
"src/test/java/com/google/devtools/build/lib/bazel/repository/BUILD",
"src/test/java/com/google/devtools/build/lib/bazel/repository/LocalConfigPlatformFunctionTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/util/CPU.java b/src/main/java/com/google/devtools/build/lib/util/CPU.java
index 78545906487ca6..8a6de0f2c2ffb1 100644
--- a/src/main/java/com/google/devtools/build/lib/util/CPU.java
+++ b/src/main/java/com/google/devtools/build/lib/util/CPU.java
@@ -44,23 +44,14 @@ public String getCanonicalName() {
}
private static final CPU HOST_CPU = determineCurrentCpu();
- @Nullable private static CPU cpuForTesting = null;
/**
* The current CPU.
*/
public static CPU getCurrent() {
- if (cpuForTesting != null) {
- return cpuForTesting;
- }
return HOST_CPU;
}
- @VisibleForTesting
- public static void setForTesting(@Nullable CPU cpu) {
- cpuForTesting = cpu;
- }
-
private static CPU determineCurrentCpu() {
String currentArch = OS_ARCH.value();
diff --git a/src/main/java/com/google/devtools/build/lib/util/OS.java b/src/main/java/com/google/devtools/build/lib/util/OS.java
index 70585ff93b7952..06266eccff3c2d 100644
--- a/src/main/java/com/google/devtools/build/lib/util/OS.java
+++ b/src/main/java/com/google/devtools/build/lib/util/OS.java
@@ -47,23 +47,14 @@ public String toString() {
}
private static final OS HOST_SYSTEM = determineCurrentOs();
- @Nullable private static OS osForTesting = null;
/**
* The current operating system.
*/
public static OS getCurrent() {
- if (osForTesting != null) {
- return osForTesting;
- }
return HOST_SYSTEM;
}
- @VisibleForTesting
- public static void setForTesting(OS os) {
- osForTesting = os;
- }
-
public static boolean isPosixCompatible() {
return POSIX_COMPATIBLE.contains(getCurrent());
}
| diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/BUILD b/src/test/java/com/google/devtools/build/lib/bazel/repository/BUILD
index 355cb47e9543e6..7e191f5c1e2dd1 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/BUILD
@@ -9,7 +9,6 @@ filegroup(
srcs = glob(["**"]) + [
"//src/test/java/com/google/devtools/build/lib/bazel/repository/cache:srcs",
"//src/test/java/com/google/devtools/build/lib/bazel/repository/downloader:srcs",
- "//src/test/java/com/google/devtools/build/lib/bazel/repository/posix:srcs",
],
visibility = ["//src/test/java/com/google/devtools/build/lib/bazel:__pkg__"],
)
@@ -74,7 +73,6 @@ test_suite(
":windows_tests",
"//src/test/java/com/google/devtools/build/lib/bazel/repository/cache:all_windows_tests",
"//src/test/java/com/google/devtools/build/lib/bazel/repository/downloader:all_windows_tests",
- "//src/test/java/com/google/devtools/build/lib/bazel/repository/posix:all_windows_tests",
],
visibility = ["//src/test/java/com/google/devtools/build/lib/bazel:__pkg__"],
)
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/LocalConfigPlatformFunctionTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/LocalConfigPlatformFunctionTest.java
index 86cbbc376021fa..663d62d19d9310 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/LocalConfigPlatformFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/LocalConfigPlatformFunctionTest.java
@@ -17,12 +17,20 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.analysis.ConfiguredTarget;
+import com.google.devtools.build.lib.analysis.platform.ConstraintSettingInfo;
+import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
+import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
+import com.google.devtools.build.lib.analysis.platform.PlatformProviderUtils;
+import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
+import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.util.CPU;
import com.google.devtools.build.lib.util.OS;
import java.util.Collection;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
+import org.junit.runners.JUnit4;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@@ -99,4 +107,45 @@ public void unknownOsConstraint() {
assertThat(LocalConfigPlatformFunction.osToConstraint(OS.UNKNOWN)).isNull();
}
}
+
+ /** Tests on overall functionality. */
+ @RunWith(JUnit4.class)
+ public static class FunctionTest extends BuildViewTestCase {
+ private static final ConstraintSettingInfo CPU_CONSTRAINT =
+ ConstraintSettingInfo.create(Label.parseAbsoluteUnchecked("@bazel_tools//platforms:cpu"));
+ private static final ConstraintSettingInfo OS_CONSTRAINT =
+ ConstraintSettingInfo.create(Label.parseAbsoluteUnchecked("@bazel_tools//platforms:os"));
+
+ @Test
+ public void generateConfigRepository() throws Exception {
+ scratch.appendFile("WORKSPACE", "local_config_platform(name='local_config_platform_test')");
+ invalidatePackages();
+
+ // Verify the package was created as expected.
+ ConfiguredTarget hostPlatform = getConfiguredTarget("@local_config_platform_test//:host");
+ assertThat(hostPlatform).isNotNull();
+
+ PlatformInfo hostPlatformProvider = PlatformProviderUtils.platform(hostPlatform);
+ assertThat(hostPlatformProvider).isNotNull();
+
+ // Verify the OS and CPU constraints.
+ ConstraintValueInfo expectedCpuConstraint =
+ ConstraintValueInfo.create(
+ CPU_CONSTRAINT,
+ Label.parseAbsoluteUnchecked(
+ LocalConfigPlatformFunction.cpuToConstraint(CPU.getCurrent())));
+ assertThat(hostPlatformProvider.constraints().has(CPU_CONSTRAINT)).isTrue();
+ assertThat(hostPlatformProvider.constraints().get(CPU_CONSTRAINT))
+ .isEqualTo(expectedCpuConstraint);
+
+ ConstraintValueInfo expectedOsConstraint =
+ ConstraintValueInfo.create(
+ OS_CONSTRAINT,
+ Label.parseAbsoluteUnchecked(
+ LocalConfigPlatformFunction.osToConstraint(OS.getCurrent())));
+ assertThat(hostPlatformProvider.constraints().has(OS_CONSTRAINT)).isTrue();
+ assertThat(hostPlatformProvider.constraints().get(OS_CONSTRAINT))
+ .isEqualTo(expectedOsConstraint);
+ }
+ }
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/posix/BUILD b/src/test/java/com/google/devtools/build/lib/bazel/repository/posix/BUILD
deleted file mode 100644
index ba02aada98a2af..00000000000000
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/posix/BUILD
+++ /dev/null
@@ -1,54 +0,0 @@
-package(
- default_testonly = 1,
- default_visibility = ["//src:__subpackages__"],
-)
-
-filegroup(
- name = "srcs",
- testonly = 0,
- srcs = glob(["**"]),
- visibility = ["//src/test/java/com/google/devtools/build/lib/bazel/repository:__pkg__"],
-)
-
-java_test(
- name = "PosixRepositoryTests",
- srcs = glob([
- "**/*.java",
- ]),
- tags = [
- "no_windows", # Tests require Linux.
- "rules",
- ],
- test_class = "com.google.devtools.build.lib.AllTests",
- deps = [
- "//src/main/java/com/google/devtools/build/lib:build-base",
- "//src/main/java/com/google/devtools/build/lib:os_util",
- "//src/main/java/com/google/devtools/build/lib:util",
- "//src/main/java/com/google/devtools/build/lib/analysis/platform",
- "//src/main/java/com/google/devtools/build/lib/analysis/platform:utils",
- "//src/main/java/com/google/devtools/build/lib/cmdline",
- "//src/test/java/com/google/devtools/build/lib:analysis_testutil",
- "//third_party:guava",
- "//third_party:guava-testlib",
- "//third_party:jsr305",
- "//third_party:junit4",
- "//third_party:truth",
- ],
-)
-
-test_suite(
- name = "windows_tests",
- tags = [
- "-no_windows",
- "-slow",
- ],
- visibility = ["//visibility:private"],
-)
-
-test_suite(
- name = "all_windows_tests",
- tests = [
- ":windows_tests",
- ],
- visibility = ["//src/test/java/com/google/devtools/build/lib/bazel/repository:__pkg__"],
-)
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/posix/LocalConfigPlatformFunctionPosixTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/posix/LocalConfigPlatformFunctionPosixTest.java
deleted file mode 100644
index 914de0111469fc..00000000000000
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/posix/LocalConfigPlatformFunctionPosixTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2018 The Bazel Authors. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package com.google.devtools.build.lib.bazel.repository.posix;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import com.google.devtools.build.lib.analysis.ConfiguredTarget;
-import com.google.devtools.build.lib.analysis.platform.ConstraintSettingInfo;
-import com.google.devtools.build.lib.analysis.platform.ConstraintValueInfo;
-import com.google.devtools.build.lib.analysis.platform.PlatformInfo;
-import com.google.devtools.build.lib.analysis.platform.PlatformProviderUtils;
-import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
-import com.google.devtools.build.lib.cmdline.Label;
-import com.google.devtools.build.lib.util.CPU;
-import com.google.devtools.build.lib.util.OS;
-import org.junit.Test;
-import org.junit.experimental.runners.Enclosed;
-import org.junit.runner.RunWith;
-import org.junit.runners.JUnit4;
-
-/** Posix-only tests for {@link LocalConfigPlatformFunction}. */
-@RunWith(Enclosed.class)
-public class LocalConfigPlatformFunctionPosixTest {
-
- /** Tests on overall functionality. */
- @RunWith(JUnit4.class)
- public static class FunctionTest extends BuildViewTestCase {
- private static final ConstraintSettingInfo CPU_CONSTRAINT =
- ConstraintSettingInfo.create(Label.parseAbsoluteUnchecked("@bazel_tools//platforms:cpu"));
- private static final ConstraintSettingInfo OS_CONSTRAINT =
- ConstraintSettingInfo.create(Label.parseAbsoluteUnchecked("@bazel_tools//platforms:os"));
-
- private static final ConstraintValueInfo X86_64_CONSTRAINT =
- ConstraintValueInfo.create(
- CPU_CONSTRAINT, Label.parseAbsoluteUnchecked("@bazel_tools//platforms:x86_64"));
- private static final ConstraintValueInfo LINUX_CONSTRAINT =
- ConstraintValueInfo.create(
- OS_CONSTRAINT, Label.parseAbsoluteUnchecked("@bazel_tools//platforms:linux"));
-
- @Test
- public void generateConfigRepository() throws Exception {
- CPU.setForTesting(CPU.X86_64);
- OS.setForTesting(OS.LINUX);
-
- scratch.appendFile("WORKSPACE", "local_config_platform(name='local_config_platform_test')");
- invalidatePackages();
-
- // Verify the package was created as expected.
- ConfiguredTarget hostPlatform = getConfiguredTarget("@local_config_platform_test//:host");
- assertThat(hostPlatform).isNotNull();
-
- PlatformInfo hostPlatformProvider = PlatformProviderUtils.platform(hostPlatform);
- assertThat(hostPlatformProvider).isNotNull();
-
- // Verify the OS and CPU constraints.
- assertThat(hostPlatformProvider.constraints().has(CPU_CONSTRAINT)).isTrue();
- assertThat(hostPlatformProvider.constraints().get(CPU_CONSTRAINT))
- .isEqualTo(X86_64_CONSTRAINT);
-
- assertThat(hostPlatformProvider.constraints().has(OS_CONSTRAINT)).isTrue();
- assertThat(hostPlatformProvider.constraints().get(OS_CONSTRAINT)).isEqualTo(LINUX_CONSTRAINT);
- }
- }
-}
| train | train | 2019-01-18T20:49:56 | "2019-01-10T15:03:50Z" | katre | test |
bazelbuild/bazel/7081_9109 | bazelbuild/bazel | bazelbuild/bazel/7081 | bazelbuild/bazel/9109 | [
"timestamp(timedelta=0.0, similarity=0.9200953409301609)"
] | e0f1c1c0f5227c1bcbcfe460889bbcf1c65de5e8 | 890cbc06726d3d6ccd21b509bf0fff6bfb0989ca | [
"This flag is part of the work on #6849 .",
"Changed the targetted flag-flip release, since this will require extensive testing and may need to wait for the projected migration plan for the cpu flag.",
"Hey @katre, I just re-discovered this flag, what's needed to flip this? Or at least to get to a place where we can ask users to try and to re-enable it on the CI to see what's broken on downstream?",
"Related: bazelbuild/rules_go#2089, bazelbuild/rules_cc#24, #8763, https://github.com/bazelbuild/bazel/issues/8766.",
"Major work left:\r\n1. Set the right tags so that we get migration readiness reports from CI, which I apparently never get right.\r\n2. Write directions so that users who currently use cross-compilation with `--cpu` and `--host_cpu` and platform-related rules can add a platform mapping and continue work. I suspect this is a small set of users but I can't prove that.",
"Looks like only Bazel is to be migrated: https://buildkite.com/bazel/bazelisk-plus-incompatible-flags/builds/175",
"Thanks for the pointer!",
"Logs: https://buildkite.com/bazel/bazelisk-plus-incompatible-flags/builds/191#annotation---incompatible_auto_configure_host_platform",
"Since this flag is already flipped, I'm temporarily removing the `migration-0.29` label from it because https://github.com/bazelbuild/bazel/issues/9104 is preventing the incompatible flags pipeline to give correct result on Windows and our update to Bazelisk is not ready yet.\r\n\r\nFYI @dslomov "
] | [
"Is this line still within the char limit? Unsure whether this can be visualized in github review...",
"One l too many in untill.",
"Yes, 99 characters long according to vim.",
"Fixed."
] | "2019-08-07T15:20:06Z" | [
"P1",
"team-Configurability",
"incompatible-change"
] | incompatible_auto_configure_host_platform: Switch to new auto-configured host platforms | Flag: --incompatible_auto_configure_host_platform
Available since: 0.23
Will be flipped in: 1.0
**ADDED CONTEXT**
This also affects platforms that inherit from platforms in `@bazel_tools//platforms`.
**Symptoms**: your build works with Bazel 0.29.1 but fails with 'no matching toolchains found' error on local builds with Bazel 1.0 (or Bazel 0.29.1 with `--incompatible_auto_configure_host_platform` is set to true).
**What's happening**: In Bazel 1.0, the default value for `--incompatible_auto_configure_host_platform` was flipped from false to true. The label for the autoconfigured host platform changed from `@bazel_tools//platforms:host_platform` to `@local_config_platform//:host`. The old platform is no longer populated with proper constraints.
**How to fix it**: The quick fix is to replace all occurrences of `@bazel_tools//platforms:host_platform` with `@local_config_platform//:host`.
If your usage of `@bazel_tools//platforms:host_platform` is tied to `remote_execution_properties`, Bazel 1.0 has new features to help you simplify your set up and decouple it from future changes to platforms and toolchains. You might be able to reduce the number of platforms you maintain and remove the need for platform inheritance in the first place. See https://github.com/bazelbuild/bazel/issues/10266 for migration instructions.
**Original Content**
See https://github.com/bazelbuild/proposals/blob/master/designs/2018-10-22-autoconfigured-host-platform.md for more context.
The default host and target platforms are defined in `@bazel_tools//platforms`, and there is special-purpose code in the Platform rule implementation to support this. This complicates the platform rules implementation and makes them dependent on the configuration.
Once this flag is enabled, Bazel will instead default to using a host platform generated by a repository rule, located at `@local_config_platform//:host`, and which will be created only once for a given build. The target platform will also default to this. Once migration is complete, the legacy targets and code can be removed.
Migration notes:
This only affects builds where the `--host_platform` and `--platforms` flags are _not_ used. Any builds currently setting those flags will not be affected.
Any users who rely on `--host_platform` and `--platforms` being affected by the `--host_cpu` and `--cpu` flags will need to begin directly setting `--host_platform` and `--platforms`.
| [
"src/main/java/com/google/devtools/build/lib/analysis/PlatformOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/PlatformOptions.java"
] | [
"src/test/java/com/google/devtools/build/lib/rules/platform/PlatformTest.java",
"src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingFunctionTest.java",
"src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingValueTest.java",
"src/test/java/com/google/devtools/build/lib/testutil/TestConstants.java",
"src/test/shell/integration/java_integration_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/PlatformOptions.java b/src/main/java/com/google/devtools/build/lib/analysis/PlatformOptions.java
index 45e50ab9df2e18..d6f9d6600ed2ab 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/PlatformOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/PlatformOptions.java
@@ -169,7 +169,7 @@ public class PlatformOptions extends FragmentOptions {
@Option(
name = "incompatible_auto_configure_host_platform",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
metadataTags = {
| diff --git a/src/test/java/com/google/devtools/build/lib/rules/platform/PlatformTest.java b/src/test/java/com/google/devtools/build/lib/rules/platform/PlatformTest.java
index b8fb9623df9d20..d2f6d0b6d6e6f3 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/platform/PlatformTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/platform/PlatformTest.java
@@ -35,8 +35,11 @@ public class PlatformTest extends BuildViewTestCase {
@Rule public ExpectedException expectedException = ExpectedException.none();
@Test
+ // TODO(https://github.com/bazelbuild/bazel/issues/6849): Remove this test when the functionality
+ // is removed, but until then it still needs to be verified.
public void testPlatform_autoconfig() throws Exception {
- useConfiguration("--host_cpu=piii", "--cpu=k8");
+ useConfiguration(
+ "--host_cpu=piii", "--cpu=k8", "--noincompatible_auto_configure_host_platform");
scratch.file(
"autoconfig/BUILD",
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingFunctionTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingFunctionTest.java
index 985cad1d77ec52..4fa80be5e57ca5 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingFunctionTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingFunctionTest.java
@@ -63,7 +63,7 @@ public class PlatformMappingFunctionTest extends BuildViewTestCase {
BuildOptions.diffForReconstruction(
DEFAULT_BUILD_CONFIG_PLATFORM_OPTIONS, DEFAULT_BUILD_CONFIG_PLATFORM_OPTIONS);
private static final Label DEFAULT_TARGET_PLATFORM =
- Label.parseAbsoluteUnchecked("@bazel_tools//platforms:target_platform");
+ Label.parseAbsoluteUnchecked("@local_config_platform//:host");
@Test
public void testMappingFileDoesNotExist() throws Exception {
diff --git a/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingValueTest.java b/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingValueTest.java
index f1efc3608419b9..b04f2d41f05ef8 100644
--- a/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingValueTest.java
+++ b/src/test/java/com/google/devtools/build/lib/skyframe/PlatformMappingValueTest.java
@@ -57,7 +57,7 @@ public class PlatformMappingValueTest {
BuildOptions.diffForReconstruction(
DEFAULT_BUILD_CONFIG_PLATFORM_OPTIONS, DEFAULT_BUILD_CONFIG_PLATFORM_OPTIONS);
private static final Label DEFAULT_TARGET_PLATFORM =
- Label.parseAbsoluteUnchecked("@bazel_tools//platforms:target_platform");
+ Label.parseAbsoluteUnchecked("@local_config_platform//:host");
@Test
public void testMapNoMappings() throws OptionsParsingException {
diff --git a/src/test/java/com/google/devtools/build/lib/testutil/TestConstants.java b/src/test/java/com/google/devtools/build/lib/testutil/TestConstants.java
index 0a43017cffb6c0..41358c638fc110 100644
--- a/src/test/java/com/google/devtools/build/lib/testutil/TestConstants.java
+++ b/src/test/java/com/google/devtools/build/lib/testutil/TestConstants.java
@@ -121,6 +121,7 @@ public static void processSkyframeExecutorForTesting(SkyframeExecutor skyframeEx
public static final ImmutableList<String> PRODUCT_SPECIFIC_FLAGS =
ImmutableList.of(
"--target_platform_fallback=@bazel_tools//platforms:default_target",
+ "--platforms=@bazel_tools//platforms:default_target",
"--host_platform=@bazel_tools//platforms:default_host",
// TODO(#7903): Remove once our own tests are migrated.
"--incompatible_py3_is_default=false",
diff --git a/src/test/shell/integration/java_integration_test.sh b/src/test/shell/integration/java_integration_test.sh
index 9722ef0f5722db..bfec5452af8aa3 100755
--- a/src/test/shell/integration/java_integration_test.sh
+++ b/src/test/shell/integration/java_integration_test.sh
@@ -277,7 +277,7 @@ toolchain(
)
platform(
name = 'platform',
- parents = ['@bazel_tools//platforms:host_platform'],
+ parents = ['@local_config_platform//:host'],
constraint_values = [':constraint'],
)
EOF
@@ -308,6 +308,7 @@ EOF
# Set javabase to an absolute path.
bazel build //$pkg/java/hello:hello //$pkg/java/hello:hello_deploy.jar \
"$stamp_arg" --javabase="//$pkg/jvm:runtime" \
+ --incompatible_auto_configure_host_platform \
--extra_toolchains="//$pkg/jvm:all,//tools/jdk:all" \
--platforms="//$pkg/jvm:platform" \
"$embed_label" >&"$TEST_log" \
| train | train | 2019-08-08T18:23:40 | "2019-01-10T16:38:51Z" | katre | test |
bazelbuild/bazel/7137_7617 | bazelbuild/bazel | bazelbuild/bazel/7137 | bazelbuild/bazel/7617 | [
"timestamp(timedelta=0.0, similarity=0.9179705795408803)"
] | 7ff1bae119a3b6537ed0e0aa8fb4c8517461f1b0 | a27c9602771e4ffd6a94951fb3ae111ff5d96aa8 | [
"We need to fix this for remote execution and caching across all protocols. In the case of remote execution, we'll also need to set `skip_cache_lookup` to `true` in order to ensure re-execution."
] | [
"So \"we don't cache failed actions\" is no longer correct for Bazel? If so, this comment is no longer true (even if Bazel won't cache failed actions itself).",
"s/missed cache/cache miss/",
"Why do we need to test for the metadata?",
"why do you think the asserts below this line are valuable for the test?",
"I think the cache and execution priority aren't important for this test, no?",
"// Failed actions are treated as a cache miss mostly in order to avoid caching flaky actions (tests).",
"Afaik these are all default values no?",
"upload should be called because `uploadLocalResults` is `true`. Generally, if a failed action was cached which then succeeds locally we want to overwrite the failed result with the successful result in the cache. This would typically be used for flaky tests.",
"Right, we don't. Cleaned up.",
"We need to verify, that current action indeed treated as a cash miss => we do not attempt to download anything. \r\nAsserts in line 528-529 are obsolete, removing them.",
"Whether or not something is being downloaded seems orthogonal to what should be tested here. I'd argue that all this test should verify is that it's indeed a cache miss. We then have a separate unit test that verifies what should/should not happen on a cache miss.",
"`when(res.exitCode()).thenReturn(1);\r\n when(res.status()).thenReturn(Status.EXECUTION_FAILED);`\r\nbecause of these 2 lines the local action also failed => no upload expected to the cache.\r\n\r\nBut I think successful use case makes more sense here, so changed to cache miss + successful local execution => cache.upload(...)",
"Fair point. Removed.",
"nit: instead of mocking the spawn you can just use SpawnResult.Builder()"
] | "2019-03-04T16:05:29Z" | [
"type: bug",
"P1",
"team-Remote-Exec"
] | remote: treat failed actions as a cache miss | If a remote cache returns a failed action (exit code != 0) then Bazel should treat this as a cache miss and attempt to re-execute the action. See for details https://gitlab.com/BuildGrid/buildgrid/issues/151 | [
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java"
] | [
"src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java",
"src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java
index f86de075f83ad4..7d9d2bde32eb2c 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java
@@ -135,8 +135,9 @@ public CacheHandle lookup(Spawn spawn, SpawnExecutionContext context)
try (SilentCloseable c = Profiler.instance().profile("RemoteCache.getCachedActionResult")) {
result = remoteCache.getCachedActionResult(actionKey);
}
- if (result != null) {
- // We don't cache failed actions, so we know the outputs exist.
+ if (result != null && result.getExitCode() == 0) {
+ // In case if failed action returned (exit code != 0) we treat it as a cache miss
+ // Otherwise, we know that result exists.
try (SilentCloseable c = Profiler.instance().profile("RemoteCache.download")) {
remoteCache.download(result, execRoot, context.getFileOutErr());
}
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java
index f0625ed2a68b31..1bbe8f0c262afd 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java
@@ -191,21 +191,20 @@ public SpawnResult exec(Spawn spawn, SpawnExecutionContext context)
}
if (cachedResult != null) {
if (cachedResult.getExitCode() != 0) {
- // The remote cache must never serve a failed action.
- throw new EnvironmentalExecException(
- "The remote cache is in an invalid state as it"
- + " served a failed action. Hash of the action: "
- + actionKey.getDigest());
- }
- try (SilentCloseable c = Profiler.instance().profile("Remote.downloadRemoteResults")) {
- return downloadRemoteResults(cachedResult, context.getFileOutErr())
- .setCacheHit(true)
- .setRunnerName("remote cache hit")
- .build();
- } catch (CacheNotFoundException e) {
- // No cache hit, so we fall through to local or remote execution.
- // We set acceptCachedResult to false in order to force the action re-execution.
+ // Failed actions are treated as a cache miss mostly in order to avoid caching flaky actions (tests).
+ // Set acceptCachedResult to false in order to force the action re-execution
acceptCachedResult = false;
+ } else {
+ try (SilentCloseable c = Profiler.instance().profile("Remote.downloadRemoteResults")) {
+ return downloadRemoteResults(cachedResult, context.getFileOutErr())
+ .setCacheHit(true)
+ .setRunnerName("remote cache hit")
+ .build();
+ } catch (CacheNotFoundException e) {
+ // No cache hit, so we fall through to local or remote execution.
+ // We set acceptCachedResult to false in order to force the action re-execution.
+ acceptCachedResult = false;
+ }
}
}
} catch (IOException e) {
| diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java
index d50adcf11d191e..da2ff6f327a5dc 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java
@@ -513,4 +513,14 @@ public Void answer(InvocationOnMock invocation) {
.containsExactly(Pair.of(ProgressStatus.CHECKING_CACHE, "remote-cache"));
assertThat(eventHandler.getEvents()).isEmpty(); // no warning is printed.
}
+
+ @Test
+ public void failedCacheActionAsCacheMiss() throws Exception {
+ ActionResult actionResult = ActionResult.newBuilder().setExitCode(1).build();
+ when(remoteCache.getCachedActionResult(any(ActionKey.class))).thenReturn(actionResult);
+
+ CacheHandle entry = cache.lookup(simpleSpawn, simplePolicy);
+
+ assertThat(entry.hasResult()).isFalse();
+ }
}
diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java
index 328a707a1cd7f7..07a585f52bfbff 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java
@@ -14,7 +14,6 @@
package com.google.devtools.build.lib.remote;
import static com.google.common.truth.Truth.assertThat;
-import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
@@ -47,7 +46,6 @@
import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander;
import com.google.devtools.build.lib.actions.ArtifactPathResolver;
import com.google.devtools.build.lib.actions.CommandLines.ParamFileActionInput;
-import com.google.devtools.build.lib.actions.EnvironmentalExecException;
import com.google.devtools.build.lib.actions.ExecutionRequirements;
import com.google.devtools.build.lib.actions.MetadataProvider;
import com.google.devtools.build.lib.actions.ParameterFile.ParameterFileType;
@@ -330,17 +328,14 @@ public void failedLocalActionShouldNotBeUploaded() throws Exception {
}
@Test
- public void dontAcceptFailedCachedAction() throws Exception {
- // Test that bazel fails if the remote cache serves a failed action.
+ @SuppressWarnings("unchecked")
+ public void treatFailedCachedActionAsCacheMiss_local() throws Exception {
+ // Test that bazel treats failed cache action as a cache miss and attempts to execute action locally
RemoteOptions options = Options.getDefaults(RemoteOptions.class);
-
ActionResult failedAction = ActionResult.newBuilder().setExitCode(1).build();
when(cache.getCachedActionResult(any(ActionKey.class))).thenReturn(failedAction);
- Spawn spawn = newSimpleSpawn();
- SpawnExecutionContext policy = new FakeSpawnExecutionContext(spawn);
-
RemoteSpawnRunner runner =
spy(
new RemoteSpawnRunner(
@@ -349,7 +344,7 @@ public void dontAcceptFailedCachedAction() throws Exception {
Options.getDefaults(ExecutionOptions.class),
new AtomicReference<>(localRunner),
true,
- /*cmdlineReporter=*/ null,
+ /* cmdlineReporter= */ null,
"build-req-id",
"command-id",
cache,
@@ -357,8 +352,79 @@ public void dontAcceptFailedCachedAction() throws Exception {
retrier,
digestUtil,
logDir));
+ Spawn spawn = newSimpleSpawn();
+ SpawnExecutionContext policy = new FakeSpawnExecutionContext(spawn);
+
+ SpawnResult succeeded =
+ new SpawnResult.Builder()
+ .setStatus(Status.SUCCESS)
+ .setExitCode(0)
+ .setRunnerName("test")
+ .build();
+ when(localRunner.exec(eq(spawn), eq(policy))).thenReturn(succeeded);
- assertThrows(EnvironmentalExecException.class, () -> runner.exec(spawn, policy));
+ runner.exec(spawn, policy);
+
+ verify(localRunner).exec(eq(spawn), eq(policy));
+ verify(runner)
+ .execLocallyAndUpload(
+ eq(spawn),
+ eq(policy),
+ any(SortedMap.class),
+ eq(cache),
+ any(ActionKey.class),
+ any(Action.class),
+ any(Command.class),
+ /* uploadLocalResults= */ eq(true));
+ verify(cache)
+ .upload(
+ any(ActionKey.class),
+ any(Action.class),
+ any(Command.class),
+ any(Path.class),
+ any(Collection.class),
+ any(FileOutErr.class));
+ verify(cache, never())
+ .download(
+ any(ActionResult.class),
+ any(Path.class),
+ eq(outErr));
+ }
+
+ @Test
+ public void treatFailedCachedActionAsCacheMiss_remote() throws Exception {
+ // Test that bazel treats failed cache action as a cache miss and attempts to execute action remotely
+
+ ActionResult failedAction = ActionResult.newBuilder().setExitCode(1).build();
+ when(cache.getCachedActionResult(any(ActionKey.class))).thenReturn(failedAction);
+
+ RemoteSpawnRunner runner =
+ new RemoteSpawnRunner(
+ execRoot,
+ options,
+ Options.getDefaults(ExecutionOptions.class),
+ new AtomicReference<>(localRunner),
+ true,
+ /* cmdlineReporter= */ null,
+ "build-req-id",
+ "command-id",
+ cache,
+ executor,
+ retrier,
+ digestUtil,
+ logDir);
+
+ ExecuteResponse succeeded = ExecuteResponse.newBuilder().setResult(
+ ActionResult.newBuilder().setExitCode(0).build()).build();
+ when(executor.executeRemotely(any(ExecuteRequest.class))).thenReturn(succeeded);
+ Spawn spawn = newSimpleSpawn();
+ SpawnExecutionContext policy = new FakeSpawnExecutionContext(spawn);
+
+ runner.exec(spawn, policy);
+
+ ArgumentCaptor<ExecuteRequest> requestCaptor = ArgumentCaptor.forClass(ExecuteRequest.class);
+ verify(executor).executeRemotely(requestCaptor.capture());
+ assertThat(requestCaptor.getValue().getSkipCacheLookup()).isTrue();
}
@Test
| val | train | 2019-03-18T08:56:31 | "2019-01-16T09:10:05Z" | buchgr | test |
bazelbuild/bazel/7167_7172 | bazelbuild/bazel | bazelbuild/bazel/7167 | bazelbuild/bazel/7172 | [
"timestamp(timedelta=1.0, similarity=0.8952493440993834)"
] | 356ad221eaa9a81ae7ef0b967195b895e9e0d217 | e545447562c4583c682bffd75b329d9614793653 | [
"cc @meisterT "
] | [] | "2019-01-18T08:27:24Z" | [
"P2",
"area-EngProd",
"team-Rules-Java",
"team-OSS"
] | //scripts/packages:without-jdk/bazel includes a jdk | `//scripts/packages:rename-bazel-bin-without-jdk`, which produces `//scripts/packages:without-jdk/bazel` includes `//src:bazel`[0], which due to semi-recent changes, now **includes** a jdk. It should be changed to `//src:bazel_nojdk` to support generating a bazel.sh without an embedded JDK. This change seems to have been missed by 7c49bd9c73385db84e678469aa7e6a5bb801c28a
[0] As of c67dceca77a93646961fc4bb863826e344fda5e0 | [
"scripts/packages/BUILD"
] | [
"scripts/packages/BUILD"
] | [] | diff --git a/scripts/packages/BUILD b/scripts/packages/BUILD
index 5a66400d1f440c..7e9ec210b2578e 100644
--- a/scripts/packages/BUILD
+++ b/scripts/packages/BUILD
@@ -93,7 +93,7 @@ genrule(
genrule(
name = "rename-bazel-bin-without-jdk",
- srcs = ["//src:bazel"],
+ srcs = ["//src:bazel_nojdk"],
outs = ["without-jdk/bazel-real"],
cmd = "mkdir -p $$(dirname $@); cp $< $@",
)
| null | train | train | 2019-01-18T07:50:46 | "2019-01-17T20:02:36Z" | emidln | test |
bazelbuild/bazel/7171_7189 | bazelbuild/bazel | bazelbuild/bazel/7171 | bazelbuild/bazel/7189 | [
"timestamp(timedelta=90479.0, similarity=0.8733058587681826)"
] | 199368ca895c00e38b88ba225ade5e91661186d0 | b03facd2576e2018da4a5464053ddf9c59db1f03 | [
"Thanks for the report, I'll look into this today. It should definitely be a warning, not a hard crash.",
"The actual cycle is this:\r\n- //tests:expansion_test\r\n- needs a toolchain of type @io_bazel_rules_m4//m4:toolchain_type\r\n- depends on all registered toolchains\r\n- includes @io_bazel_rules_m4//m4/toolchains:v1.4.18\r\n- depends on @io_bazel_rules_m4//m4/internal:deny_shell\r\n- needs a toolchain of type @bazel_tools//tools/cpp:toolchain_type\r\n- depends on all registered toolchains\r\n- cycle\r\n\r\nSo, as you said, the real error here is that RegisteredToolchainsFunction has a dependency on something that isn't providing ToolchainRuleInfo.\r\n\r\nNormally, RegisteredToolchainsFunction only accepts targets of a rule named \"toolchain\", \r\nwhich prevents this in the typical case, but still allows for the odd case where someone writes a Starlark rule named \"toolchain\" and uses that incorrectly as the argument to register_toolchains. This rule is applied when expanding target patterns, such as if you wrote `register_toolchains('//toolchains:all')`.\r\n\r\nThe reason you see this error is because RegisteredToolchainsFunction tries to be forgiving, so that if a target is directly specified as the argument to register_toolchains, it is kept even if the rule name is not \"toolchain\". The assumption here being that the user knows what they are doing and intended wrat they wrote.\r\n\r\nGiven this, the best way forward is to try to add better error handling in RegisteredToolchainsFunction, which I will look into adding.",
"Reproduction:\r\n```sh\r\n$ git clone [email protected]:jmillikin/rules_m4.git\r\n$ cd rules_m4\r\n$ bazel build //tests:expansion_test --extra_toolchains=//m4/internal:toolchain_v1.4.18\r\n```\r\n\r\nOddly, a simpler reproduction test case I tried to wrote did show an error message:\r\n```\r\n$ bazel build --extra_toolchains=//:demo //:sample\r\nStarting local Bazel server and connecting to it...\r\nINFO: Invocation ID: 5958e443-ec4a-4054-8cc6-112d98bd94bf\r\nERROR: While resolving toolchains for target //:sample: invalid registered toolchain '//:demo': target does not provide the DeclaredToolchainInfo provider\r\nWARNING: errors encountered while analyzing target '//:sample': it will not be built\r\nINFO: Analysed target //:sample (6 packages loaded, 23 targets configured).\r\nINFO: Found 0 targets...\r\nERROR: command succeeded, but not all targets were analyzed\r\nINFO: Elapsed time: 2.956s, Critical Path: 0.02s\r\nINFO: 0 processes.\r\nFAILED: Build did NOT complete successfully\r\n```",
"Okay, managed to get a simpler reproduction, because this relies on their being two toolchains, one of which depends on the other, and the top-level one being mis-configured in register_toolchains.\r\n\r\nLooking into implementing a cycle reporter to make the problem clear. I'm not sure there's any level of introspection in RegisteredToolchainsFunction that can catch this, due to the fact that the error happens while the toolchain targets are being loaded."
] | [] | "2019-01-19T19:09:00Z" | [
"P2",
"team-Configurability"
] | java.lang.IllegalStateException when referencing ToolchainInfo targets instead of ToolchainRuleInfo | Bazel's toolchain registration involves two targets: a "toolchain info" that returns a `platform_common.ToolchainInfo` with arbitrary content, and a "toolchain" that registers the toolchain info with execution constraints.
If the user confuses these two (either when calling `native.register_toolchains()` or with the `--extra_toolchains` flag) then Bazel will crash during analysis.
example BUILD ([`rules_m4/m4/toolchains/BUILD`](https://github.com/jmillikin/rules_m4/blob/5a8562a8796963da93b6ed8e6c205551cbf949b5/m4/toolchains/BUILD)):
```
load("//m4:m4.bzl", "M4_VERSIONS")
load("//m4:toolchain.bzl", "m4_toolchain_info")
[m4_toolchain_info(
name = "v{}".format(version),
m4 = "@m4_v{}//bin:m4".format(version),
tags = ["manual"],
visibility = ["//visibility:public"],
) for version in M4_VERSIONS]
[toolchain(
name = "v{}_toolchain".format(version),
toolchain = ":v{}".format(version),
toolchain_type = "//m4:toolchain_type",
) for version in M4_VERSIONS]
```
Full error output when the user forgets the `_toolchain` suffix:
```
$ ./bazel-0.22.0rc1-darwin-x86_64 build //tests:expansion_test --extra_toolchains=@io_bazel_rules_m4//m4/toolchains:v1.4.18
Starting local Bazel server and connecting to it...
INFO: Invocation ID: 2780f5f3-5e47-4588-805e-0b2ce38fc86e
Internal error thrown during build. Printing stack trace: java.lang.IllegalStateException: topLevelKey: //tests:expansion_test BuildConfigurationValue.Key[94f032dd1c40f99180ff553125967cf3] false
alreadyReported: false
path to cycle:
//tests:expansion_test BuildConfigurationValue.Key[94f032dd1c40f99180ff553125967cf3] false
Key{configurationKey=BuildConfigurationValue.Key[94f032dd1c40f99180ff553125967cf3], toolchainTypeLabel=@io_bazel_rules_m4//m4:toolchain_type, targetPlatformKey=@bazel_tools//platforms:target_platform BuildConfigurationValue.Key[94f032dd1c40f99180ff553125967cf3] false, availableExecutionPlatformKeys=[@bazel_tools//platforms:host_platform BuildConfigurationValue.Key[94f032dd1c40f99180ff553125967cf3] false]}
RegisteredToolchainsValue.Key{configurationKey: BuildConfigurationValue.Key[94f032dd1c40f99180ff553125967cf3]}
@io_bazel_rules_m4//m4/toolchains:v1.4.18 BuildConfigurationValue.Key[94f032dd1c40f99180ff553125967cf3] false
cycle:
@io_bazel_rules_m4//m4/internal:deny_shell BuildConfigurationValue.Key[a1782a45cb1a1c8fbec9cef9245c752c] true
Key{configurationKey=BuildConfigurationValue.Key[a1782a45cb1a1c8fbec9cef9245c752c], toolchainTypeLabel=@bazel_tools//tools/cpp:toolchain_type, targetPlatformKey=@bazel_tools//platforms:host_platform BuildConfigurationValue.Key[a1782a45cb1a1c8fbec9cef9245c752c] true, availableExecutionPlatformKeys=[@bazel_tools//platforms:host_platform BuildConfigurationValue.Key[a1782a45cb1a1c8fbec9cef9245c752c] true]}
RegisteredToolchainsValue.Key{configurationKey: BuildConfigurationValue.Key[a1782a45cb1a1c8fbec9cef9245c752c]}
@io_bazel_rules_m4//m4/toolchains:v1.4.18 BuildConfigurationValue.Key[a1782a45cb1a1c8fbec9cef9245c752c] true
at com.google.common.base.Preconditions.checkState(Preconditions.java:507)
at com.google.devtools.build.skyframe.CyclesReporter.reportCycles(CyclesReporter.java:85)
at com.google.devtools.build.lib.skyframe.SkyframeBuildView.processErrors(SkyframeBuildView.java:527)
at com.google.devtools.build.lib.skyframe.SkyframeBuildView.configureTargets(SkyframeBuildView.java:444)
at com.google.devtools.build.lib.analysis.BuildView.update(BuildView.java:369)
at com.google.devtools.build.lib.buildtool.AnalysisPhaseRunner.runAnalysisPhase(AnalysisPhaseRunner.java:209)
at com.google.devtools.build.lib.buildtool.AnalysisPhaseRunner.execute(AnalysisPhaseRunner.java:118)
at com.google.devtools.build.lib.buildtool.BuildTool.buildTargets(BuildTool.java:143)
at com.google.devtools.build.lib.buildtool.BuildTool.processRequest(BuildTool.java:253)
at com.google.devtools.build.lib.runtime.commands.BuildCommand.exec(BuildCommand.java:83)
at com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.execExclusively(BlazeCommandDispatcher.java:477)
at com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.exec(BlazeCommandDispatcher.java:205)
at com.google.devtools.build.lib.server.GrpcServerImpl.executeCommand(GrpcServerImpl.java:749)
at com.google.devtools.build.lib.server.GrpcServerImpl.access$1600(GrpcServerImpl.java:103)
at com.google.devtools.build.lib.server.GrpcServerImpl$2.lambda$run$0(GrpcServerImpl.java:818)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
INFO: Elapsed time: 4.065s
``` | [
"src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java
index 1f3470a8a1eac0..283780d12588cf 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/ToolchainResolver.java
@@ -543,7 +543,7 @@ public ToolchainContext load(
if (toolchainType != null) {
ToolchainInfo toolchainInfo =
PlatformProviderUtils.toolchain(target.getConfiguredTarget());
- if (toolchainType != null) {
+ if (toolchainInfo != null) {
toolchains.put(toolchainType, toolchainInfo);
}
}
| null | test | train | 2019-01-19T18:33:38 | "2019-01-18T06:13:33Z" | jmillikin | test |
bazelbuild/bazel/7196_7423 | bazelbuild/bazel | bazelbuild/bazel/7196 | bazelbuild/bazel/7423 | [
"timestamp(timedelta=0.0, similarity=0.8850649384482638)"
] | b7bd7a1e8014a638e9b4475be8bb75e97fc53af5 | dd6f7e823d2c54cb73ef09098386c055f98beba8 | [
"For this flag and the one in #7197 - what if users don't want to download this archive, or want to change the location/manner in which this archive is obtained? This would be important for CI systems with no internet connectivity, and orgs that want to audit/control build-time dependencies (both in terms of artifacts and systems). Will there be a flag moving forward that will disable this download?",
"@scottmin0r To not download the archive you have to set the flags `--java_toolchain` and `--host_java_toolchain` to point to local tools.",
"Specifically what should I pass for those flag values? As per [this comment](https://github.com/bazelbuild/bazel/issues/6656#issuecomment-461084131) I've tried:\r\n\r\n(release 0.24.1)\r\n\r\n```\r\nbuild --javabase=@local_jdk//:jdk\r\nbuild --host_javabase=@local_jdk//:jdk\r\nbuild --java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8\r\nbuild --host_java_toolchain=@bazel_tools//tools/jdk:toolchain_hostjdk8\r\n```\r\n\r\nbut this still seems to try to download tools (with two different failure modes):\r\n\r\n```\r\nAnalyzing: 1166 targets (68 packages loaded, 2267 targets configured)\r\nAnalyzing: 1166 targets (68 packages loaded, 2267 targets configured)\r\nAnalyzing: 1166 targets (68 packages loaded, 2267 targets configured)\r\nAnalyzing: 1166 targets (68 packages loaded, 2267 targets configured)\r\nAnalyzing: 1166 targets (68 packages loaded, 2267 targets configured)\r\nERROR: /home/kbuilder/.cache/bazel/_bazel_kbuilder/94efa1614cde89691caae16b65396550/external/bazel_tools/tools/jdk/BUILD:218:1: no such package '@remote_java_tools//': java.io.IOException: Error downloading [https://mirror.bazel.build/bazel_java_tools/java_tools_pkg-0.5.1.tar.gz] to /home/kbuilder/.cache/bazel/_bazel_kbuilder/94efa1614cde89691caae16b65396550/external/remote_java_tools/java_tools_pkg-0.5.1.tar.gz: Network is unreachable (connect failed) and referenced by '@bazel_tools//tools/jdk:JacocoCoverageRunner'\r\n```\r\n\r\n```\r\nAnalyzing: 56 targets (8 packages loaded, 587 targets configured)\r\nAnalyzing: 56 targets (8 packages loaded, 587 targets configured)\r\nAnalyzing: 56 targets (8 packages loaded, 587 targets configured)\r\nAnalyzing: 56 targets (8 packages loaded, 587 targets configured)\r\nAnalyzing: 56 targets (8 packages loaded, 587 targets configured)\r\nAnalyzing: 56 targets (8 packages loaded, 587 targets configured)\r\nERROR: /home/kbuilder/.cache/bazel/_bazel_kbuilder/1858cc0ae663ea49d21c8c6b3132f559/external/bazel_tools/tools/jdk/BUILD:153:1: no such package '@remote_java_tools//': java.io.IOException: thread interrupted and referenced by '@bazel_tools//tools/jdk:genclass'\r\n```"
] | [] | "2019-02-13T15:09:10Z" | [
"incompatible-change"
] | incompatible_use_remote_java_toolchain: use remote Java tools instead of the embedded deploy jars | The option `--incompatible_use_remote_java_toolchain` will download the remote Java tools (archive of deploy jars) for the target configuration instead of using the corresponding embedded deploy jars. Enabling this flag only affects users of the Java rules.
# Migration Notes
There are no actions required from the users. No migration is needed.
| [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java",
"src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
index d4a72fdff59878..70e0c0679b2257 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
@@ -586,7 +586,7 @@ public ImportDepsCheckingLevelConverter() {
@Option(
name = "incompatible_use_remote_java_toolchain",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
metadataTags = {
@@ -600,7 +600,7 @@ public ImportDepsCheckingLevelConverter() {
@Option(
name = "incompatible_use_remote_host_java_toolchain",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
metadataTags = {
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
index e58cd0e121b1f8..9f0557f2c4b487 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
@@ -108,6 +108,19 @@ public void setupMockClient(MockToolsConfig config, List<String> workspaceConten
" genclass = ['GenClass_deploy.jar'],",
" ijar = ['ijar'],",
")",
+ "java_toolchain(",
+ " name = 'remote_toolchain',",
+ " source_version = '8',",
+ " target_version = '8',",
+ " bootclasspath = [':bootclasspath'],",
+ " extclasspath = [':extclasspath'],",
+ " javac = [':langtools'],",
+ " javabuilder = ['JavaBuilder_deploy.jar'],",
+ " header_compiler = ['turbine_deploy.jar'],",
+ " singlejar = ['SingleJar_deploy.jar'],",
+ " genclass = ['GenClass_deploy.jar'],",
+ " ijar = ['ijar'],",
+ ")",
"java_runtime(name = 'jdk', srcs = [])",
"java_runtime(name = 'host_jdk', srcs = [])",
"java_runtime(name = 'remote_jdk', srcs = [])",
diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java
index f86d67aa924f05..185c58acc6143b 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java
@@ -1899,7 +1899,10 @@ public void javaToolchainFlag_default() throws Exception {
configuredTarget.get(
new SkylarkKey(Label.parseAbsolute("//foo:rule.bzl", ImmutableMap.of()), "result"));
Label javaToolchainLabel = ((Label) info.getValue("java_toolchain_label"));
- assertThat(javaToolchainLabel.toString()).endsWith("jdk:toolchain");
+ assertThat(
+ javaToolchainLabel.toString().endsWith("jdk:remote_toolchain")
+ || javaToolchainLabel.toString().endsWith("jdk:toolchain"))
+ .isTrue();
}
@Test
| val | train | 2019-02-13T14:30:01 | "2019-01-21T10:49:02Z" | iirina | test |
bazelbuild/bazel/7197_7423 | bazelbuild/bazel | bazelbuild/bazel/7197 | bazelbuild/bazel/7423 | [
"timestamp(timedelta=157133.0, similarity=0.8819002292370186)"
] | b7bd7a1e8014a638e9b4475be8bb75e97fc53af5 | dd6f7e823d2c54cb73ef09098386c055f98beba8 | [] | [] | "2019-02-13T15:09:10Z" | [
"incompatible-change"
] | incompatible_use_remote_host_java_toolchain: use remote Java tools instead of the embedded deploy jars | The option `--incompatible_use_remote_host_java_toolchain` will download the remote Java tools (archive of deploy jars) for the host configuration instead of using the corresponding embedded deploy jars. Enabling this flag only affects users of the Java rules.
# Migration Notes
There are no actions required from the users. No migration is needed.
| [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java",
"src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
index d4a72fdff59878..70e0c0679b2257 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
@@ -586,7 +586,7 @@ public ImportDepsCheckingLevelConverter() {
@Option(
name = "incompatible_use_remote_java_toolchain",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
metadataTags = {
@@ -600,7 +600,7 @@ public ImportDepsCheckingLevelConverter() {
@Option(
name = "incompatible_use_remote_host_java_toolchain",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
effectTags = {OptionEffectTag.UNKNOWN},
metadataTags = {
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
index e58cd0e121b1f8..9f0557f2c4b487 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
@@ -108,6 +108,19 @@ public void setupMockClient(MockToolsConfig config, List<String> workspaceConten
" genclass = ['GenClass_deploy.jar'],",
" ijar = ['ijar'],",
")",
+ "java_toolchain(",
+ " name = 'remote_toolchain',",
+ " source_version = '8',",
+ " target_version = '8',",
+ " bootclasspath = [':bootclasspath'],",
+ " extclasspath = [':extclasspath'],",
+ " javac = [':langtools'],",
+ " javabuilder = ['JavaBuilder_deploy.jar'],",
+ " header_compiler = ['turbine_deploy.jar'],",
+ " singlejar = ['SingleJar_deploy.jar'],",
+ " genclass = ['GenClass_deploy.jar'],",
+ " ijar = ['ijar'],",
+ ")",
"java_runtime(name = 'jdk', srcs = [])",
"java_runtime(name = 'host_jdk', srcs = [])",
"java_runtime(name = 'remote_jdk', srcs = [])",
diff --git a/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java b/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java
index f86d67aa924f05..185c58acc6143b 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/java/JavaSkylarkApiTest.java
@@ -1899,7 +1899,10 @@ public void javaToolchainFlag_default() throws Exception {
configuredTarget.get(
new SkylarkKey(Label.parseAbsolute("//foo:rule.bzl", ImmutableMap.of()), "result"));
Label javaToolchainLabel = ((Label) info.getValue("java_toolchain_label"));
- assertThat(javaToolchainLabel.toString()).endsWith("jdk:toolchain");
+ assertThat(
+ javaToolchainLabel.toString().endsWith("jdk:remote_toolchain")
+ || javaToolchainLabel.toString().endsWith("jdk:toolchain"))
+ .isTrue();
}
@Test
| val | train | 2019-02-13T14:30:01 | "2019-01-21T10:49:45Z" | iirina | test |
bazelbuild/bazel/7204_8276 | bazelbuild/bazel | bazelbuild/bazel/7204 | bazelbuild/bazel/8276 | [
"timestamp(timedelta=153861.0, similarity=0.9533572855750213)"
] | 1df1635b0db2175191998d993052b8e37dadae7c | a68f135b19ac77b9150ea6b0c6b861cf48026500 | [
"deprecated in https://github.com/bazelbuild/bazel/pull/7985 \r\nWill be removed in #7895 "
] | [] | "2019-05-09T13:11:43Z" | [
"P2",
"type: support / not a bug (process)",
"team-Remote-Exec"
] | remote: remove --experimental_remote_retry_* flags | Simplify to just `--remote_retries=NUM` with a `0` value disabling retries. | [
"src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java b/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java
index 755b6e5ea7da18..c5a72a1bbbd133 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java
@@ -120,36 +120,6 @@ public final class RemoteOptions extends OptionsBase {
help = "Value to pass as instance_name in the remote execution API.")
public String remoteInstanceName;
- @Deprecated
- @Option(
- name = "experimental_remote_retry",
- defaultValue = "true",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public boolean experimentalRemoteRetry;
-
- @Deprecated
- @Option(
- name = "experimental_remote_retry_start_delay_millis",
- defaultValue = "100",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.UNKNOWN},
- help = "The initial delay before retrying a transient error. Use --remote_retries instead.")
- public long experimentalRemoteRetryStartDelayMillis;
-
- @Deprecated
- @Option(
- name = "experimental_remote_retry_max_delay_millis",
- defaultValue = "5000",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public long experimentalRemoteRetryMaxDelayMillis;
-
@Option(
name = "remote_retries",
oldName = "experimental_remote_retry_max_attempts",
@@ -161,26 +131,6 @@ public final class RemoteOptions extends OptionsBase {
+ "If set to 0, retries are disabled.")
public int remoteMaxRetryAttempts;
- @Deprecated
- @Option(
- name = "experimental_remote_retry_multiplier",
- defaultValue = "2",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public double experimentalRemoteRetryMultiplier;
-
- @Deprecated
- @Option(
- name = "experimental_remote_retry_jitter",
- defaultValue = "0.1",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public double experimentalRemoteRetryJitter;
-
@Option(
name = "disk_cache",
defaultValue = "null",
| null | val | train | 2019-05-09T14:50:15 | "2019-01-21T16:05:45Z" | buchgr | test |
bazelbuild/bazel/7232_7243 | bazelbuild/bazel | bazelbuild/bazel/7232 | bazelbuild/bazel/7243 | [
"timestamp(timedelta=1.0, similarity=0.9491581201419624)"
] | 4f48981dbe5b9e432bd39f92155228769467f60b | 32981566073d824bb046c0eaee645e2a13e29031 | [
"cc @benjaminp "
] | [
"The javadoc needs a update.",
"In the `RemoteSpawnCache`, the equivalent condition was moved before the concurrent modification check. It probably doesn't matter, but it doesn't hurt to be consistent either way.",
"Is it worthwhile to keep the `containsExactly` by adding the `actionKey` to the list here?",
"I'm wondering if there should be a helper for the above three lines. They appear a lot.",
"done",
"done",
"I'd argue no, as this test checks that directory uploads work. it's a protocol detail that the action and command are also stored in the CAS that should be verified elsewhere.",
"yep. done",
"done"
] | "2019-01-24T17:07:46Z" | [
"type: bug",
"P2",
"team-Remote-Exec"
] | remote: don't upload failed action outputs | For historical reasons we are currently uploading the outputs of failed actions. This was mostly so that `test.log` and `test.xml` of failed tests would be uploaded when BES was enabled. However, we have had local file uploads in BES for a while now and thus this (unexpected) feature is now obsolete. | [
"src/main/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCache.java",
"src/main/java/com/google/devtools/build/lib/remote/GrpcRemoteCache.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java",
"src/main/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCache.java",
"src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/ExecutionServer.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCache.java",
"src/main/java/com/google/devtools/build/lib/remote/GrpcRemoteCache.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java",
"src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java",
"src/main/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCache.java",
"src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/ExecutionServer.java"
] | [
"src/test/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCacheTests.java",
"src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteCacheTest.java",
"src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java",
"src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java",
"src/test/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCacheTest.java",
"src/test/shell/bazel/remote/remote_execution_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCache.java b/src/main/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCache.java
index 6b0b96c1b7eba8..0d742f5b198910 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCache.java
@@ -93,11 +93,10 @@ public AbstractRemoteActionCache(RemoteOptions options, DigestUtil digestUtil, R
throws IOException, InterruptedException;
/**
- * Upload the result of a locally executed action to the cache by uploading any necessary files,
- * stdin / stdout, as well as adding an entry for the given action key to the cache if
- * uploadAction is true.
+ * Upload the result of a locally executed action to the remote cache.
*
- * @throws IOException if the remote cache is unavailable.
+ * @throws IOException if there was an error uploading to the remote cache
+ * @throws ExecException if uploading any of the action outputs is not supported
*/
abstract void upload(
DigestUtil.ActionKey actionKey,
@@ -105,8 +104,7 @@ abstract void upload(
Command command,
Path execRoot,
Collection<Path> files,
- FileOutErr outErr,
- boolean uploadAction)
+ FileOutErr outErr)
throws ExecException, IOException, InterruptedException;
/**
diff --git a/src/main/java/com/google/devtools/build/lib/remote/GrpcRemoteCache.java b/src/main/java/com/google/devtools/build/lib/remote/GrpcRemoteCache.java
index 30dc103f23d04e..1e1ae401fb3cb9 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/GrpcRemoteCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/GrpcRemoteCache.java
@@ -297,20 +297,16 @@ public void onCompleted() {
}
@Override
- public void upload(
+ public void
+ upload(
ActionKey actionKey,
Action action,
Command command,
Path execRoot,
Collection<Path> files,
- FileOutErr outErr,
- boolean uploadAction)
- throws ExecException, IOException, InterruptedException {
+ FileOutErr outErr) throws ExecException, IOException, InterruptedException {
ActionResult.Builder result = ActionResult.newBuilder();
- upload(execRoot, actionKey, action, command, files, outErr, uploadAction, result);
- if (!uploadAction) {
- return;
- }
+ upload(execRoot, actionKey, action, command, files, outErr, result);
try {
retrier.execute(
() ->
@@ -333,7 +329,6 @@ void upload(
Command command,
Collection<Path> files,
FileOutErr outErr,
- boolean uploadAction,
ActionResult.Builder result)
throws ExecException, IOException, InterruptedException {
UploadManifest manifest =
@@ -344,9 +339,7 @@ void upload(
options.incompatibleRemoteSymlinks,
options.allowSymlinkUpload);
manifest.addFiles(files);
- if (uploadAction) {
- manifest.addAction(actionKey, action, command);
- }
+ manifest.addAction(actionKey, action, command);
List<Chunker> filesToUpload = new ArrayList<>();
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java
index 66a0b23ab41fc7..77fd0cb71e7abf 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnCache.java
@@ -190,7 +190,12 @@ public boolean willStore() {
@Override
public void store(SpawnResult result)
- throws ExecException, InterruptedException, IOException {
+ throws ExecException, InterruptedException {
+ boolean uploadResults = Status.SUCCESS.equals(result.status()) && result.exitCode() == 0;
+ if (!uploadResults) {
+ return;
+ }
+
if (options.experimentalGuardAgainstConcurrentChanges) {
try (SilentCloseable c =
Profiler.instance().profile("RemoteCache.checkForConcurrentModifications")) {
@@ -200,13 +205,13 @@ public void store(SpawnResult result)
return;
}
}
- boolean uploadAction = Status.SUCCESS.equals(result.status()) && result.exitCode() == 0;
+
Context previous = withMetadata.attach();
Collection<Path> files =
RemoteSpawnRunner.resolveActionInputs(execRoot, spawn.getOutputFiles());
try (SilentCloseable c = Profiler.instance().profile("RemoteCache.upload")) {
remoteCache.upload(
- actionKey, action, command, execRoot, files, context.getFileOutErr(), uploadAction);
+ actionKey, action, command, execRoot, files, context.getFileOutErr());
} catch (IOException e) {
String errorMsg = e.getMessage();
if (isNullOrEmpty(errorMsg)) {
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java
index 55d0cdd3a4635a..14ea4b2ae1ff00 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java
@@ -528,20 +528,23 @@ SpawnResult execLocallyAndUpload(
Map<Path, Long> ctimesBefore = getInputCtimes(inputMap);
SpawnResult result = execLocally(spawn, context);
Map<Path, Long> ctimesAfter = getInputCtimes(inputMap);
+ uploadLocalResults = uploadLocalResults &&
+ Status.SUCCESS.equals(result.status()) && result.exitCode() == 0;
+ if (!uploadLocalResults) {
+ return result;
+ }
+
for (Map.Entry<Path, Long> e : ctimesBefore.entrySet()) {
// Skip uploading to remote cache, because an input was modified during execution.
if (!ctimesAfter.get(e.getKey()).equals(e.getValue())) {
return result;
}
}
- if (!uploadLocalResults) {
- return result;
- }
- boolean uploadAction = Status.SUCCESS.equals(result.status()) && result.exitCode() == 0;
+
Collection<Path> outputFiles = resolveActionInputs(execRoot, spawn.getOutputFiles());
try (SilentCloseable c = Profiler.instance().profile("Remote.upload")) {
remoteCache.upload(
- actionKey, action, command, execRoot, outputFiles, context.getFileOutErr(), uploadAction);
+ actionKey, action, command, execRoot, outputFiles, context.getFileOutErr());
} catch (IOException e) {
if (verboseFailures) {
report(Event.debug("Upload to remote cache failed: " + e.getMessage()));
diff --git a/src/main/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCache.java b/src/main/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCache.java
index 6610e4b2d716cd..bb0e7d58b0e06b 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCache.java
@@ -95,11 +95,9 @@ public void upload(
Command command,
Path execRoot,
Collection<Path> files,
- FileOutErr outErr,
- boolean uploadAction)
- throws ExecException, IOException, InterruptedException {
+ FileOutErr outErr) throws ExecException, IOException, InterruptedException {
ActionResult.Builder result = ActionResult.newBuilder();
- upload(result, actionKey, action, command, execRoot, files, uploadAction);
+ upload(result, actionKey, action, command, execRoot, files, /* uploadAction= */ true);
if (outErr.getErrorPath().exists()) {
Digest stderr = uploadFileContents(outErr.getErrorPath());
result.setStderrDigest(stderr);
@@ -108,9 +106,7 @@ public void upload(
Digest stdout = uploadFileContents(outErr.getOutputPath());
result.setStdoutDigest(stdout);
}
- if (uploadAction) {
- blobStore.putActionResult(actionKey.getDigest().getHash(), result.build().toByteArray());
- }
+ blobStore.putActionResult(actionKey.getDigest().getHash(), result.build().toByteArray());
}
public void upload(
diff --git a/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/ExecutionServer.java b/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/ExecutionServer.java
index b9450244ccd976..b35e447fe59636 100644
--- a/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/ExecutionServer.java
+++ b/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/ExecutionServer.java
@@ -329,7 +329,7 @@ private ActionResult execute(Digest actionDigest, Path execRoot)
ActionResult.Builder result = ActionResult.newBuilder();
boolean setResult = exitCode == 0 && !action.getDoNotCache();
try {
- cache.upload(result, actionKey, action, command, execRoot, outputs, setResult);
+ cache.upload(result, actionKey, action, command, execRoot, outputs, setResult);
} catch (ExecException e) {
if (errStatus == null) {
errStatus =
| diff --git a/src/test/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCacheTests.java b/src/test/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCacheTests.java
index da5e8218dca333..f4f6026a3efec6 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCacheTests.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/AbstractRemoteActionCacheTests.java
@@ -732,8 +732,7 @@ void upload(
Command command,
Path execRoot,
Collection<Path> files,
- FileOutErr outErr,
- boolean uploadAction)
+ FileOutErr outErr)
throws ExecException, IOException, InterruptedException {
throw new UnsupportedOperationException();
}
diff --git a/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteCacheTest.java b/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteCacheTest.java
index 92894f8928cebf..b047842f024211 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/GrpcRemoteCacheTest.java
@@ -81,6 +81,7 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
+import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@@ -656,20 +657,18 @@ public void findMissingBlobs(
FindMissingBlobsRequest request,
StreamObserver<FindMissingBlobsResponse> responseObserver) {
assertThat(request.getBlobDigestsList())
- .containsExactly(fooDigest, quxDigest, barDigest);
+ .containsAllOf(fooDigest, quxDigest, barDigest);
// Nothing is missing.
responseObserver.onNext(FindMissingBlobsResponse.getDefaultInstance());
responseObserver.onCompleted();
}
});
- ActionResult.Builder result = ActionResult.newBuilder();
- client.upload(
- execRoot, null, null, null, ImmutableList.<Path>of(fooFile, barDir), outErr, false, result);
+ ActionResult result = uploadDirectory(client, ImmutableList.<Path>of(fooFile, barDir));
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputFilesBuilder().setPath("a/foo").setDigest(fooDigest);
expectedResult.addOutputDirectoriesBuilder().setPath("bar").setTreeDigest(barDigest);
- assertThat(result.build()).isEqualTo(expectedResult.build());
+ assertThat(result).isEqualTo(expectedResult.build());
}
@Test
@@ -686,19 +685,17 @@ public void testUploadDirectoryEmpty() throws Exception {
public void findMissingBlobs(
FindMissingBlobsRequest request,
StreamObserver<FindMissingBlobsResponse> responseObserver) {
- assertThat(request.getBlobDigestsList()).containsExactly(barDigest);
+ assertThat(request.getBlobDigestsList()).contains(barDigest);
// Nothing is missing.
responseObserver.onNext(FindMissingBlobsResponse.getDefaultInstance());
responseObserver.onCompleted();
}
});
- ActionResult.Builder result = ActionResult.newBuilder();
- client.upload(
- execRoot, null, null, null, ImmutableList.<Path>of(barDir), outErr, false, result);
+ ActionResult result = uploadDirectory(client, ImmutableList.<Path>of(barDir));
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputDirectoriesBuilder().setPath("bar").setTreeDigest(barDigest);
- assertThat(result.build()).isEqualTo(expectedResult.build());
+ assertThat(result).isEqualTo(expectedResult.build());
}
@Test
@@ -738,19 +735,27 @@ public void findMissingBlobs(
FindMissingBlobsRequest request,
StreamObserver<FindMissingBlobsResponse> responseObserver) {
assertThat(request.getBlobDigestsList())
- .containsExactly(quxDigest, barDigest, wobbleDigest);
+ .containsAllOf(quxDigest, barDigest, wobbleDigest);
// Nothing is missing.
responseObserver.onNext(FindMissingBlobsResponse.getDefaultInstance());
responseObserver.onCompleted();
}
});
- ActionResult.Builder result = ActionResult.newBuilder();
- client.upload(
- execRoot, null, null, null, ImmutableList.<Path>of(barDir), outErr, false, result);
+ ActionResult result = uploadDirectory(client, ImmutableList.of(barDir));
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputDirectoriesBuilder().setPath("bar").setTreeDigest(barDigest);
- assertThat(result.build()).isEqualTo(expectedResult.build());
+ assertThat(result).isEqualTo(expectedResult.build());
+ }
+
+ private ActionResult uploadDirectory(GrpcRemoteCache client, List<Path> outputs)
+ throws Exception {
+ ActionResult.Builder result = ActionResult.newBuilder();
+ Action action = Action.newBuilder().build();
+ ActionKey actionKey = DIGEST_UTIL.computeActionKey(action);
+ Command cmd = Command.newBuilder().build();
+ client.upload(execRoot, actionKey, action, cmd, outputs, outErr, result);
+ return result.build();
}
@Test
@@ -789,7 +794,6 @@ public void findMissingBlobs(
command,
ImmutableList.<Path>of(fooFile, barFile),
outErr,
- true,
result);
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputFilesBuilder().setPath("a/foo").setDigest(fooDigest);
@@ -840,7 +844,6 @@ public void findMissingBlobs(
command,
ImmutableList.<Path>of(fooFile, barFile),
outErr,
- true,
result);
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputFilesBuilder().setPath("a/foo").setDigest(fooDigest);
@@ -853,47 +856,6 @@ public void findMissingBlobs(
assertThat(numGetMissingCalls.get()).isEqualTo(4);
}
- @Test
- public void testUploadUploadsOnlyOutputs() throws Exception {
- final GrpcRemoteCache client = newClient();
- final Digest fooDigest =
- fakeFileCache.createScratchInput(ActionInputHelper.fromPath("a/foo"), "xyz");
- final Digest barDigest =
- fakeFileCache.createScratchInput(ActionInputHelper.fromPath("bar"), "x");
- serviceRegistry.addService(
- new ContentAddressableStorageImplBase() {
- @Override
- public void findMissingBlobs(
- FindMissingBlobsRequest request,
- StreamObserver<FindMissingBlobsResponse> responseObserver) {
- // This checks we will try to upload the actual outputs.
- assertThat(request.getBlobDigestsList()).containsExactly(fooDigest, barDigest);
- responseObserver.onNext(FindMissingBlobsResponse.getDefaultInstance());
- responseObserver.onCompleted();
- }
- });
- serviceRegistry.addService(
- new ActionCacheImplBase() {
- @Override
- public void updateActionResult(
- UpdateActionResultRequest request, StreamObserver<ActionResult> responseObserver) {
- fail("Update action result was expected to not be called.");
- }
- });
-
- ActionKey emptyKey = DIGEST_UTIL.computeActionKey(Action.getDefaultInstance());
- Path fooFile = execRoot.getRelative("a/foo");
- Path barFile = execRoot.getRelative("bar");
- client.upload(
- emptyKey,
- Action.getDefaultInstance(),
- Command.getDefaultInstance(),
- execRoot,
- ImmutableList.<Path>of(fooFile, barFile),
- outErr,
- false);
- }
-
@Test
public void testUploadCacheMissesWithRetries() throws Exception {
final GrpcRemoteCache client = newClient();
@@ -1014,8 +976,7 @@ public void onError(Throwable t) {
Command.getDefaultInstance(),
execRoot,
ImmutableList.<Path>of(fooFile, barFile, bazFile),
- outErr,
- true);
+ outErr);
// 4 times for the errors, 3 times for the successful uploads.
Mockito.verify(mockByteStreamImpl, Mockito.times(7))
.write(Mockito.<StreamObserver<WriteResponse>>anyObject());
diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java
index f0005a8bbe7e7a..c3defa1dd37344 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnCacheTest.java
@@ -239,8 +239,7 @@ public Void answer(InvocationOnMock invocation) {
any(Command.class),
any(Path.class),
any(Collection.class),
- any(FileOutErr.class),
- any(Boolean.class));
+ any(FileOutErr.class));
assertThat(result.setupSuccess()).isTrue();
assertThat(result.exitCode()).isEqualTo(0);
assertThat(result.isCacheHit()).isTrue();
@@ -279,8 +278,7 @@ public Void answer(InvocationOnMock invocation) {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
entry.store(result);
verify(remoteCache)
.upload(
@@ -289,8 +287,7 @@ public Void answer(InvocationOnMock invocation) {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
assertThat(progressUpdates)
.containsExactly(Pair.of(ProgressStatus.CHECKING_CACHE, "remote-cache"));
}
@@ -326,9 +323,8 @@ public void noCacheSpawns() throws Exception {
}
@Test
- public void noCacheSpawnsNoResultStore() throws Exception {
- // Only successful action results are uploaded to the remote cache. The artifacts, however,
- // are uploaded regardless.
+ public void failedActionsAreNotUploaded() throws Exception {
+ // Only successful action results are uploaded to the remote cache.
CacheHandle entry = cache.lookup(simpleSpawn, simplePolicy);
verify(remoteCache).getCachedActionResult(any(ActionKey.class));
assertThat(entry.hasResult()).isFalse();
@@ -340,15 +336,14 @@ public void noCacheSpawnsNoResultStore() throws Exception {
.build();
ImmutableList<Path> outputFiles = ImmutableList.of(fs.getPath("/random/file"));
entry.store(result);
- verify(remoteCache)
+ verify(remoteCache, never())
.upload(
any(ActionKey.class),
any(Action.class),
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(false));
+ eq(outErr));
assertThat(progressUpdates)
.containsExactly(Pair.of(ProgressStatus.CHECKING_CACHE, "remote-cache"));
}
@@ -373,8 +368,7 @@ public void printWarningIfUploadFails() throws Exception {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
entry.store(result);
verify(remoteCache)
@@ -384,8 +378,7 @@ public void printWarningIfUploadFails() throws Exception {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
assertThat(eventHandler.getEvents()).hasSize(1);
Event evt = eventHandler.getEvents().get(0);
@@ -428,8 +421,7 @@ public Void answer(InvocationOnMock invocation) {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
entry.store(result);
verify(remoteCache)
.upload(
@@ -438,8 +430,7 @@ public Void answer(InvocationOnMock invocation) {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
assertThat(eventHandler.getEvents()).hasSize(1);
Event evt = eventHandler.getEvents().get(0);
@@ -498,8 +489,7 @@ public Void answer(InvocationOnMock invocation) {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
entry.store(result);
verify(remoteCache)
.upload(
@@ -508,8 +498,7 @@ public Void answer(InvocationOnMock invocation) {
any(Command.class),
any(Path.class),
eq(outputFiles),
- eq(outErr),
- eq(true));
+ eq(outErr));
assertThat(progressUpdates)
.containsExactly(Pair.of(ProgressStatus.CHECKING_CACHE, "remote-cache"));
assertThat(eventHandler.getEvents()).isEmpty(); // no warning is printed.
diff --git a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java
index 93df866fd00026..6cfc635cd16471 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/RemoteSpawnRunnerTest.java
@@ -220,8 +220,7 @@ public void nonCachableSpawnsShouldNotBeCached_remote() throws Exception {
any(Command.class),
any(Path.class),
any(Collection.class),
- any(FileOutErr.class),
- any(Boolean.class));
+ any(FileOutErr.class));
verifyZeroInteractions(localRunner);
}
@@ -276,9 +275,8 @@ public void nonCachableSpawnsShouldNotBeCached_local() throws Exception {
@Test
@SuppressWarnings("unchecked")
- public void failedActionShouldOnlyUploadOutputs() throws Exception {
- // Test that the outputs of a failed locally executed action are uploaded to a remote cache,
- // but the action result itself is not.
+ public void failedLocalActionShouldNotBeUploaded() throws Exception {
+ // Test that the outputs of a locally executed action that failed are not uploaded.
options.remoteUploadLocalResults = true;
@@ -319,16 +317,15 @@ public void failedActionShouldOnlyUploadOutputs() throws Exception {
any(ActionKey.class),
any(Action.class),
any(Command.class),
- eq(true));
- verify(cache)
+ /* uploadLocalResults= */ eq(true));
+ verify(cache, never())
.upload(
any(ActionKey.class),
any(Action.class),
any(Command.class),
any(Path.class),
any(Collection.class),
- any(FileOutErr.class),
- eq(false));
+ any(FileOutErr.class));
}
@Test
@@ -405,8 +402,7 @@ public void printWarningIfCacheIsDown() throws Exception {
any(Command.class),
any(Path.class),
any(Collection.class),
- any(FileOutErr.class),
- eq(true));
+ any(FileOutErr.class));
SpawnResult res =
new SpawnResult.Builder()
diff --git a/src/test/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCacheTest.java b/src/test/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCacheTest.java
index d63cea5ff60503..3d75d1d467ac7c 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/SimpleBlobStoreActionCacheTest.java
@@ -35,7 +35,9 @@
import com.google.devtools.build.lib.remote.Retrier.Backoff;
import com.google.devtools.build.lib.remote.blobstore.ConcurrentMapBlobStore;
import com.google.devtools.build.lib.remote.util.DigestUtil;
+import com.google.devtools.build.lib.remote.util.DigestUtil.ActionKey;
import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
+import com.google.devtools.build.lib.util.io.OutErr;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
@@ -44,6 +46,7 @@
import com.google.devtools.common.options.Options;
import io.grpc.Context;
import java.io.IOException;
+import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
@@ -373,7 +376,7 @@ public void testUploadDirectory() throws Exception {
cmd,
execRoot,
ImmutableList.<Path>of(fooFile, barDir),
- true);
+ /* uploadAction= */ true);
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputFilesBuilder().setPath("a/foo").setDigest(fooDigest);
expectedResult.addOutputDirectoriesBuilder().setPath("bar").setTreeDigest(barDigest);
@@ -399,13 +402,12 @@ public void testUploadDirectoryEmpty() throws Exception {
final ConcurrentMap<String, byte[]> map = new ConcurrentHashMap<>();
final SimpleBlobStoreActionCache client = newClient(map);
- ActionResult.Builder result = ActionResult.newBuilder();
- client.upload(result, null, null, null, execRoot, ImmutableList.<Path>of(barDir), false);
+ ActionResult result = uploadDirectory(client, ImmutableList.<Path>of(barDir));
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputDirectoriesBuilder().setPath("bar").setTreeDigest(barDigest);
- assertThat(result.build()).isEqualTo(expectedResult.build());
+ assertThat(result).isEqualTo(expectedResult.build());
- assertThat(map.keySet()).containsExactly(barDigest.getHash());
+ assertThat(map.keySet()).contains(barDigest.getHash());
}
@Test
@@ -442,14 +444,23 @@ public void testUploadDirectoryNested() throws Exception {
quxFile.setExecutable(true);
final Path barDir = execRoot.getRelative("bar");
- ActionResult.Builder result = ActionResult.newBuilder();
- client.upload(result, null, null, null, execRoot, ImmutableList.<Path>of(barDir), false);
+ ActionResult result = uploadDirectory(client, ImmutableList.<Path>of(barDir));
ActionResult.Builder expectedResult = ActionResult.newBuilder();
expectedResult.addOutputDirectoriesBuilder().setPath("bar").setTreeDigest(barDigest);
- assertThat(result.build()).isEqualTo(expectedResult.build());
+ assertThat(result).isEqualTo(expectedResult.build());
assertThat(map.keySet())
- .containsExactly(wobbleDigest.getHash(), quxDigest.getHash(), barDigest.getHash());
+ .containsAllOf(wobbleDigest.getHash(), quxDigest.getHash(), barDigest.getHash());
+ }
+
+ private ActionResult uploadDirectory(SimpleBlobStoreActionCache client, List<Path> outputs)
+ throws Exception {
+ ActionResult.Builder result = ActionResult.newBuilder();
+ Action action = Action.newBuilder().build();
+ ActionKey actionKey = DIGEST_UTIL.computeActionKey(action);
+ Command cmd = Command.newBuilder().build();
+ client.upload(result, actionKey, action, cmd, execRoot, outputs, /* uploadAction= */ true);
+ return result.build();
}
@Test
diff --git a/src/test/shell/bazel/remote/remote_execution_test.sh b/src/test/shell/bazel/remote/remote_execution_test.sh
index 02570d95de4448..c49d1d54d20087 100755
--- a/src/test/shell/bazel/remote/remote_execution_test.sh
+++ b/src/test/shell/bazel/remote/remote_execution_test.sh
@@ -248,58 +248,20 @@ function is_file_uploaded() {
if [ -e "$cas_path/${h:0:64}" ]; then return 0; else return 1; fi
}
-function test_failing_cc_test_grpc_cache() {
+function test_failed_test_outputs_not_uploaded() {
+ # Test that outputs of a failed test/action are not uploaded to the remote
+ # cache. This is a regression test for https://github.com/bazelbuild/bazel/issues/7232
mkdir -p a
cat > a/BUILD <<EOF
package(default_visibility = ["//visibility:public"])
cc_test(
-name = 'test',
-srcs = [ 'test.cc' ],
+ name = 'test',
+ srcs = [ 'test.cc' ],
)
EOF
cat > a/test.cc <<EOF
#include <iostream>
int main() { std::cout << "Fail me!" << std::endl; return 1; }
-EOF
- bazel test \
- --remote_cache=localhost:${worker_port} \
- --test_output=errors \
- //a:test >& $TEST_log \
- && fail "Expected test failure" || true
- $(is_file_uploaded bazel-testlogs/a/test/test.log) \
- || fail "Expected test log to be uploaded to remote execution"
- $(is_file_uploaded bazel-testlogs/a/test/test.xml) \
- || fail "Expected test xml to be uploaded to remote execution"
-}
-
-function test_failing_cc_test_remote_spawn_cache() {
- mkdir -p a
- cat > a/BUILD <<EOF
-package(default_visibility = ["//visibility:public"])
-cc_test(
-name = 'test',
-srcs = [ 'test.cc' ],
-)
-EOF
- cat > a/test.cc <<EOF
-#include <iostream>
-int main() { std::cout << "Fail me!" << std::endl; return 1; }
-EOF
- bazel test \
- --remote_cache=localhost:${worker_port} \
- --test_output=errors \
- //a:test >& $TEST_log \
- && fail "Expected test failure" || true
- $(is_file_uploaded bazel-testlogs/a/test/test.log) \
- || fail "Expected test log to be uploaded to remote execution"
- $(is_file_uploaded bazel-testlogs/a/test/test.xml) \
- || fail "Expected test xml to be uploaded to remote execution"
- # Check that logs are uploaded regardless of the spawn being cacheable.
- # Re-running a changed test that failed once renders the test spawn uncacheable.
- rm -f a/test.cc
- cat > a/test.cc <<EOF
-#include <iostream>
-int main() { std::cout << "Fail me again!" << std::endl; return 1; }
EOF
bazel test \
--remote_cache=localhost:${worker_port} \
| val | train | 2019-01-25T10:22:12 | "2019-01-24T09:36:50Z" | buchgr | test |
bazelbuild/bazel/7259_8017 | bazelbuild/bazel | bazelbuild/bazel/7259 | bazelbuild/bazel/8017 | [
"timestamp(timedelta=1760.0, similarity=0.8561444596451517)"
] | 0dbbb4c07e17df4112ea89825da9dc3e9dbabbac | 34d9c6717593ca134713dcc46a44529bddd2ab66 | [
"I need this for properly fixing #6400 (support for grpc.enable_http_proxy channel arg was added in gRPC 1.14).",
"@tetromino this is about the gRPC Java dependency. I believe you need https://github.com/bazelbuild/bazel/issues/2804",
"The Google auth library in third_party/auth is quite old. It did not work with my company's proxy to GCS when I tried to use a GCS bucket as a remote cache. It needs to be updated.\r\n",
"See https://github.com/bazelbuild/bazel/pull/8017"
] | [] | "2019-04-12T10:52:54Z" | [
"P2",
"type: process",
"team-Remote-Exec"
] | remote: update grpc and google auth library to latest | [
"third_party/BUILD"
] | [
"third_party/BUILD"
] | [] | diff --git a/third_party/BUILD b/third_party/BUILD
index c927b759969b42..90ab565687731f 100644
--- a/third_party/BUILD
+++ b/third_party/BUILD
@@ -226,8 +226,8 @@ java_import(
java_import(
name = "auth",
jars = [
- "auth/google-auth-library-oauth2-http-0.6.0.jar",
- "auth/google-auth-library-credentials-0.6.0.jar",
+ "auth/google-auth-library-oauth2-http-0.15.0.jar",
+ "auth/google-auth-library-credentials-0.15.0.jar",
],
runtime_deps = [
":api_client",
| null | train | train | 2019-04-12T12:33:51 | "2019-01-25T16:56:01Z" | buchgr | test |
|
bazelbuild/bazel/7297_7299 | bazelbuild/bazel | bazelbuild/bazel/7297 | bazelbuild/bazel/7299 | [
"timestamp(timedelta=36669.0, similarity=0.8402573714705566)"
] | ee1107a6ada146666f50aa7e834e9f954153de32 | e77af453c4fae5ad07175d871f48f4751446abda | [
"Hmm, I thought I had updated it: 9259683c6b460629d1ca83759ce26fa76839558d\r\n\r\nAre you building with any `--incompatible_` flags?",
"I think the problem is that there's also `third_party/java/java_tools/turbine_deploy.jar`.",
"I hacked up an integration test to demonstrate the problem:\r\n```\r\n$ git diff\r\ndiff --git a/src/test/shell/integration/java_integration_test.sh b/src/test/shell/integration/java_integration_test.sh\r\nindex 9435e13101..fc0790afea 100755\r\n--- a/src/test/shell/integration/java_integration_test.sh\r\n+++ b/src/test/shell/integration/java_integration_test.sh\r\n@@ -634,6 +634,7 @@ java_library(name = 'processor_dep',\r\n \r\n java_plugin(name = 'processor',\r\n processor_class = 'test.processor.Processor',\r\n+ generates_api = True,\r\n deps = [ ':annotation', ':processor_dep' ],\r\n srcs = [ 'Processor.java' ])\r\n EOF\r\n@@ -695,6 +696,10 @@ java_library(name = 'client',\r\n srcs = [ 'ProcessorClient.java' ],\r\n deps = [ '//$pkg/java/test/processor:annotation' ],\r\n plugins = [ '//$pkg/java/test/processor:processor' ])\r\n+\r\n+java_binary(name = 'bin',\r\n+ srcs = ['MyBinary.java'],\r\n+ deps = [':client'])\r\n EOF\r\n \r\n cat >$pkg/java/test/client/ProcessorClient.java <<EOF\r\n@@ -704,11 +709,19 @@ import test.processor.TestAnnotation;\r\n class ProcessorClient { }\r\n EOF\r\n \r\n- bazel build ${bazel_opts[@]+\"${bazel_opts[@]}\"} //$pkg/java/test/client:client --use_ijars || fail \"build failed\"\r\n+ cat > $pkg/java/test/client/MyBinary.java <<EOF\r\n+class MyBinary {\r\n+ public static void main(String[] args) {\r\n+ new ProcessorClient();\r\n+ }\r\n+}\r\n+EOF\r\n+\r\n+ bazel build ${bazel_opts[@]+\"${bazel_opts[@]}\"} //$pkg/java/test/client:bin || fail \"build failed\"\r\n unzip -l ${PRODUCT_NAME}-bin/$pkg/java/test/client/libclient.jar > $TEST_log\r\n expect_log \" test/Generated.class\" \"missing class file from annotation processing\"\r\n \r\n- bazel build ${bazel_opts[@]+\"${bazel_opts[@]}\"} //$pkg/java/test/client:libclient-src.jar --use_ijars \\\r\n+ bazel build ${bazel_opts[@]+\"${bazel_opts[@]}\"} //$pkg/java/test/client:libclient-src.jar \\\r\n || fail \"build failed\"\r\n unzip -l ${PRODUCT_NAME}-bin/$pkg/java/test/client/libclient-src.jar > $TEST_log\r\n expect_log \" test/Generated.java\" \"missing source file from annotation processing\"\r\n$ bazel test //src/test/shell/integration:java_integration_test --test_filter test_java_plugin\r\n```",
"Thanks, I'd forgotten about #7196.\r\n\r\nIt's concerning that there apparently aren't any integration tests using `generates_api`.\r\n\r\n@lberki are there plans for more automation around `third_party/java/java_tools/update_java_tools.sh`?",
"Closing since 92adff893fbd185269bf734abf4d3b12d3117ebc fixed the immediate problem. It does seem like there should be an integration test for javac turbine.",
"I'm getting this error on 0.23.0 with `--all_incompatible_changes`."
] | [
"nit: Isn't this duplicated from the 0.22 (see line 38 in the same file?)",
"The file didn't have a trailing newline, the only thing that changed on this line was trailing whitespace.",
"Oh, also, I think the duplication with 38 is deliberate? The script is printing the list of files that change in each update, and this file changed in this update and the one below."
] | "2019-01-30T06:07:33Z" | [
"team-Rules-Java"
] | javac turbine needs to be updated | Since d42a026e63872efb9f9f3879248ddf4431c65d20, I've been seeing failures like this:
```
java -Xverify:none -Xbootclasspath/p:external/bazel_tools/third_party/java/jdk/langtools/javac-9+181-r4173-1.jar -jar external/bazel_tools/tools/jdk/turbine_deploy.jar --output ... (remaining 221 argument(s) skipped)
Use --sandbox_debug to see verbose messages from the sandbox.
Exception in thread "main" java.lang.IllegalArgumentException: unknown option: --reduce_classpath
at com.google.turbine.options.TurbineOptionsParser.parse(TurbineOptionsParser.java:123)
at com.google.turbine.options.TurbineOptionsParser.parse(TurbineOptionsParser.java:53)
at com.google.turbine.options.TurbineOptionsParser.parse(TurbineOptionsParser.java:41)
at com.google.devtools.build.java.turbine.javac.JavacTurbine.main(JavacTurbine.java:81)
``` | [
"third_party/java/java_tools/README.md",
"third_party/java/java_tools/update_java_tools.sh"
] | [
"third_party/java/java_tools/README.md",
"third_party/java/java_tools/update_java_tools.sh"
] | [] | diff --git a/third_party/java/java_tools/README.md b/third_party/java/java_tools/README.md
index 408669c11285fc..fd029df6fe0751 100644
--- a/third_party/java/java_tools/README.md
+++ b/third_party/java/java_tools/README.md
@@ -21,4 +21,20 @@ third_party/java/java_tools/SingleJar_deploy.jar
The following tools were built with bazel 0.21.0 at commit 019f13b64630ea7e7837a2ed8b664c4262322b1c by running:
$ third_party/java/java_tools/update_java_tools.sh
-third_party/java/java_tools/jarjar_command_deploy.jar
\ No newline at end of file
+third_party/java/java_tools/jarjar_command_deploy.jar
+
+The following tools were built with bazel 0.22.0 at commit ee1107a6ada146666f50aa7e834e9f954153de32
+by running:
+$ third_party/java/java_tools/update_java_tools.sh
+
+third_party/java/java_tools/turbine_deploy.jar
+third_party/java/java_tools/ExperimentalRunner_deploy.jar
+third_party/java/java_tools/bazel-singlejar_deploy.jar
+third_party/java/java_tools/GenClass_deploy.jar
+third_party/java/java_tools/VanillaJavaBuilder_deploy.jar
+third_party/java/java_tools/JacocoCoverage_jarjar_deploy.jar
+third_party/java/java_tools/turbine_direct_binary_deploy.jar
+third_party/java/java_tools/JavaBuilder_deploy.jar
+third_party/java/java_tools/jarjar_command_deploy.jar
+third_party/java/java_tools/Runner_deploy.jar
+
diff --git a/third_party/java/java_tools/update_java_tools.sh b/third_party/java/java_tools/update_java_tools.sh
index c77013c3c2855f..50be12fa3689ec 100755
--- a/third_party/java/java_tools/update_java_tools.sh
+++ b/third_party/java/java_tools/update_java_tools.sh
@@ -99,12 +99,13 @@ done
if [[ ${#updated_tools[@]} -gt 0 ]]; then
bazel_version=$(bazel version | grep "Build label" | cut -d " " -f 3)
git_head=$(git rev-parse HEAD)
- echo ""
- echo "Please copy/paste the following into third_party/java/java_tools/README.md:"
- echo ""
- echo "The following tools were built with bazel $bazel_version at commit $git_head \
+ cat >>third_party/java/java_tools/README.md <<EOL
+
+The following tools were built with bazel $bazel_version at commit $git_head
by running:
$ third_party/java/java_tools/update_java_tools.sh $@
-"
- ( IFS=$'\n'; echo "${updated_tools[*]}" )
+
+$( IFS=$'\n'; echo "${updated_tools[*]}" )
+
+EOL
fi
| null | train | train | 2019-01-30T00:33:53 | "2019-01-29T22:55:30Z" | benjaminp | test |
bazelbuild/bazel/7331_7491 | bazelbuild/bazel | bazelbuild/bazel/7331 | bazelbuild/bazel/7491 | [
"timestamp(timedelta=0.0, similarity=0.8577877964005944)"
] | 1898f41b807d846d3553db645e6d718ba2348a60 | ae3cd77654e233ee82ac066a54b283016afbf98b | [
"Not team-Starlark?\r\nI'm tagging @c-parsons since `{s,}he` has opened the original deprecation issue. ",
"It's probably my fault, sorry about that.\r\nI'm looking at it.",
"@laurentlb I guess you did too much refactoring on https://github.com/bazelbuild/bazel/commit/2b3ad18eec4e6b968d840777249c809e478b2e13 and removed the warning with the flag by mistake. "
] | [] | "2019-02-21T14:44:22Z" | [
"P1",
"bad error messaging"
] | bad error messaging when using the deprecated `PACKAGE_NAME` or `REPOSITORY_NAME` | ### Description of the problem / feature request:
Instead of a nice deprecation warning / error, I got this ambiguous error: `builtin variable 'REPOSITORY_NAME' is referenced before assignment.`.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Use `REPOSITORY_NAME` or `PACKAGE_NAME`. With master too.
### What operating system are you running Bazel on?
Linux
### What's the output of `bazel info release`?
release 0.22.0- (@non-git)
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
Official archlinux release
### Have you found anything relevant by searching the web?
[This deprecation thread](https://github.com/bazelbuild/bazel/issues/5827) | [
"src/main/java/com/google/devtools/build/lib/syntax/Identifier.java"
] | [
"src/main/java/com/google/devtools/build/lib/syntax/Identifier.java"
] | [
"src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/syntax/Identifier.java b/src/main/java/com/google/devtools/build/lib/syntax/Identifier.java
index 98e7d5b69ba855..a246ee5e93ecc8 100644
--- a/src/main/java/com/google/devtools/build/lib/syntax/Identifier.java
+++ b/src/main/java/com/google/devtools/build/lib/syntax/Identifier.java
@@ -107,9 +107,12 @@ Object doEval(Environment env) throws EvalException {
if (result == null) {
// Since Scope was set, we know that the variable is defined in the scope.
// However, the assignment was not yet executed.
- throw new EvalException(
- getLocation(),
- scope.getQualifier() + " variable '" + name + "' is referenced before assignment.");
+ EvalException e = getSpecialException();
+ throw e != null
+ ? e
+ : new EvalException(
+ getLocation(),
+ scope.getQualifier() + " variable '" + name + "' is referenced before assignment.");
}
return result;
@@ -125,11 +128,37 @@ public Kind kind() {
return Kind.IDENTIFIER;
}
+ /**
+ * Exception to provide a better error message for using PACKAGE_NAME or REPOSITORY_NAME.
+ */
+ private EvalException getSpecialException() {
+ if (name.equals("PACKAGE_NAME")) {
+ return new EvalException(
+ getLocation(),
+ "The value 'PACKAGE_NAME' has been removed in favor of 'package_name()', "
+ + "please use the latter ("
+ + "https://docs.bazel.build/versions/master/skylark/lib/native.html#package_name). ");
+ }
+ if (name.equals("REPOSITORY_NAME")) {
+ return new EvalException(
+ getLocation(),
+ "The value 'REPOSITORY_NAME' has been removed in favor of 'repository_name()', "
+ + "please use the latter ("
+ + "https://docs.bazel.build/versions/master/skylark/lib/native.html#repository_name).");
+ }
+ return null;
+ }
+
EvalException createInvalidIdentifierException(Set<String> symbols) {
if (name.equals("$error$")) {
return new EvalException(getLocation(), "contains syntax error(s)", true);
}
+ EvalException e = getSpecialException();
+ if (e != null) {
+ return e;
+ }
+
String suggestion = SpellChecker.didYouMean(name, symbols);
return new EvalException(getLocation(), "name '" + name + "' is not defined" + suggestion);
}
| diff --git a/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java b/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java
index 354fb0c58be645..239fcba012ec0c 100644
--- a/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/packages/PackageFactoryTest.java
@@ -240,6 +240,16 @@ public void testPrefixBetweenRules2() throws Exception {
"output file 'a' of rule 'kiwi2' conflicts " + "with output file 'a/b' of rule 'kiwi1'");
}
+ @Test
+ public void testPackageConstantIsForbidden() throws Exception {
+ events.setFailFast(false);
+ Path buildFile = scratch.file("/pina/BUILD", "cc_library(name=PACKAGE_NAME + '-colada')");
+ packages.createPackage(
+ "pina",
+ RootedPath.toRootedPath(root, buildFile));
+ events.assertContainsError("The value 'PACKAGE_NAME' has been removed");
+ }
+
@Test
public void testPackageNameFunction() throws Exception {
Path buildFile = scratch.file("/pina/BUILD", "cc_library(name=package_name() + '-colada')");
@@ -252,6 +262,19 @@ public void testPackageNameFunction() throws Exception {
assertThat(Sets.newHashSet(pkg.getTargets(Rule.class)).size()).isSameAs(1);
}
+ @Test
+ public void testPackageConstantInExternalRepositoryIsForbidden() throws Exception {
+ events.setFailFast(false);
+ Path buildFile =
+ scratch.file(
+ "/external/a/b/BUILD", "genrule(name='c', srcs=[], outs=['ao'], cmd=REPOSITORY_NAME)");
+ packages.createPackage(
+ PackageIdentifier.create("@a", PathFragment.create("b")),
+ RootedPath.toRootedPath(root, buildFile),
+ events.reporter());
+ events.assertContainsError("The value 'REPOSITORY_NAME' has been removed");
+ }
+
@Test
public void testPackageFunctionInExternalRepository() throws Exception {
Path buildFile =
| train | train | 2019-02-21T15:42:28 | "2019-02-02T06:40:08Z" | Reflexe | test |
bazelbuild/bazel/7349_7350 | bazelbuild/bazel | bazelbuild/bazel/7349 | bazelbuild/bazel/7350 | [
"timestamp(timedelta=0.0, similarity=0.9373832826710414)"
] | 0cd3594dcabd508636d6f3af8867de4d1a044aac | eeea9db75e3ed152a761879968836277916c550f | [] | [
"when does this happen?",
"If `path` itself was empty.\r\nShall I move this check above the conversion?",
"Yes please.",
"Done."
] | "2019-02-05T10:58:49Z" | [
"type: bug",
"P1",
"area-Windows",
"team-OSS"
] | Windows, java_binary: MakeDirectoriesW fail in launcher | ### Description of the problem / feature request:
If you copy a java_binary's outputs somewhere out of bazel-bin and try to run it from the current working directory, the launcher will fail with a MakeDirectoriesW error.
BUILD:
```
java_binary(
name = "foo",
srcs = ["Main.java"],
main_class = "Main",
)
```
Main.java
```
public class Main {
public static void main(String[] args) {
System.out.println("helloworld");
}
}
```
Then copy `bazel-bin\foo.exe`, `bazel-bin\foo.exe.runfiles_manifest`, and `bazel-bin\foo.jar` into `c:\tmp1\launcher_test`, and run foo.exe:
```
C:\tmp1\launcher_test>foo.exe --classpath_limit=0 --print_launcher_command
FATAL: MakeDirectoriesW(foo.exe.j) could not find dirname: (error: 2): The system cannot find the file specified.
```
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
0.22.0 | [
"src/main/cpp/util/file_windows.cc"
] | [
"src/main/cpp/util/file_windows.cc"
] | [] | diff --git a/src/main/cpp/util/file_windows.cc b/src/main/cpp/util/file_windows.cc
index cc2225ed37ae72..a71db514216aca 100644
--- a/src/main/cpp/util/file_windows.cc
+++ b/src/main/cpp/util/file_windows.cc
@@ -755,22 +755,28 @@ void SyncFile(const string& path) {
}
bool MakeDirectoriesW(const wstring& path, unsigned int mode) {
- if (path.empty()) {
+ std::wstring abs_path;
+ std::string error;
+ if (abs_path.empty()) {
return false;
}
- if (IsRootDirectoryW(path) || IsDirectoryW(path)) {
+ if (!AsAbsoluteWindowsPath(path, &abs_path, &error)) {
+ BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR) << "MakeDirectoriesW("
+ << blaze_util::WstringToString(path) << "): " << error;
+ }
+ if (IsRootDirectoryW(abs_path) || IsDirectoryW(abs_path)) {
return true;
}
- wstring parent = SplitPathW(path).first;
+ wstring parent = SplitPathW(abs_path).first;
if (parent.empty()) {
- // Since `path` is not a root directory, there should have been at least one
- // directory above it.
+ // Since `abs_path` is not a root directory, there should have been at least
+ // one directory above it.
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
- << "MakeDirectoriesW(" << blaze_util::WstringToString(path)
+ << "MakeDirectoriesW(" << blaze_util::WstringToString(abs_path)
<< ") could not find dirname: " << GetLastErrorString();
}
return MakeDirectoriesW(parent, mode) &&
- ::CreateDirectoryW(path.c_str(), NULL) == TRUE;
+ ::CreateDirectoryW(abs_path.c_str(), NULL) == TRUE;
}
bool MakeDirectories(const string& path, unsigned int mode) {
| null | train | train | 2019-02-05T11:51:41 | "2019-02-05T10:50:39Z" | laszlocsomor | test |
bazelbuild/bazel/7370_7484 | bazelbuild/bazel | bazelbuild/bazel/7370 | bazelbuild/bazel/7484 | [
"timestamp(timedelta=1.0, similarity=0.8840656578174207)"
] | 53b5170eadaf60ec20a0595da6347a791d680aeb | 85b23f4b8639e35d2c440d081130ed0e401e01d8 | [
"If I'm understanding my build errors correctly, this change re-broke the py2/3 compatibility on make_deb.py that #6818 had previously fixed.\r\n\r\n```\r\n File \".../bazel-out/k8-opt/bin/external/bazel_tools/tools/build_defs/pkg/make_deb.runfiles/bazel_tools/tools/build_defs/pkg/make_deb.py\", line 301, in GetFlagValue\r\n flagvalue = flagvalue.decode('utf-8')\r\nAttributeError: 'str' object has no attribute 'decode'\r\n```\r\n\r\nIt's possible that the toolchain changes in 0.25.0 are also at fault and/or the only problem, but with the binary tagged `PY2AND3`, the code doesn't look correct to me on first read.",
"See https://github.com/bazelbuild/rules_pkg/issues/35"
] | [
"Can you add \r\n # -*- coding: utf-8 -*-\r\nat the top of this file and build_test.sh ",
"I think it is safer to do the decode at the top of the method on the incoming value.\r\nOr, better yet, the transform from bytes to unicode string should happen in GetFlagValue.",
"If you would like to do future maintainers a favor, you could clean up the formatting on the block above this.\r\nThe current formatting is an unreadable mess. How about.\r\n\r\n changesdata = ''.join(\r\n MakeDebianControlField(*x)\r\n for x in [\r\n ('Format', '1.8'),\r\n ('Date', time.ctime(timestamp)),\r\n ('Source', package),\r\n ('Binary', package),\r\n ('Architecture', architecture),\r\n ('Version', version),\r\n ('Distribution', distribution),\r\n ('Urgency', urgency),\r\n ('Maintainer', maintainer),\r\n ('Changed-By', maintainer),\r\n ('Description', '\\n%s - %s' % (package, short_description)),\r\n ('Changes', (\r\n '\\n%s (%s) %s; urgency=%s'\r\n '\\nChanges are tracked in revision control.') % (\r\n package, version, distribution, urgency)),\r\n ('Files', '\\n' + ' '.join(\r\n [checksums['md5'], debsize, section, priority, deb_basename])),\r\n ('Checksums-Sha1', '\\n' + ' '.join(\r\n [checksums['sha1'], debsize, deb_basename])),\r\n ('Checksums-Sha256', '\\n' + ' '.join(\r\n [checksums['sha256'], debsize, deb_basename]))])\r\n\r\nOr even:\r\n changesdata = ''.join(\r\n MakeDebianControlField('Format', '1.8'),\r\n MakeDebianControlField('Date', time.ctime(timestamp)),\r\n ...\r\n\r\nIf not, I'll clean it up after.",
"The decode() could be at line 295 \r\n return flagvalue.decode('utf-8')\r\n\r\nBut also we might want to add it at line 289\r\n flagvalue = flagvalue.decode('utf-8')\r\nso that an @file usage can have a utf-8 path",
"Thanks for the review aiuto! Apologies it's taken me so long to get back to you. I'd be happy to add the encoding.\r\n\r\nI was seeing `# -*- coding: utf-8 -*-` in other places in the codebase. (Mainly third_party/protobuf) Is that preferred or is `# -- coding: utf-8 --` alright?",
"That's fair. I'm happy to do it. I was trying to keep my initial changes minimal so it was easier to review.\r\n\r\nI like the below approach so will go ahead and do that unless you prefer the other method:\r\n```python\r\nchangesdata = ''.join([\r\nMakeDebianControlField(...),\r\nMakeDebianControlField(...),\r\n...\r\n])\r\n```",
"Sounds good. I'll play around with this a little. I had a friend suggest setting `changesdata = u''` and `changesfile = u''` as well so they won't have to be overridden at each access point.",
"-*-. My typo the firs time.",
"You might as well do the encoding just once. ",
"That works for me too. It is easier to follow than \"MakeDebianControlField(*x)\"",
"Doing some testing - it seems that doing:\r\n```python\r\nif flagvalue:\r\n flagvalue = flagvalue.decode('utf-8')\r\n ...\r\n```\r\nand removing the decode in: `return result.decode('utf-8').replace(...) + '\\n\\'` on line 145 will cause UnicodeDecodeErrors if one of the fields that doesn't use GetFlagValue(s) in CreateDeb (line 306) contains a utf-8 variable.\r\n\r\nI could move the `flagvalue = flagvalue.decode('utf-8')` line further into the if statement nest so the `@file` directive will get it and leave the rest the same.\r\n",
"I agree. However, I get a TypeError from the `f.addfile(... BytesIO(controlfile))` line if I do the encoding at the top of the method. It will work if I do:\r\n```python\r\ncontrolfile = ''\r\n for values in DEBIAN_FIELDS:\r\n fieldname = values[0]\r\n key = fieldname[0].lower() + fieldname[1:].replace('-', '')\r\n if values[1] or (key in kwargs and kwargs[key]):\r\n controlfile += MakeDebianControlField(fieldname, kwargs[key], values[2])\r\n controlfile = controlfile.encode('utf-8')\r\n...\r\n```\r\nand remove the encode() calls further down.\r\n\r\nDo you have any idea why that would be? My guess would be the `controlfile += MakeDebianControlField(...)` line in the `for` loop but I'm unsure why that would override the encoding if it's set earlier. It seems like both this TypeError and the issues I run into `MakeDebianControlField` function result from the `installed_size` flag.",
"I think that is worth it. We have other outstanding bugs for not supporting UTF-8 file paths. So GetFlagValue needs to do that. AND the content should be interpreted as utf-8 encoded.\r\n\r\nBut I think I have the solution to what you observed. We upgrade str to unicode str in MakeDebianControlField\r\nI changed one of the non GetFlagValue() attributes to be unicode also, so the test would have a that case too.\r\n maintainer = \"somé[email protected]\",\r\n\r\nIf you have extra tests, I would like to try them against my suggestion. If you think that change works. I also have it patched on top of your PR, so I could to the merge of yours.\r\n\r\nFull diff: https://github.com/bazelbuild/bazel/compare/master...aiuto:deb\r\n\r\ninline diff\r\n\r\n*** 133,148 ****\r\n def MakeDebianControlField(name, value, wrap=False):\r\n \"\"\"Add a field to a debian control file.\"\"\"\r\n result = name + ': '\r\n if type(value) is list:\r\n! value = ', '.join(value)\r\n if wrap:\r\n! result += ' '.join(value.split('\\n'))\r\n result = textwrap.fill(result,\r\n break_on_hyphens=False,\r\n break_long_words=False)\r\n else:\r\n result += value\r\n! return result.decode('utf-8').replace('\\n', '\\n ') + '\\n'\r\n \r\n \r\n def CreateDebControl(extrafiles=None, **kwargs):\r\n--- 133,150 ----\r\n def MakeDebianControlField(name, value, wrap=False):\r\n \"\"\"Add a field to a debian control file.\"\"\"\r\n result = name + ': '\r\n+ if type(value) is str:\r\n+ value = value.decode('utf-8')\r\n if type(value) is list:\r\n! value = u', '.join(value)\r\n if wrap:\r\n! result += u' '.join(value.split('\\n'))\r\n result = textwrap.fill(result,\r\n break_on_hyphens=False,\r\n break_long_words=False)\r\n else:\r\n result += value\r\n! return result.replace('\\n', '\\n ') + '\\n'\r\n \r\n \r\n def CreateDebControl(extrafiles=None, **kwargs):\r\n***************\r\n*** 295,303 ****\r\n \r\n def GetFlagValue(flagvalue, strip=True):\r\n if flagvalue:\r\n if flagvalue[0] == '@':\r\n with open(flagvalue[1:], 'r') as f:\r\n! flagvalue = f.read()\r\n if strip:\r\n return flagvalue.strip()\r\n return flagvalue\r\n--- 297,306 ----\r\n \r\n def GetFlagValue(flagvalue, strip=True):\r\n if flagvalue:\r\n+ flagvalue = flagvalue.decode('utf-8')\r\n if flagvalue[0] == '@':\r\n with open(flagvalue[1:], 'r') as f:\r\n! flagvalue = f.read().decode('utf-8')\r\n if strip:\r\n return flagvalue.strip()\r\n return flagvalue\r\n\r\n\r\n\r\n",
"Sounds good - if there are other outstanding utf-8 filepath bugs it'd be worth it to deal with that while we're here. \r\n\r\nAmusingly - that was the exact test case I was using. I'd be fine with you merging on top of my commits. I guess I didn't go far enough in changing things to unicode strings!\r\n\r\nThe one other thing I was noticing was that if the controlfile isn't utf-8 encoded when determining the size content will be dropped from it. I've been using `expect_log \"Built-Using: Bazel\"` to test for that as that seems to usually be the last line in the controlfile. However, I'm not sure how robust of a test that is.",
"Yes. I saw your fix for that. I'll try to commit this now. Having flakiness with the windows/jdk8 tests. So this may take a few tries to catch a clean build.",
"Looks like it passed. Thanks for the review!"
] | "2019-02-20T22:31:58Z" | [
"P4",
"team-Rules-Server"
] | pkg_deb fails when control fields contain unicode/utf-8 encoded characters | ### Description of the problem:
pkg_deb fails when control fields contain unicode characters or the contents of utf-8 encoded files.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Using the following:
```shell
~/utf8-test$ ls
BUILD WORKSPACE
```
WORKSPACE
```
```
BUILD
```
load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar", "pkg_deb")
pkg_tar(
name = "data",
)
pkg_deb(
name = "utf8-test",
data = ":data",
maintainer = "foo",
description = "Unicode symbols ®, Δ, Й, ק ,م, ๗, あ, 叶, 葉, 말, ü and é",
package = "utf8-test",
version = "1.0",
)
```
You will get an error message like the following:
```
~/utf8-test$ bazel build :utf8-test --verbose_failures
INFO: Invocation ID: 4831418c-4a4a-41f7-abf4-d18b50934194
INFO: Analysed target //:utf8-test (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
ERROR: /home/user/utf8-test/BUILD:7:1: MakeDeb utf8-test_1.0_all.deb failed (Exit 1) make_deb failed: error executing command
(cd /home/user/.cache/bazel/_bazel_user/e6e7bd4474c6bcca1dea3235a205b76e/execroot/__main__ && \
exec env - \
bazel-out/host/bin/external/bazel_tools/tools/build_defs/pkg/make_deb '--output=bazel-out/k8-fastbuild/bin/utf8-test_1.0_all.deb' '--changes=bazel-out/k8-fastbuild/bin/utf8-test_1.0_all.changes' '--data=bazel-out/k8-fastbuild/bin/data.tar' '--package=utf8-test' '--architecture=all' '--maintainer=foo' '--version=1.0' '--description=Reserved symbol®' '--distribution=unstable' '--urgency=medium')
Execution platform: @bazel_tools//platforms:host_platform
Use --sandbox_debug to see verbose messages from the sandbox: make_deb failed: error executing command
(cd /home/user/.cache/bazel/_bazel_user/e6e7bd4474c6bcca1dea3235a205b76e/execroot/__main__ && \
exec env - \
bazel-out/host/bin/external/bazel_tools/tools/build_defs/pkg/make_deb '--output=bazel-out/k8-fastbuild/bin/utf8-test_1.0_all.deb' '--changes=bazel-out/k8-fastbuild/bin/utf8-test_1.0_all.changes' '--data=bazel-out/k8-fastbuild/bin/data.tar' '--package=utf8-test' '--architecture=all' '--maintainer=foo' '--version=1.0' '--description=Reserved symbol®' '--distribution=unstable' '--urgency=medium')
Execution platform: @bazel_tools//platforms:host_platform
Use --sandbox_debug to see verbose messages from the sandbox
Traceback (most recent call last):
File "/home/user/.cache/bazel/_bazel_user/e6e7bd4474c6bcca1dea3235a205b76e/sandbox/linux-sandbox/1/execroot/__main__/bazel-out/host/bin/external/bazel_tools/tools/build_defs/pkg/make_deb.runfiles/bazel_tools/tools/build_defs/pkg/make_deb.py", line 342, in <module>
main(FLAGS(sys.argv))
File "/home/user/.cache/bazel/_bazel_user/e6e7bd4474c6bcca1dea3235a205b76e/sandbox/linux-sandbox/1/execroot/__main__/bazel-out/host/bin/external/bazel_tools/tools/build_defs/pkg/make_deb.runfiles/bazel_tools/tools/build_defs/pkg/make_deb.py", line 328, in main
installedSize=GetFlagValue(FLAGS.installed_size))
File "/home/user/.cache/bazel/_bazel_user/e6e7bd4474c6bcca1dea3235a205b76e/sandbox/linux-sandbox/1/execroot/__main__/bazel-out/host/bin/external/bazel_tools/tools/build_defs/pkg/make_deb.runfiles/bazel_tools/tools/build_defs/pkg/make_deb.py", line 195, in CreateDeb
control = CreateDebControl(extrafiles=extrafiles, **kwargs)
File "/home/user/.cache/bazel/_bazel_user/e6e7bd4474c6bcca1dea3235a205b76e/sandbox/linux-sandbox/1/execroot/__main__/bazel-out/host/bin/external/bazel_tools/tools/build_defs/pkg/make_deb.runfiles/bazel_tools/tools/build_defs/pkg/make_deb.py", line 163, in CreateDebControl
f.addfile(tarinfo, fileobj=BytesIO(controlfile.encode('utf-8')))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 136: ordinal not in range(128)
Target //:utf8-test failed to build
INFO: Elapsed time: 0.349s, Critical Path: 0.15s
INFO: 0 processes.
FAILED: Build did NOT complete successfully
```
### What operating system are you running Bazel on?
Ubuntu 16.04 & 18.04
### What's the output of `bazel info release`?
`release 0.22.0`
### Have you found anything relevant by searching the web?
No
### Any other information, logs, or outputs that you want to share?
Bazel used to work with the "®" symbol in the description field. It seems like the changes to make pkg defs Python 2/3 compatible here: https://github.com/bazelbuild/bazel/commit/6fff4da5f5e436551aa9294b58960da1d64af39a may have introduced the bug. Based on some initial StackOverflow searching it seems like using .decode("utf-8") on the input may be necessary. https://stackoverflow.com/a/16508962 If it's alright, I'd be happy to submit a patch on `tools/build_defs/pkg/make_deb.py` along those lines.
| [
"tools/build_defs/pkg/BUILD",
"tools/build_defs/pkg/build_test.sh",
"tools/build_defs/pkg/make_deb.py"
] | [
"tools/build_defs/pkg/BUILD",
"tools/build_defs/pkg/build_test.sh",
"tools/build_defs/pkg/make_deb.py"
] | [] | diff --git a/tools/build_defs/pkg/BUILD b/tools/build_defs/pkg/BUILD
index f3c8b4c86e995f..c7e9e26997d5a6 100644
--- a/tools/build_defs/pkg/BUILD
+++ b/tools/build_defs/pkg/BUILD
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
licenses(["notice"]) # Apache 2.0
filegroup(
@@ -213,7 +214,7 @@ pkg_deb(
"dep1",
"dep2",
],
- description = "toto",
+ description = "toto ®, Й, ק ,م, ๗, あ, 叶, 葉, 말, ü and é",
distribution = "trusty",
maintainer = "[email protected]",
make_deb = ":make_deb",
diff --git a/tools/build_defs/pkg/build_test.sh b/tools/build_defs/pkg/build_test.sh
index 99bae8e8fcbfa6..a1d920e8a24573 100755
--- a/tools/build_defs/pkg/build_test.sh
+++ b/tools/build_defs/pkg/build_test.sh
@@ -1,4 +1,5 @@
#!/bin/bash
+# -*- coding: utf-8 -*-
# Copyright 2015 The Bazel Authors. All rights reserved.
#
@@ -181,7 +182,7 @@ function test_deb() {
check_eq "-rwxr-xr-x" "$(get_deb_permission test-deb.deb ./usr/titi)"
check_eq "-rw-r--r--" "$(get_deb_permission test-deb.deb ./etc/nsswitch.conf)"
get_deb_description test-deb.deb >$TEST_log
- expect_log "Description: toto"
+ expect_log "Description: toto ®, Й, ק ,م, ๗, あ, 叶, 葉, 말, ü and é"
expect_log "Package: titi"
expect_log "Depends: dep1, dep2"
diff --git a/tools/build_defs/pkg/make_deb.py b/tools/build_defs/pkg/make_deb.py
index 737c075a787721..1c9c84d68ab5b0 100644
--- a/tools/build_defs/pkg/make_deb.py
+++ b/tools/build_defs/pkg/make_deb.py
@@ -142,7 +142,7 @@ def MakeDebianControlField(name, value, wrap=False):
break_long_words=False)
else:
result += value
- return result.replace('\n', '\n ') + '\n'
+ return result.decode('utf-8').replace('\n', '\n ') + '\n'
def CreateDebControl(extrafiles=None, **kwargs):
@@ -159,7 +159,8 @@ def CreateDebControl(extrafiles=None, **kwargs):
with gzip.GzipFile('control.tar.gz', mode='w', fileobj=tar, mtime=0) as gz:
with tarfile.open('control.tar.gz', mode='w', fileobj=gz) as f:
tarinfo = tarfile.TarInfo('control')
- tarinfo.size = len(controlfile)
+ # Don't discard unicode characters when computing the size
+ tarinfo.size = len(controlfile.encode('utf-8'))
f.addfile(tarinfo, fileobj=BytesIO(controlfile.encode('utf-8')))
if extrafiles:
for name, (data, mode) in extrafiles.items():
@@ -261,27 +262,31 @@ def CreateChanges(output,
debsize = str(os.path.getsize(deb_file))
deb_basename = os.path.basename(deb_file)
- changesdata = ''.join(
- MakeDebianControlField(*x)
- for x in [('Format', '1.8'), ('Date', time.ctime(timestamp)), (
- 'Source', package
- ), ('Binary', package
- ), ('Architecture', architecture), ('Version', version), (
- 'Distribution', distribution
- ), ('Urgency', urgency), ('Maintainer', maintainer), (
- 'Changed-By', maintainer
- ), ('Description', '\n%s - %s' % (package, short_description)
- ), ('Changes', ('\n%s (%s) %s; urgency=%s'
- '\nChanges are tracked in revision control.'
- ) % (package, version, distribution, urgency)
- ), ('Files', '\n' + ' '.join(
- [checksums['md5'], debsize, section, priority, deb_basename])
- ), ('Checksums-Sha1', '\n' + ' '.join(
- [checksums['sha1'], debsize, deb_basename])
- ), ('Checksums-Sha256', '\n' + ' '.join(
- [checksums['sha256'], debsize, deb_basename]))])
+ changesdata = ''.join([
+ MakeDebianControlField('Format', '1.8'),
+ MakeDebianControlField('Date', time.ctime(timestamp)),
+ MakeDebianControlField('Source', package),
+ MakeDebianControlField('Binary', package),
+ MakeDebianControlField('Architecture', architecture),
+ MakeDebianControlField('Version', version),
+ MakeDebianControlField('Distribution', distribution),
+ MakeDebianControlField('Urgency', urgency),
+ MakeDebianControlField('Maintainer', maintainer),
+ MakeDebianControlField('Changed-By', maintainer),
+ MakeDebianControlField('Description', '\n%s - %s' % (
+ package, short_description)),
+ MakeDebianControlField('Changes', (
+ '\n%s (%s) %s; urgency=%s'
+ '\nChanges are tracked in revision control.') % (
+ package, version, distribution, urgency)),
+ MakeDebianControlField('Files', '\n' + ' '.join(
+ [checksums['md5'], debsize, section, priority, deb_basename])),
+ MakeDebianControlField('Checksums-Sha1', '\n' + ' '.join(
+ [checksums['sha1'], debsize, deb_basename])),
+ MakeDebianControlField('Checksums-Sha256', '\n' + ' '.join(
+ [checksums['sha256'], debsize, deb_basename]))])
with open(output, 'w') as changes_fh:
- changes_fh.write(changesdata)
+ changes_fh.write(changesdata.encode("utf-8"))
def GetFlagValue(flagvalue, strip=True):
| null | train | train | 2019-02-20T23:06:14 | "2019-02-07T05:41:44Z" | imcginnis | test |
bazelbuild/bazel/7375_8440 | bazelbuild/bazel | bazelbuild/bazel/7375 | bazelbuild/bazel/8440 | [
"timestamp(timedelta=160224.0, similarity=0.8566001287297237)"
] | 207c24f04453ef026c202f2962e55d2a125e388f | 923c45faecaabd00e0214ff7d178507623958b37 | [
"(Plan is to use this work to also address #4815, rather than implement an ad hoc solution to that bug.)",
"Design doc [here](https://github.com/bazelbuild/rules_python/blob/master/proposals/2019-02-12-design-for-a-python-toolchain.md).\r\n\r\nDiscussion can proceed in this thread. Initial reviewers are @katre (Bazel, Toolchains), @mrovner (Python), and @nlopezgi (Remote Execution).",
"Overall, this looks good. A few points:\r\n\r\n1. Get rid of the host_python_toolchain, just use the autodetecting version. I don't think the time spent running the autodetection script will really hurt python performance, will it?\r\n1. In the **Backwards Compatbility** section, you mention deleting several flags: I do not think flags can be conditionally deleted based on another flag. Ignoring the values should be sufficient, and they can be deleted in a post-migration cleanup.",
"1. Ok, I'll remove `host_python_toolchain`. I don't have a strong opinion about its impact on performance, but it's worth remembering that it will still be superseded by any other applicable toolchain that the user registers.\r\n\r\n2. By \"delete\" I really mean \"fail-fast if the user tries to specify them while the incompatible flag is enabled\". This can be implemented by checking the flag value for null, and logging an error in the fragment's `reportInvalidOptions()` (see [example](https://github.com/bazelbuild/bazel/blob/ea956ae20bac5be1e9917faabdcac3cab2965c12/src/main/java/com/google/devtools/build/lib/rules/python/PythonConfiguration.java#L99)). The true deletion would happen around the time the old code paths and incompatible flag are removed.",
"I think the distinction between \"delete\" and \"ignore with a warning\" is worth calling out.",
"(See also Nicolas's comments [here](https://github.com/bazelbuild/rules_python/pull/161#pullrequestreview-202814381).)",
"Replying to @nlopezgi's concern about toolchains and extensibility here:\r\n\r\n> I think you need something similar as there are rules that execute the native py_binary (e.g., rules_docker does here: https://github.com/bazelbuild/rules_docker/blob/master/python/image.bzl#L84) and there might be something special that these type of users need to do to work with the new py toolchains properly.\r\n\r\nUsers who operate at the level of BUILD targets and macros only need to worry about having definitions for their platforms and python toolchains, i.e. the `py_runtime_pair` target and an associated `toolchain` target referencing it, with appropriate constraints. Whatever the build graph looks like, it should Just Work.\r\n\r\nUsers who are writing new rules that interoperate with the Python rules may need to manipulate Python toolchains. To receive a Python toolchain, they should declare `@bazel_tools//tools/python:toolchain_type` as a required toolchain type in their rule and receive it with `ctx.toolchains[<same label>]`. This would give them back the `ToolchainInfo` with the schema described in the doc. This would be necessary for instance to write a replica of `py_binary` in Starlark. Conversely, users can write a replacement for `py_runtime` or `py_runtime_pair` by simply returning an appropriate `PyRuntimeInfo` / `ToolchainInfo` provider.\r\n\r\nI didn't go into too much detail about how to write rules that produce or consume Python toolchains (aside from a description of the provider schema) because this is already covered by the general toolchain documentation linked in the doc's abstract.",
"(please do not assign issues to more than one `team-*`)",
"Let me add my 5 coins as an end user\r\nI would like to see similar naming convention and signatures for toolchain types as is done for all other toolchains\r\n```\r\npy_runtime_pair -> py_toolchain\r\n```\r\nAlso related the section\r\n> Why not split Python 2 and Python 3 into two separate toolchain types?\r\n> The naming convention for toolchain types is to literally name the target \"toolchain_type\",\r\n\r\nBased on jdk toolchain implementation it doesn't look like a problem - [tools/jdk/BUILD](https://github.com/bazelbuild/bazel/blob/be9483129401a7c9f1a86a40a3d7770662248576/tools/jdk/BUILD#L25)\r\nAlso \r\n```\r\n@bazel_tools//tools/python2:toolchain_type\r\n@bazel_tools//tools/python3:toolchain_type\r\n```\r\ndoesn't break the convention but helps avoids problems with a missed py_runtime attribute in the pair and provide an opportunity to force version as \r\n```\r\n--python3_toolchain .../python:remote3.7.15 --python2_toolchain ../python:remote2.7.13\r\n```\r\nAlso it allows to rid of python_version attribute from `py_binary`/`py_test` rules and select runtime based on provided toolchain type\r\n",
"Hi Guro, thanks for the comments. There's a few reasons I didn't organize it that way.\r\n\r\n> py_runtime_pair -> py_toolchain\r\n\r\nIt's not clear what the ideal way to deal with multiple Python runtimes will be long-term. Currently the rules are organized around this PY2/PY3 distinction, but in the future that will become less important and there may be more emphasis on choosing minor versions. Building the current schema into the rule name gives us a little more room to redesign it in the future without extra breaking changes.\r\n\r\n>> Why not split Python 2 and Python 3 into two separate toolchain types?\r\n>\r\n> Based on jdk toolchain implementation it doesn't look like a problem\r\n\r\nAgain, future-proofing is part of the reason. It's easier to migrate the schema of a `ToolchainInfo` to use some other layout rather than `py2_runtime = ..., py3_runtime = ...`, and even to migrate a toolchain rule to have different attributes, than it is to migrate Python rules to accept different toolchain types.\r\n \r\nFor platforms that do not provide an implementation for one of these toolchains, we'd still have to define a dummy toolchain that fails at analysis time, since even if a target does not use the toolchain its rule type will still require both toolchain types.\r\n\r\nAlso, creating `.../python[2|3]:toolchain_type` implies the creation of two additional directories and `BUILD` files whose only purpose is to provide naming disambiguation for the toolchain types. I'd sooner just break convention and name them `.../python:py[2|3]_toolchain_type`.\r\n\r\n> provide an opportunity to force version\r\n\r\nI don't believe there's anything in the toolchain framework that would allow you to directly force the toolchain implementation to use for a given toolchain type, as opposed to just letting Bazel select one based on constraints, though I could be wrong.\r\n\r\n> Also it allows to rid of `python_version` attribute from `py_binary`/`py_test` rules and select runtime based on provided toolchain type\r\n\r\nI checked with @katre before starting the design doc, and it turns out that currently toolchains can really only differentiate themselves based on platform constraints, not other rule logic constraints. You can't easily express that a given py_binary has a constraint of \"I want Python 2\".\r\n",
"Looks good to me.",
"Thanks for addressing my question about extending python rules. It would be ideal to get this info as part of user docs whenever the right time for that comes.\r\n\r\nLooks good to me. ",
"@brandjon is it really not possible to express a version constraint for e.g. a py_binary using toolchains? There is an example here: https://docs.bazel.build/versions/master/platforms.html#defining-constraints-and-platforms talking about defining Version as a constraint. That could not be used?\r\n\r\nThis is sidetracking a bit but I am also curios about this as I was planning to implement to add a constraint for the nodejs toolchains so it would be possible to use different versions of nodejs in the same workspace and one could choose on nodejs_binary level. ",
"In that example the platform either supports one version or the other, and targets build/run on whichever platform has the version they require. Here the same platform is generally expected to provide both Python versions. Currently all values for a constraint setting are considered mutually exclusive.\r\n\r\nI think the bigger issue is that Python version is a property of the target, not the platform. @katre could comment more.",
"Ah yeah I see, so I can say a platform is compatible with a certain version, but I can not say that a platform is compatible with multiple versions and then just choose the version on a per-target level. It would be nice to hear more details about how to make such a use-case possible in a generic way from @katre. As I imagine this could come up again and again. I am also happy to pull this in a separate issue or bazel-discuss as this is just tangentially related to this issue.\r\n\r\nI also do wonder how `rules_go` manages to allow the setting toolchain attributes on a per-target basis, e.g. I can set `go_binary(os=\"windows\",...)` and then that will compile for windows.",
"We don't yet have a good story for handling constraints on specific toolchain versions. I know that rules_scala also has problems with this, but I am not sure what the best UX would be (ie, what is the easiest way for users to express the idea that \"this target needs nodejs X.Y to build\").\r\n\r\nI don't think there's an existing issue in Github to track this, so feel free to open one and make any suggestions as to how you think it should be handled.",
"I'm running into some bootstrapping issues with the new provider definition that I won't have time to address before we cut the baseline for 0.24. So this feature and the associated --incompatible change to preview it will be available in 0.25.",
"Legacy code cleanup tracked by #8169.",
"Reopening this because the flag flip failed due to downstream breakages. Follow the migration tracking bug #7899.",
"This seems to be resolved, but as a casual user of Python and new user of rules_python, it would be helpful to have simple documentation explaining how to do a hermetic build.\r\n\r\n(Somehow I am able to run my py_binary targets at the moment even though I know the dependencies in the BUILD.bazel files are inadequate.)"
] | [
"Can the input `bash_binary` ever be just `bash.exe` for example, which would mean \"whatever is on the PATH\"?",
"I think there are two ways to tell which shell binary to use, `BAZEL_SH` or `--shell_executable`. Both way requires user to set an absolute path. The only case `bash_binary` is a relative path (runfile path) is that when using shell toolchain (similar to python toolchain), but I'm not sure it's implemented.",
"But here, `python_binary` will just be `python` if nothing is specified.. I need to fix this.",
"Thanks, let me know when the PR is ready for another review.",
"Thanks for catching the problem! Please take a look again. ;)",
"Just checking: `bash_binary` can either be an absolute Bash path (from `BAZEL_SH` or `--shell_executable`), or (theoretically perhaps) a bash toolchain's runfiles-relative path. Correct?\r\n\r\nAnd it always ends with \"bash\" or \"bash.exe\" (so just \"bash\" without the extension), right?\r\n\r\nAny other option I'm missing?",
"What other values could `python_binary` have, and in what situations?",
"Everything you said I believe is true, I don't think there's any other option.",
"Similar to shell, we have\r\n\r\n1. `--python_path`, gives an absolute path\r\n2. `--python_top`, gives an runfile path\r\n3. python toolchain (`py_runtime`), gives a runfile path\r\n4. Default if nothing specified: `python`\r\n\r\n@brandjon Can confirm this.",
"Thanks for confirming that!",
"Could you please add a comment about this?",
"Thanks! Waiting for @brandjon to confirm before LGTM. Please add a comment in the code summarizing Jon's answer.",
"Will do that!",
"Oh, just realized I had a typo. It should be `GetBinaryPathWithoutExtension(bash_binary) != L\"bash\")`, `GetBinaryPathWithoutExtension` just strips out the ending `.exe` if there is any. I wanted to check if bash_binary is already `bash` or `bash.exe`. Similar for the python case.",
"Will add comment for this!",
"Both `--python_top` and Python toolchains select a `py_runtime` to use. `py_runtime` provides a runfiles path if its `interpreter` attribute is set, and an absolute path if its `interpreter_path` attribute is set (these attributes are exclusive).\r\n\r\n`--python_path` is validated to be an absolute path. If nothing is specified, the `python` default is passed along the same code path that `--python_path` uses but skips this validation check as a special case. It is intended that both of these approaches are deprecated and replaced by toolchains, with the `python` PATH lookup behavior provided by an autodetecting toolchain.",
"Thanks for the confirmation, I'll add those to comment",
"Rewrite comment as follows:\r\n\r\n> There are three kinds of values for `python_binary`:\r\n> 1. An absolute path to a system interpreter. This is the case if `--python_path` is set by the user, or if a `py_runtime` is used that has `interpreter_path` set.\r\n> 2. A runfile path to an in-workspace interpreter. This is the case if a `py_runtime` is used that has `interpreter` set.\r\n> 3. The special constant, \"python\". This is the default case if neither of the above apply.\r\n> Rlocation resolves runfiles paths to absolute paths, and if given an absolute path it leaves it alone, so it's suitable for cases 1 and 2.\r\n\r\nThere's a slight detail that the default toolchain's py_runtime on windows contains a sentinel value hack that tells bazel to use legacy --python_path, but I don't think we need to mention that in this comment.",
"Thanks for help with the comment!"
] | "2019-05-22T12:24:59Z" | [
"type: feature request",
"P1",
"team-Rules-Python"
] | Switch Python rules to use toolchains | This bug tracks designing, implementing, and migrating built-in Python rules to use the toolchain mechanism for resolving the Python runtime. This replaces the legacy mechanism of specifying `--python_top` to globally make all Python targets look at a specific `py_runtime`, or omitting `--python_top` to use the system default "python" command.
This is prioritized. Design doc to follow. | [
"src/tools/launcher/bash_launcher.cc",
"src/tools/launcher/python_launcher.cc"
] | [
"src/tools/launcher/bash_launcher.cc",
"src/tools/launcher/python_launcher.cc"
] | [] | diff --git a/src/tools/launcher/bash_launcher.cc b/src/tools/launcher/bash_launcher.cc
index 0020d5f92d55d3..67f0a5d53a2b51 100644
--- a/src/tools/launcher/bash_launcher.cc
+++ b/src/tools/launcher/bash_launcher.cc
@@ -30,6 +30,14 @@ static constexpr const char* BASH_BIN_PATH = "bash_bin_path";
ExitCode BashBinaryLauncher::Launch() {
wstring bash_binary = this->GetLaunchInfoByKey(BASH_BIN_PATH);
+
+ // If bash_binary is already "bash" or "bash.exe", that means we want to
+ // rely on the shell binary in PATH, no need to do Rlocation.
+ if (GetBinaryPathWithoutExtension(bash_binary) != L"bash") {
+ // Rlocation returns the original path if bash_binary is an absolute path.
+ bash_binary = this->Rlocation(bash_binary, true);
+ }
+
if (DoesFilePathExist(bash_binary.c_str())) {
wstring bash_bin_dir = GetParentDirFromPath(bash_binary);
wstring path_env;
diff --git a/src/tools/launcher/python_launcher.cc b/src/tools/launcher/python_launcher.cc
index c4d2d5c04670fd..be655cf1c4eeb2 100644
--- a/src/tools/launcher/python_launcher.cc
+++ b/src/tools/launcher/python_launcher.cc
@@ -30,6 +30,20 @@ static constexpr const char* WINDOWS_STYLE_ESCAPE_JVM_FLAGS = "escape_args";
ExitCode PythonBinaryLauncher::Launch() {
wstring python_binary = this->GetLaunchInfoByKey(PYTHON_BIN_PATH);
+
+ // There are three kinds of values for `python_binary`:
+ // 1. An absolute path to a system interpreter. This is the case if `--python_path` is set by the
+ // user, or if a `py_runtime` is used that has `interpreter_path` set.
+ // 2. A runfile path to an in-workspace interpreter. This is the case if a `py_runtime` is used
+ // that has `interpreter` set.
+ // 3. The special constant, "python". This is the default case if neither of the above apply.
+ // Rlocation resolves runfiles paths to absolute paths, and if given an absolute path it leaves
+ // it alone, so it's suitable for cases 1 and 2.
+ if (GetBinaryPathWithoutExtension(python_binary) != L"python") {
+ // Rlocation returns the original path if python_binary is an absolute path.
+ python_binary = this->Rlocation(python_binary, true);
+ }
+
// If specified python binary path doesn't exist, then fall back to
// python.exe and hope it's in PATH.
if (!DoesFilePathExist(python_binary.c_str())) {
| null | train | train | 2019-05-22T12:19:28 | "2019-02-07T15:09:57Z" | brandjon | test |
bazelbuild/bazel/7376_7437 | bazelbuild/bazel | bazelbuild/bazel/7376 | bazelbuild/bazel/7437 | [
"timestamp(timedelta=0.0, similarity=0.8402525541748938)"
] | 3d88d7517744d600bd6c77e3facc2b52724de212 | 5575d63af6ef89be39000a2aa4fe7c98ca0e3e5f | [
"@petemounce -- could you please take a look?",
"FYI, @petemounce is currently on holiday, will be back in ~2 weeks, so I don't expect this to be addressed until late Feb/early March.",
"@RNabel , thanks for the heads-up!\r\n\r\n@vmax , is this issue blocking you? Can you work around it until the package is updated?",
"@RNabel @laszlocsomor thank you! \r\n\r\n>Can you work around it until the package is updated?\r\n\r\nYes, using the hint I posted in `Any other information, logs, or outputs that you want to share?` in issue description"
] | [] | "2019-02-15T13:48:34Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Package provided in Chocolatey does not declare a dependency | ### Description of the problem / feature request:
`bazel` installed via Chocolatey does not declare dependency on VC Redist
### Feature requests: what underlying problem are you trying to solve with this feature?
I'm trying to use `bazel` to build code on Windows instance on GCE (specifically `windows-2019/windows-cloud`)
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
`choco install bazel`
`bazel version` => {
`cmd` -> prints out empty string
`bash` on `msys2` -> prints out `C:/ProgramData/chocolatey/bin/bazel.exe: error while loading shared libraries: ?: cannot open shared object file: No such file or directory`
}
### What operating system are you running Bazel on?
Windows Server 2019
### What's the output of `bazel info release`?
```
$ bazel version
WARNING: --batch mode is deprecated. Please instead explicitly shut down your Bazel server using the command "bazel shutdown".
INFO: Invocation ID: aa5a2fea-ff69-4f76-b963-f7fb4f427831
Build label: 0.22.0
Build target: bazel-out/x64_windows-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Mon Jan 28 12:59:27 2019 (1548680367)
Build timestamp: 1548680367
Build timestamp as int: 1548680367
```
### Have you found anything relevant by searching the web?
Related: #5254
### Any other information, logs, or outputs that you want to share?
`choco install -y vcredist2015` should be ran to be able to use `bazel`
it should be either automatically installed or at least advised
| [
"scripts/packages/chocolatey/bazel.nuspec.template"
] | [
"scripts/packages/chocolatey/bazel.nuspec.template"
] | [] | diff --git a/scripts/packages/chocolatey/bazel.nuspec.template b/scripts/packages/chocolatey/bazel.nuspec.template
index 761d43f0e552c6..da5f5198aed3f4 100644
--- a/scripts/packages/chocolatey/bazel.nuspec.template
+++ b/scripts/packages/chocolatey/bazel.nuspec.template
@@ -78,6 +78,7 @@ Supply like `--params="/option:'value' ..."` ([see docs for --params](https://gi
<dependency id="chocolatey-core.extension" version="1.0.7"/>
<dependency id="msys2" version="[20160719.1.0,20160719.1.1]"/>
<dependency id="python2" version="[2.7.11,3.0)"/>
+ <dependency id="vcredist140" version="14.20.27508.1"/>
</dependencies>
<!-- chocolatey-uninstall.extension - If supporting 0.9.9.x (or below) and including a chocolateyUninstall.ps1 file to uninstall an EXE/MSI, you probably want to include chocolatey-uninstall.extension as a dependency. Please verify whether you are using a helper function from that package. -->
| null | val | train | 2019-05-08T00:07:05 | "2019-02-07T15:16:26Z" | vmax | test |
bazelbuild/bazel/7407_8512 | bazelbuild/bazel | bazelbuild/bazel/7407 | bazelbuild/bazel/8512 | [
"timestamp(timedelta=41156.0, similarity=0.9193090360911036)"
] | 3290e22356b59371274849ee51297635b9435285 | 72c9357191f34d6c91559c4ec22f3e3c48b6178f | [
"CC @katre ",
"Seems like the flag wasn't flipped. Changing breaking-change label to 0.26"
] | [] | "2019-05-30T08:53:32Z" | [
"P1",
"team-Rules-CPP",
"incompatible-change"
] | incompatible_dont_enable_host_nonhost_crosstool_features: Do not automatically enable "host" and "nonhost" crosstool features | **Flag:** `--incompatible_dont_enable_host_nonhost_crosstool_features`
**Available since:** 0.24 (March 2019 release)
**Will be flipped in:** 0.25 (April 2019 release)
**Tracking issue:** #6516
# Motivation
With the move of C++ rules to use platforms/toolchains (tracked in #6516), we are removing host specific logic. Platforms don't guarantee existence of separate host toolchain, in which case it's not clear which feature to enable, and it can happen that there will be multiple execution platforms, which currently don't have a way to enable a specific feature. My research shows that these Bazel features are actually mostly unused, so instead of coming up with non-trivial solution, we will remove them.
# Migration
With the flag flipped, `host` and `nonhost` features will never be enabled automatically. There are no generally useful migration notes. | [
"src/main/java/com/google/devtools/build/lib/rules/cpp/CppOptions.java",
"tools/cpp/BUILD"
] | [
"src/main/java/com/google/devtools/build/lib/rules/cpp/CppOptions.java",
"tools/cpp/BUILD"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/mock/cc_toolchain_config.bzl",
"src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java",
"src/test/java/com/google/devtools/build/lib/rules/cpp/CompileBuildVariablesTest.java",
"src/test/java/com/google/devtools/build/lib/rules/cpp/LinkBuildVariablesTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppOptions.java b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppOptions.java
index 58fd83c8ef7275..abe07496f948ef 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/cpp/CppOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/cpp/CppOptions.java
@@ -726,7 +726,7 @@ public Label getFdoPrefetchHintsLabel() {
@Option(
name = "incompatible_dont_enable_host_nonhost_crosstool_features",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.TOOLCHAIN,
effectTags = {OptionEffectTag.LOADING_AND_ANALYSIS},
metadataTags = {
diff --git a/tools/cpp/BUILD b/tools/cpp/BUILD
index 34c428999b999e..c5e48ad0d83e87 100644
--- a/tools/cpp/BUILD
+++ b/tools/cpp/BUILD
@@ -357,10 +357,10 @@ toolchain(
cc_toolchain(
name = "cc-compiler-x64_windows_msvc",
- all_files = ":every-file-x64_windows",
+ all_files = ":empty",
ar_files = ":empty",
as_files = ":empty",
- compiler_files = ":compile-x64_windows",
+ compiler_files = ":empty",
dwp_files = ":empty",
linker_files = ":empty",
objcopy_files = ":empty",
@@ -391,24 +391,6 @@ toolchain(
toolchain_type = ":toolchain_type",
)
-filegroup(
- name = "every-file-x64_windows",
- srcs = [
- ":compile-x64_windows",
- ],
-)
-
-filegroup(
- name = "compile-x64_windows",
- srcs = glob(
- [
- "wrapper/bin/msvc_*",
- "wrapper/bin/pydir/msvc*",
- ],
- allow_empty = True,
- ),
-)
-
filegroup(
name = "srcs",
srcs = glob(["**"]) + [
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/mock/cc_toolchain_config.bzl b/src/test/java/com/google/devtools/build/lib/analysis/mock/cc_toolchain_config.bzl
index 656604fd01c85f..9de5293b924356 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/mock/cc_toolchain_config.bzl
+++ b/src/test/java/com/google/devtools/build/lib/analysis/mock/cc_toolchain_config.bzl
@@ -522,7 +522,6 @@ _thin_lto_feature = feature(
],
),
],
- requires = [feature_set(features = ["nonhost"])],
)
_simple_thin_lto_feature = feature(
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java
index 76002e39f04ee3..6f569a68bea112 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/CcLibraryConfiguredTargetTest.java
@@ -1229,64 +1229,6 @@ public void testCompilationModeFeatures() throws Exception {
assertThat(flags).containsNoneOf("-fastbuild", "-opt");
}
- private List<String> getHostAndTargetFlags(boolean useHost, boolean isDisabledByFlag)
- throws Exception {
- AnalysisMock.get()
- .ccSupport()
- .setupCcToolchainConfig(
- mockToolsConfig,
- CcToolchainConfig.builder()
- .withFeatures(
- MockCcSupport.HOST_AND_NONHOST_CONFIGURATION_FEATURES,
- CppRuleClasses.SUPPORTS_PIC));
- scratch.overwriteFile("mode/BUILD", "cc_library(name = 'a', srcs = ['a.cc'])");
- useConfiguration(
- "--cpu=k8",
- isDisabledByFlag
- ? "--incompatible_dont_enable_host_nonhost_crosstool_features"
- : "--noincompatible_dont_enable_host_nonhost_crosstool_features");
- ConfiguredTarget target;
- String objectPath;
- if (useHost) {
- target = getHostConfiguredTarget("//mode:a");
- objectPath = "_objs/a/a.o";
- } else {
- target = getConfiguredTarget("//mode:a");
- objectPath = "_objs/a/a.pic.o";
- }
- Artifact objectArtifact = getBinArtifact(objectPath, target);
- CppCompileAction action = (CppCompileAction) getGeneratingAction(objectArtifact);
- assertThat(action).isNotNull();
- return action.getCompilerOptions();
- }
-
- @Test
- public void testHostAndNonHostFeatures() throws Exception {
- useConfiguration();
- List<String> flags;
-
- flags = getHostAndTargetFlags(/* useHost= */ true, /* isDisabledByFlag= */ false);
- assertThat(flags).contains("-host");
- assertThat(flags).doesNotContain("-nonhost");
-
- flags = getHostAndTargetFlags(/* useHost= */ false, /* isDisabledByFlag= */ false);
- assertThat(flags).contains("-nonhost");
- assertThat(flags).doesNotContain("-host");
- }
-
- @Test
- public void testHostAndNonHostFeaturesDisabledByTheFlag() throws Exception {
- List<String> flags;
-
- flags = getHostAndTargetFlags(/* useHost= */ true, /* isDisabledByFlag= */ true);
- assertThat(flags).doesNotContain("-host");
- assertThat(flags).doesNotContain("-nonhost");
-
- flags = getHostAndTargetFlags(/* useHost= */ false, /* isDisabledByFlag= */ true);
- assertThat(flags).doesNotContain("-nonhost");
- assertThat(flags).doesNotContain("-host");
- }
-
@Test
public void testIncludePathsOutsideExecutionRoot() throws Exception {
scratchRule(
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/CompileBuildVariablesTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/CompileBuildVariablesTest.java
index 96d8c2cb2c7ece..4c508145088c1f 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/CompileBuildVariablesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/CompileBuildVariablesTest.java
@@ -220,8 +220,7 @@ public void testPresenceOfIsUsingFissionAndPerDebugObjectFileVariablesWithThinlt
"fission_flags_for_lto_backend",
CppRuleClasses.PER_OBJECT_DEBUG_INFO,
CppRuleClasses.SUPPORTS_START_END_LIB,
- CppRuleClasses.THIN_LTO,
- MockCcSupport.HOST_AND_NONHOST_CONFIGURATION_FEATURES));
+ CppRuleClasses.THIN_LTO));
useConfiguration("--fission=yes", "--features=thin_lto");
scratch.file("x/BUILD", "cc_binary(name = 'bin', srcs = ['bin.cc'])");
diff --git a/src/test/java/com/google/devtools/build/lib/rules/cpp/LinkBuildVariablesTest.java b/src/test/java/com/google/devtools/build/lib/rules/cpp/LinkBuildVariablesTest.java
index 706013f82509fd..bcff1372642729 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/cpp/LinkBuildVariablesTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/cpp/LinkBuildVariablesTest.java
@@ -217,7 +217,6 @@ public void testNoIfsoBuildingWhenWhenThinLtoIndexing() throws Exception {
.withFeatures(
CppRuleClasses.THIN_LTO,
CppRuleClasses.SUPPORTS_PIC,
- MockCcSupport.HOST_AND_NONHOST_CONFIGURATION_FEATURES,
CppRuleClasses.SUPPORTS_INTERFACE_SHARED_LIBRARIES,
CppRuleClasses.SUPPORTS_DYNAMIC_LINKER,
CppRuleClasses.SUPPORTS_START_END_LIB));
@@ -343,7 +342,6 @@ public void testOutputExecpathIsNotExposedWhenThinLtoIndexing() throws Exception
CcToolchainConfig.builder()
.withFeatures(
CppRuleClasses.THIN_LTO,
- MockCcSupport.HOST_AND_NONHOST_CONFIGURATION_FEATURES,
CppRuleClasses.SUPPORTS_DYNAMIC_LINKER,
CppRuleClasses.SUPPORTS_PIC,
CppRuleClasses.SUPPORTS_INTERFACE_SHARED_LIBRARIES,
| train | train | 2019-05-30T01:35:13 | "2019-02-12T17:45:58Z" | hlopko | test |
bazelbuild/bazel/7425_7426 | bazelbuild/bazel | bazelbuild/bazel/7425 | bazelbuild/bazel/7426 | [
"timestamp(timedelta=0.0, similarity=0.8598241582022159)"
] | b109a5f69edb35572d65332fe677d032ccdc5282 | eadd1e9f702e3443719748a2da7b4e3acf41fd88 | [] | [] | "2019-02-14T09:18:00Z" | [
"incompatible-change"
] | incompatible_java_coverage: allow coverage collection for JVM languages | The option `--incompatible_java_coverage`:
- makes possible collecting coverage for Starlark JVM languages and jars imported with `java_import`
- only includes JVM files in the coverage report (dismisses data files, for example `.js` files that shouldn't have been in the report in the first place)
- the report includes the actual path of the files relative to the workspace root instead of the package path (e.g. `src/com/google/Action.java` instead of `com/google/Action.java`). This allows `genhtml` to generate HTML reports from the combined bazel coverage output.
For more details see [Bazel coverage for JVM languages](https://docs.google.com/document/d/1mQLQa2uMIgVcwTE-hwaKgwQ5upExIRH5p9lHFyxhj4g/edit?usp=sharing).
# Migration Notes
The users do not have to do any migration. Having the package paths in the report was filed as a bug (see #2528).
| [
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java"
] | [
"src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
index 4347d97681d619..0732a81409504f 100644
--- a/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
+++ b/src/main/java/com/google/devtools/build/lib/analysis/config/BuildConfiguration.java
@@ -589,7 +589,7 @@ public static class Options extends FragmentOptions implements Cloneable {
@Option(
name = "incompatible_java_coverage",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS,
effectTags = {OptionEffectTag.AFFECTS_OUTPUTS},
metadataTags = {
| null | train | train | 2019-02-14T10:07:12 | "2019-02-14T08:44:05Z" | iirina | test |
bazelbuild/bazel/7454_7645 | bazelbuild/bazel | bazelbuild/bazel/7454 | bazelbuild/bazel/7645 | [
"timestamp(timedelta=0.0, similarity=0.868161844385077)"
] | 426f434d0ee01b77fff0b0940d248dca8b46c1c3 | 3eabbbacdae10edcf6d008e099c162848e99d4e5 | [
"Fixed by https://github.com/laszlocsomor/bazel/commit/363016efe0973f12f28ac42e43c79c84bb0a05df. Closing issue. ",
"No, https://github.com/laszlocsomor/bazel/commit/363016efe0973f12f28ac42e43c79c84bb0a05df was not merged! This flag is not a breaking change in 0.25",
"Sorry about that, thanks for updating the labels",
"I re-added breaking change 26 because that will put this bug in the queue for the next release manager to check up on it. No pressure if it doesn't get flipped, the protocol is to extend the window in that case. But I think if it doesn't have a breaking change label it will fall through the cracks eventually. ",
"Good to know. Thank you!",
"This flag is marked as `migration-0.25`, causing it to be run by the bazelisk incompatible change pipeline. But this flag is not available (at least under linux), causing the build to [fail](https://buildkite.com/bazel/bazelisk-plus-incompatible-flags/builds/104#5b8edad8-db18-440d-a0cb-08614a27c374/1958).",
"We can remove the migration tag; the flag is now flipped (but not yet removed).\r\n\r\nThis flag is a startup flag, which Bazelisk cannot handle.\r\nI don't see any failure in the log you linked, can you check the link again?",
"The link goes to line 1958 of the Subpar build on 14.04 (OpenJDK 8). Copy/pasting the section:\r\n\r\n```\r\nRunning Bazel with --incompatible_windows_style_arg_escaping | 0s\r\n-- | --\r\n | \r\n | bazel test --flaky_test_attempts=3 --build_tests_only --local_test_jobs=12 --show_progress_rate_limit=5 --curses=yes --color=yes --verbose_failures --keep_going --jobs=32 --announce_rc --experimental_multi_threaded_digest --experimental_repository_cache_hardlinks --disk_cache= --sandbox_tmpfs_path=/tmp --experimental_build_event_json_file_path_conversion=false --build_event_json_file=/tmp/tmp117gcv3x/test_bep.json --remote_timeout=60 --remote_max_connections=200 --remote_http_cache=https://storage.googleapis.com/bazel-untrusted-buildkite-cache/e0979f59aee862bb5636c07921415ff395dc7b7a24c297265429c5fae66e56f6 --google_default_credentials --test_env=HOME --sandbox_writable_path=/home/bazel/.cache/bazelisk ... --incompatible_windows_style_arg_escaping\r\n | ERROR: Unrecognized option: --incompatible_windows_style_arg_escaping\r\n | INFO: Invocation ID: 8c007530-88e6-423f-b651-02fe88d5071c\r\n```\r\n\r\nBazelisk being unable to handle startup options is a good reason for this to fail the pipeline. I'll ignore.",
"Maybe we should label issues for startup flags such that bazelisk can exclude issues with the label.",
"@laurentlb can you fix the labels here for bazelisk, with 0.25.2 this fails because the flag isn't recognized",
"removed"
] | [] | "2019-03-06T14:13:35Z" | [
"area-Windows",
"incompatible-change",
"team-OSS"
] | incompatible_windows_style_arg_escaping: enables correct subprocess argument escaping on Windows | # Description
The option `--incompatible_windows_style_arg_escaping` enables correct subprocess argument escaping on Windows. This flag has NO effect on other platforms.
When enabled, [WindowsSubprocessFactory will use ShellUtils.windowsEscapeArg to escape command line arguments](https://github.com/bazelbuild/bazel/blob/1da48619d94ccc9fda59c114c6cd14904dbc6e34/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocessFactory.java#L77). This is correct, as [verified by tests](https://github.com/bazelbuild/bazel/blob/1da48619d94ccc9fda59c114c6cd14904dbc6e34/src/test/java/com/google/devtools/build/lib/windows/WindowsSubprocessTest.java#L230).
When disabled, [WindowsSubprocessFactory will use ShellUtils.quoteCommandLine](https://github.com/bazelbuild/bazel/blob/1da48619d94ccc9fda59c114c6cd14904dbc6e34/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocessFactory.java#L90). This is buggy, as shown by https://github.com/bazelbuild/bazel/issues/7122.
# Migration recipe
None, as of 2019-02-18.
We don't expect any breakages when this flag is enabled. However if it breaks your build, please let us know so we can help fixing it and provide a migration recipe.
# Rollout plan
- Bazel 0.23.0 will not support this flag.
- Bazel 0.24.0 is expected to support this flag, with default value being `false`.
- Bazel 0.25.0 is expected to flip this flag to true. | [
"src/main/cpp/bazel_startup_options.cc",
"src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java"
] | [
"src/main/cpp/bazel_startup_options.cc",
"src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java"
] | [] | diff --git a/src/main/cpp/bazel_startup_options.cc b/src/main/cpp/bazel_startup_options.cc
index f4d494fe8d0d1b..b6cce11db7a6fb 100644
--- a/src/main/cpp/bazel_startup_options.cc
+++ b/src/main/cpp/bazel_startup_options.cc
@@ -29,7 +29,7 @@ BazelStartupOptions::BazelStartupOptions(
use_workspace_rc(true),
use_home_rc(true),
use_master_bazelrc_(true),
- incompatible_windows_style_arg_escaping(false) {
+ incompatible_windows_style_arg_escaping(true) {
RegisterNullaryStartupFlag("home_rc");
RegisterNullaryStartupFlag("incompatible_windows_style_arg_escaping");
RegisterNullaryStartupFlag("master_bazelrc");
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java b/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java
index d4de1f90b855c7..52941982d7cfa1 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/BlazeServerStartupOptions.java
@@ -467,7 +467,7 @@ public String getTypeDescription() {
@Option(
name = "incompatible_windows_style_arg_escaping",
- defaultValue = "false", // NOTE: purely decorative, rc files are read by the client.
+ defaultValue = "true", // NOTE: purely decorative, rc files are read by the client.
documentationCategory = OptionDocumentationCategory.EXECUTION_STRATEGY,
effectTags = {
OptionEffectTag.ACTION_COMMAND_LINES,
| null | train | train | 2019-04-08T16:29:34 | "2019-02-18T10:02:17Z" | laszlocsomor | test |
bazelbuild/bazel/7454_7957 | bazelbuild/bazel | bazelbuild/bazel/7454 | bazelbuild/bazel/7957 | [
"timestamp(timedelta=10802.0, similarity=0.857245402727535)"
] | 466bf40f3f41fa6edf66f6401c5c16cb9b53510d | 6d4223b51218f4f2ffad0f118006dee2f777a96e | [
"Fixed by https://github.com/laszlocsomor/bazel/commit/363016efe0973f12f28ac42e43c79c84bb0a05df. Closing issue. ",
"No, https://github.com/laszlocsomor/bazel/commit/363016efe0973f12f28ac42e43c79c84bb0a05df was not merged! This flag is not a breaking change in 0.25",
"Sorry about that, thanks for updating the labels",
"I re-added breaking change 26 because that will put this bug in the queue for the next release manager to check up on it. No pressure if it doesn't get flipped, the protocol is to extend the window in that case. But I think if it doesn't have a breaking change label it will fall through the cracks eventually. ",
"Good to know. Thank you!",
"This flag is marked as `migration-0.25`, causing it to be run by the bazelisk incompatible change pipeline. But this flag is not available (at least under linux), causing the build to [fail](https://buildkite.com/bazel/bazelisk-plus-incompatible-flags/builds/104#5b8edad8-db18-440d-a0cb-08614a27c374/1958).",
"We can remove the migration tag; the flag is now flipped (but not yet removed).\r\n\r\nThis flag is a startup flag, which Bazelisk cannot handle.\r\nI don't see any failure in the log you linked, can you check the link again?",
"The link goes to line 1958 of the Subpar build on 14.04 (OpenJDK 8). Copy/pasting the section:\r\n\r\n```\r\nRunning Bazel with --incompatible_windows_style_arg_escaping | 0s\r\n-- | --\r\n | \r\n | bazel test --flaky_test_attempts=3 --build_tests_only --local_test_jobs=12 --show_progress_rate_limit=5 --curses=yes --color=yes --verbose_failures --keep_going --jobs=32 --announce_rc --experimental_multi_threaded_digest --experimental_repository_cache_hardlinks --disk_cache= --sandbox_tmpfs_path=/tmp --experimental_build_event_json_file_path_conversion=false --build_event_json_file=/tmp/tmp117gcv3x/test_bep.json --remote_timeout=60 --remote_max_connections=200 --remote_http_cache=https://storage.googleapis.com/bazel-untrusted-buildkite-cache/e0979f59aee862bb5636c07921415ff395dc7b7a24c297265429c5fae66e56f6 --google_default_credentials --test_env=HOME --sandbox_writable_path=/home/bazel/.cache/bazelisk ... --incompatible_windows_style_arg_escaping\r\n | ERROR: Unrecognized option: --incompatible_windows_style_arg_escaping\r\n | INFO: Invocation ID: 8c007530-88e6-423f-b651-02fe88d5071c\r\n```\r\n\r\nBazelisk being unable to handle startup options is a good reason for this to fail the pipeline. I'll ignore.",
"Maybe we should label issues for startup flags such that bazelisk can exclude issues with the label.",
"@laurentlb can you fix the labels here for bazelisk, with 0.25.2 this fails because the flag isn't recognized",
"removed"
] | [] | "2019-04-05T14:10:44Z" | [
"area-Windows",
"incompatible-change",
"team-OSS"
] | incompatible_windows_style_arg_escaping: enables correct subprocess argument escaping on Windows | # Description
The option `--incompatible_windows_style_arg_escaping` enables correct subprocess argument escaping on Windows. This flag has NO effect on other platforms.
When enabled, [WindowsSubprocessFactory will use ShellUtils.windowsEscapeArg to escape command line arguments](https://github.com/bazelbuild/bazel/blob/1da48619d94ccc9fda59c114c6cd14904dbc6e34/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocessFactory.java#L77). This is correct, as [verified by tests](https://github.com/bazelbuild/bazel/blob/1da48619d94ccc9fda59c114c6cd14904dbc6e34/src/test/java/com/google/devtools/build/lib/windows/WindowsSubprocessTest.java#L230).
When disabled, [WindowsSubprocessFactory will use ShellUtils.quoteCommandLine](https://github.com/bazelbuild/bazel/blob/1da48619d94ccc9fda59c114c6cd14904dbc6e34/src/main/java/com/google/devtools/build/lib/windows/WindowsSubprocessFactory.java#L90). This is buggy, as shown by https://github.com/bazelbuild/bazel/issues/7122.
# Migration recipe
None, as of 2019-02-18.
We don't expect any breakages when this flag is enabled. However if it breaks your build, please let us know so we can help fixing it and provide a migration recipe.
# Rollout plan
- Bazel 0.23.0 will not support this flag.
- Bazel 0.24.0 is expected to support this flag, with default value being `false`.
- Bazel 0.25.0 is expected to flip this flag to true. | [
"src/tools/launcher/util/BUILD"
] | [
"src/tools/launcher/util/BUILD"
] | [
"src/test/py/bazel/BUILD",
"src/test/py/bazel/printargs.cc",
"src/test/py/bazel/test_wrapper_test.py",
"tools/test/BUILD",
"tools/test/windows/tw.cc"
] | diff --git a/src/tools/launcher/util/BUILD b/src/tools/launcher/util/BUILD
index 5077e2300775eb..e3aa79a8fe6ad7 100644
--- a/src/tools/launcher/util/BUILD
+++ b/src/tools/launcher/util/BUILD
@@ -1,6 +1,6 @@
package(default_visibility = ["//src/tools/launcher:__subpackages__"])
-load("//src/tools/launcher:win_rules.bzl", "cc_library", "cc_binary", "cc_test")
+load("//src/tools/launcher:win_rules.bzl", "cc_binary", "cc_library", "cc_test")
filegroup(
name = "srcs",
@@ -19,6 +19,10 @@ cc_library(
name = "util",
srcs = ["launcher_util.cc"],
hdrs = ["launcher_util.h"],
+ visibility = [
+ "//src/tools/launcher:__subpackages__",
+ "//tools/test:__pkg__",
+ ],
deps = ["//src/main/cpp/util:filesystem"],
)
| diff --git a/src/test/py/bazel/BUILD b/src/test/py/bazel/BUILD
index d5f59d680c4530..ae947e2c9ba5c8 100644
--- a/src/test/py/bazel/BUILD
+++ b/src/test/py/bazel/BUILD
@@ -164,6 +164,16 @@ py_test(
"//src/conditions:windows": [":test_base"],
"//conditions:default": [],
}),
+ data = select({
+ "//src/conditions:windows": [":printargs"],
+ "//conditions:default": [],
+ }),
+)
+
+cc_binary(
+ name = "printargs",
+ srcs = ["printargs.cc"],
+ testonly = 1,
)
py_test(
diff --git a/src/test/py/bazel/printargs.cc b/src/test/py/bazel/printargs.cc
new file mode 100644
index 00000000000000..745398b824be99
--- /dev/null
+++ b/src/test/py/bazel/printargs.cc
@@ -0,0 +1,7 @@
+#include <stdio.h>
+int main(int argc, char** argv) {
+ for (int i = 1; i < argc; ++i) {
+ printf("arg=(%s)\n", argv[i]);
+ }
+ return 0;
+}
diff --git a/src/test/py/bazel/test_wrapper_test.py b/src/test/py/bazel/test_wrapper_test.py
index 7665f6810d93f3..b214dac24628f1 100644
--- a/src/test/py/bazel/test_wrapper_test.py
+++ b/src/test/py/bazel/test_wrapper_test.py
@@ -81,9 +81,9 @@ def _CreateMockWorkspace(self):
' srcs = ["unexported.bat"],',
')',
'sh_test(',
- ' name = "testargs_test.bat",',
- ' srcs = ["testargs.bat"],',
- ' args = ["foo", "a b", "", "bar"],',
+ ' name = "testargs_test.exe",',
+ ' srcs = ["testargs.exe"],',
+ r' args = ["foo", "a b", "", "\"c d\"", "\"\"", "bar"],',
')',
'py_test(',
' name = "undecl_test",',
@@ -134,21 +134,11 @@ def _CreateMockWorkspace(self):
'@echo BAD=%TEST_UNDECLARED_OUTPUTS_MANIFEST%',
],
executable=True)
- self.ScratchFile(
- 'foo/testargs.bat',
- [
- '@echo arg=(%~nx0)', # basename of $0
- '@echo arg=(%1)',
- '@echo arg=(%2)',
- '@echo arg=(%3)',
- '@echo arg=(%4)',
- '@echo arg=(%5)',
- '@echo arg=(%6)',
- '@echo arg=(%7)',
- '@echo arg=(%8)',
- '@echo arg=(%9)',
- ],
- executable=True)
+
+ self.CopyFile(
+ src_path = self.Rlocation("io_bazel/src/test/py/bazel/printargs.exe"),
+ dst_path = "foo/testargs.exe",
+ executable = True)
# A single white pixel as an ".ico" file. /usr/bin/file should identify this
# as "image/x-icon".
@@ -385,7 +375,7 @@ def _AssertTestArgs(self, flag, expected):
exit_code, stdout, stderr = self.RunBazel([
'test',
- '//foo:testargs_test.bat',
+ '//foo:testargs_test.exe',
'-t-',
'--test_output=all',
'--test_arg=baz',
@@ -568,24 +558,20 @@ def testTestExecutionWithTestSetupSh(self):
self._AssertTestArgs(
flag,
[
- '(testargs_test.bat)',
'(foo)',
'(a)',
'(b)',
+ '(c d)',
+ '()',
'(bar)',
- # Note: debugging shows that test-setup.sh receives more-or-less
- # good arguments (let's ignore issues #6276 and #6277 for now), but
- # mangles the last few.
- # I (laszlocsomor@) don't know the reason (as of 2018-10-01) but
- # since I'm planning to phase out test-setup.sh on Windows in favor
- # of the native test wrapper, I don't intend to debug this further.
- # The test is here merely to guard against unwanted future change of
- # behavior.
'(baz)',
- '("\\"x)',
- '(y\\"")',
- '("\\\\\\")',
- '(qux")'
+ '("x y")',
+ # I (laszlocsomor@) don't know the exact reason (as of 2019-04-05)
+ # why () and (qux) are mangled as they are, but since I'm planning
+ # to phase out test-setup.sh on Windows in favor of the native test
+ # wrapper, I don't intend to debug this further. The test is here
+ # merely to guard against unwanted future change of behavior.
+ '(\\" qux)'
])
self._AssertUndeclaredOutputs(flag)
self._AssertUndeclaredOutputsAnnotations(flag)
@@ -606,7 +592,6 @@ def testTestExecutionWithTestWrapperExe(self):
self._AssertTestArgs(
flag,
[
- '(testargs_test.bat)',
'(foo)',
# TODO(laszlocsomor): assert that "a b" is passed as one argument,
# not two, after https://github.com/bazelbuild/bazel/issues/6277
@@ -616,12 +601,13 @@ def testTestExecutionWithTestWrapperExe(self):
# TODO(laszlocsomor): assert that the empty string argument is
# passed, after https://github.com/bazelbuild/bazel/issues/6276
# is fixed.
+ '(c d)',
+ '()',
'(bar)',
'(baz)',
'("x y")',
'("")',
'(qux)',
- '()'
])
self._AssertUndeclaredOutputs(flag)
self._AssertUndeclaredOutputsAnnotations(flag)
diff --git a/tools/test/BUILD b/tools/test/BUILD
index 735e2fbb0132e1..6deb7dde275004 100644
--- a/tools/test/BUILD
+++ b/tools/test/BUILD
@@ -80,6 +80,7 @@ cc_library(
"//src/main/cpp/util:strings",
"//src/main/native/windows:lib-file",
"//src/main/native/windows:lib-util",
+ "//src/tools/launcher/util",
"//third_party/ijar:zip",
"@bazel_tools//tools/cpp/runfiles",
],
diff --git a/tools/test/windows/tw.cc b/tools/test/windows/tw.cc
index aec0853c21eb46..cacbd66477084c 100644
--- a/tools/test/windows/tw.cc
+++ b/tools/test/windows/tw.cc
@@ -43,6 +43,7 @@
#include "src/main/cpp/util/strings.h"
#include "src/main/native/windows/file.h"
#include "src/main/native/windows/util.h"
+#include "src/tools/launcher/util/launcher_util.h"
#include "third_party/ijar/common.h"
#include "third_party/ijar/platform_utils.h"
#include "third_party/ijar/zip.h"
@@ -1118,7 +1119,7 @@ bool AddCommandLineArg(const wchar_t* arg, const size_t arg_size,
}
bool CreateCommandLine(const Path& path,
- const std::vector<const wchar_t*>& args,
+ const std::vector<std::wstring>& args,
std::unique_ptr<WCHAR[]>* result) {
// kMaxCmdline value: see lpCommandLine parameter of CreateProcessW.
static constexpr size_t kMaxCmdline = 32767;
@@ -1132,9 +1133,9 @@ bool CreateCommandLine(const Path& path,
return false;
}
- for (const auto arg : args) {
- if (!AddCommandLineArg(arg, wcslen(arg), false, result->get(), kMaxCmdline,
- &total_len)) {
+ for (const std::wstring& arg : args) {
+ if (!AddCommandLineArg(arg.c_str(), arg.size(), false, result->get(),
+ kMaxCmdline, &total_len)) {
return false;
}
}
@@ -1145,7 +1146,7 @@ bool CreateCommandLine(const Path& path,
return true;
}
-bool StartSubprocess(const Path& path, const std::vector<const wchar_t*>& args,
+bool StartSubprocess(const Path& path, const std::vector<std::wstring>& args,
const Path& outerr, std::unique_ptr<Tee>* tee,
LARGE_INTEGER* start_time,
bazel::windows::AutoHandle* process) {
@@ -1342,7 +1343,7 @@ bool CreateUndeclaredOutputsAnnotations(const Path& undecl_annot_dir,
bool ParseArgs(int argc, wchar_t** argv, Path* out_argv0,
std::wstring* out_test_path_arg,
- std::vector<const wchar_t*>* out_args) {
+ std::vector<std::wstring>* out_args) {
if (!out_argv0->Set(argv[0])) {
return false;
}
@@ -1358,7 +1359,7 @@ bool ParseArgs(int argc, wchar_t** argv, Path* out_argv0,
out_args->clear();
out_args->reserve(argc - 1);
for (int i = 1; i < argc; i++) {
- out_args->push_back(argv[i]);
+ out_args->push_back(bazel::launcher::WindowsEscapeArg2(argv[i]));
}
return true;
}
@@ -1434,7 +1435,7 @@ bool TeeImpl::MainFunc() const {
}
int RunSubprocess(const Path& test_path,
- const std::vector<const wchar_t*>& args,
+ const std::vector<std::wstring>& args,
const Path& test_outerr, Duration* test_duration) {
std::unique_ptr<Tee> tee;
bazel::windows::AutoHandle process;
@@ -1871,7 +1872,7 @@ int TestWrapperMain(int argc, wchar_t** argv) {
std::wstring test_path_arg;
Path test_path, exec_root, srcdir, tmpdir, test_outerr, xml_log;
UndeclaredOutputs undecl;
- std::vector<const wchar_t*> args;
+ std::vector<std::wstring> args;
if (!ParseArgs(argc, argv, &argv0, &test_path_arg, &args) ||
!PrintTestLogStartMarker() ||
!FindTestBinary(argv0, test_path_arg, &test_path) ||
| test | train | 2019-04-05T16:48:05 | "2019-02-18T10:02:17Z" | laszlocsomor | test |
bazelbuild/bazel/7480_8286 | bazelbuild/bazel | bazelbuild/bazel/7480 | bazelbuild/bazel/8286 | [
"timestamp(timedelta=0.0, similarity=0.8428690127330948)"
] | efdd3b270faaaf9bca6439da4fc177e97296c1bd | 480849fb0cc81fd1c3aaad7b974350d620dcca6b | [
"/sub",
"Thanks @philwo ! This looks helpful.\r\n\r\nWe moved over to just using ```--spawn_strategy=linux-sandbox``` based on your advice in late 2017. That means we no longer have a patch for that.\r\n\r\nDoes this replace ```--remote_local_fallback_strategy=linux-sandbox``` ?",
"Yes.\r\nUnder `incompatible_list_based_execution_strategy_selection`, `remote_local_fallback_strategy` will no longer be respected. A target that is marked no-remote will not be eligible for remote execution, so the next available strategy from the list will be applied.\r\n\r\nWe plan to deprecate `remote_local_fallback_strategy` by the time `incompatible_list_based_execution_strategy_selection` becomes the default.\r\n\r\nWe think that the new strategy list should serve all the fallback needs (and make things more explicit and cleaner). Do let us know if for some reason your case is not being served!",
"@ishikhman as parts of your flag work can you please take over ownership of flipping this flag? You probably won't get to it by 0.26 (this thursday) so let's target to flip this in 0.27? I don't expect there to be much trouble except for fixing a few tests.",
"Could you improve the release notes about it?\r\nSee https://github.com/bazelbuild/bazel/issues/7816#issuecomment-502304725",
"> Could you improve the release notes about it?\r\n> See [#7816 (comment)](https://github.com/bazelbuild/bazel/issues/7816#issuecomment-502304725)\r\n\r\nhm, it is in release notes (I've checked https://github.com/bazelbuild/bazel-blog/pull/178) and blog post is coming right after 0.27 release (https://github.com/bazelbuild/bazel-blog/pull/173). \r\n\r\nThe release notes are already rather long, so what I can suggest is to include a link to the blog post. WDYT?",
"Sounds good to me.",
"> Yes.\r\n> Under `incompatible_list_based_execution_strategy_selection`, `remote_local_fallback_strategy` will no longer be respected. A target that is marked no-remote will not be eligible for remote execution, so the next available strategy from the list will be applied.\r\n> \r\n> We plan to deprecate `remote_local_fallback_strategy` by the time `incompatible_list_based_execution_strategy_selection` becomes the default.\r\n> \r\n> We think that the new strategy list should serve all the fallback needs (and make things more explicit and cleaner). Do let us know if for some reason your case is not being served!\r\n\r\n@agoulti @buchgr I've just checked that this is no _exactly_ the case. There are 2 use cases where `remote_local_fallback_strategy` was used:\r\n1) when target is marked as `no-remote` or `no-remote-exec`: [link](https://github.com/bazelbuild/bazel/blob/11a98a51095bfda494ddf7ba69d8ad80309ef63c/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java#L181)\r\n2) when remote execution failed and was caused NOT by a Timeout exception: [link](https://github.com/bazelbuild/bazel/blob/11a98a51095bfda494ddf7ba69d8ad80309ef63c/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java#L281) and [link2](https://github.com/bazelbuild/bazel/blob/11a98a51095bfda494ddf7ba69d8ad80309ef63c/src/main/java/com/google/devtools/build/lib/remote/RemoteSpawnRunner.java#L216)\r\n\r\nThe first case is fully covered by a list-based strategy, but not the second one. Therefore if the second use case is important (which I think it is, because someone mentioned that they rely on fallback in case of connection problems to a remote system) we cannot discard `remote_local_fallback_strategy`.\r\n\r\nI'll remove the usages for the first case as a part of #8970.\r\n\r\nIf we want to completely deprecate `remote_local_fallback_strategy`, i think, we should consider generic fallback mechanism that would be using a provided list.\r\n"
] | [] | "2019-05-10T09:24:38Z" | [
"incompatible-change",
"team-Remote-Exec"
] | incompatible_list_based_execution_strategy_selection: List-based explicit spawn strategy selection. | For more detailed description visit our blog post: https://blog.bazel.build/2019/06/19/list-strategy.html
## :no_good_man: Current situation:
- The user can set the execution strategy in general and for individual action mnemonics using the flags `--spawn_strategy=`, `--strategy=Mnemonic=` and `--strategy_regexp=Regex=`. The flags take a single strategy name as value. Example: `--spawn_strategy=linux-sandbox`.
- Bazel has a hardcoded and undocumented list of mnemonics that are known to work well with certain strategies and uses these unless the user overrides them *individually* using `--strategy=Mnemonic=` flags. Example: Bazel will use some kind of sandboxing by default if its available on your system, otherwise non-sandboxed execution (e.g. on Windows). However, it will run Javac actions via the persistent worker strategy.
- Each strategy has custom code to deal with the situation that it can't execute a given action - for example, the remote strategy silently falls back to sandboxed execution if an action can't run remotely. The sandbox strategy silently falls back to non-sandboxed local execution if an action doesn't support sandboxing. There's no good way to configure this behavior.
## :new: The option `--incompatible_list_based_execution_strategy_selection`:
- Allows the user to pass comma-separated lists of strategies to the above mentioned flags: `--spawn_strategy=remote,worker,linux-sandbox`.
- Each strategy now knows whether it can execute a given action. For any action that it wants to execute, Bazel just picks the first strategy from the given list that claims to be able to execute the action. If no strategy remains, the execution will fail.
- This means you can now have your build fail if any non-sandboxable or non-remotable action sneaks in! More reproducibility and safety for your builds! :tada:
- The strategies no longer do their own custom fallback, simplifying the code and unifying the behavior.
## :bulb: Some ideas how to use this:
- Don't set any flags and Bazel will try to do the best automatically: Use remote execution if it's available, otherwise persistent workers, otherwise sandboxed execution, otherwise non-sandboxed execution.
- I want the best sandboxed build on my Linux machine and no automatic fallback to symlink-only sandboxing, non-sandboxed execution and no persistent workers: `--spawn_strategy=linux-sandbox`.
- I want persistent workers for actions that support it, but otherwise only sandboxed execution: `--spawn_strategy=worker,sandboxed`.
## :construction: Migration needed:
- If you currently use the strategy selection flags, you'll want to revisit the values you set them to.
- If you currently patch your Bazel version to remove fallback to non-sandboxed execution, this should no longer be necessary then (:wave: @AustinSchuh).
- If you currently use remote execution with `--strategy=remote` and/or `--spawn_strategy=remote` and have actions that might not be executed remotely, consider removing those `strategy` flags completely, in this case bazel will pickup the first available strategy from the default list, which is `remote,worker,sandboxed,local`. Alternatively, add a strategy to fallback to if remote is not possible for an action, for example `--spawn_strategy=remote,sandboxed` will fallback to a sandboxed execution if remote is not possible.
- If you are using `--config=remote` you might need to change your .bazelrc file, where all the `remote` configs are located, including `strategy` flags. | [
"src/main/java/com/google/devtools/build/lib/exec/ExecutionOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/exec/ExecutionOptions.java"
] | [
"src/test/shell/bazel/remote/remote_execution_test.sh",
"src/test/shell/integration/bazel_worker_test.sh",
"src/test/shell/integration/execution_strategies_test.sh"
] | diff --git a/src/main/java/com/google/devtools/build/lib/exec/ExecutionOptions.java b/src/main/java/com/google/devtools/build/lib/exec/ExecutionOptions.java
index 843178d3669721..205e5eb54284f7 100644
--- a/src/main/java/com/google/devtools/build/lib/exec/ExecutionOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/exec/ExecutionOptions.java
@@ -59,7 +59,7 @@ public class ExecutionOptions extends OptionsBase {
@Option(
name = "incompatible_list_based_execution_strategy_selection",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.EXECUTION_STRATEGY,
effectTags = {OptionEffectTag.EXECUTION},
metadataTags = {
| diff --git a/src/test/shell/bazel/remote/remote_execution_test.sh b/src/test/shell/bazel/remote/remote_execution_test.sh
index 4fe983c09be561..7e1c8a0b460838 100755
--- a/src/test/shell/bazel/remote/remote_execution_test.sh
+++ b/src/test/shell/bazel/remote/remote_execution_test.sh
@@ -104,7 +104,6 @@ EOF
bazel clean >& $TEST_log
bazel build \
- --incompatible_list_based_execution_strategy_selection \
--remote_executor=localhost:${worker_port} \
//a:test >& $TEST_log \
|| fail "Failed to build //a:test with remote execution"
@@ -261,10 +260,7 @@ EOF
--remote_local_fallback_strategy=local \
--build_event_text_file=gen1.log \
//gen1 >& $TEST_log \
- || fail "Expected success"
-
- mv gen1.log $TEST_log
- expect_log "1 process: 1 local"
+ && fail "Expected failure" || true
}
function test_local_fallback_with_local_strategy_lists() {
@@ -280,7 +276,6 @@ tags = ["no-remote"],
EOF
bazel build \
- --incompatible_list_based_execution_strategy_selection \
--spawn_strategy=remote,local \
--remote_executor=localhost:${worker_port} \
--build_event_text_file=gen1.log \
@@ -304,7 +299,6 @@ tags = ["no-remote"],
EOF
bazel build \
- --incompatible_list_based_execution_strategy_selection \
--spawn_strategy=remote,sandboxed,local \
--remote_executor=localhost:${worker_port} \
--build_event_text_file=gen1.log \
@@ -328,7 +322,6 @@ tags = ["no-remote"],
EOF
bazel build \
- --incompatible_list_based_execution_strategy_selection \
--remote_executor=localhost:${worker_port} \
--build_event_text_file=gen1.log \
//gen1 >& $TEST_log \
@@ -356,10 +349,7 @@ EOF
--remote_local_fallback_strategy=sandboxed \
--build_event_text_file=gen2.log \
//gen2 >& $TEST_log \
- || fail "Expected success"
-
- mv gen2.log $TEST_log
- expect_log "1 process: 1 .*-sandbox"
+ && fail "Expected failure" || true
}
function is_file_uploaded() {
@@ -903,7 +893,7 @@ EOF
|| fail "Expected bazel-bin/a/remote.txt to have not been downloaded"
bazel build \
- --genrule_strategy=remote \
+ --genrule_strategy=remote,local \
--remote_executor=localhost:${worker_port} \
--experimental_inmemory_jdeps_files \
--experimental_inmemory_dotd_files \
diff --git a/src/test/shell/integration/bazel_worker_test.sh b/src/test/shell/integration/bazel_worker_test.sh
index c7202cf0acf24c..1e17705f15648e 100755
--- a/src/test/shell/integration/bazel_worker_test.sh
+++ b/src/test/shell/integration/bazel_worker_test.sh
@@ -460,16 +460,15 @@ EOF
sed -i.bak '/execution_requirements/d' work.bzl
rm -f work.bzl.bak
- bazel build --worker_quit_after_build :hello_world &> $TEST_log \
- || fail "build failed"
+ bazel build --worker_quit_after_build :hello_world &> $TEST_log && fail "Failure expected" || true
- expect_log "Worker strategy cannot execute this Work action, because the action's execution info does not contain 'supports-workers=1'"
+ expect_log "No usable spawn strategy found for spawn with mnemonic Work"
expect_not_log "Created new ${WORKER_TYPE_LOG_STRING} Work worker (id [0-9]\+)"
expect_not_log "Destroying Work worker (id [0-9]\+)"
# WorkerSpawnStrategy falls back to standalone strategy, so we still expect the output to be generated.
[ -e "$BINS/hello_world.out" ] \
- || fail "Worker did not produce output"
+ && fail "Worker was not supposed to produce output" || true
}
function test_environment_is_clean() {
diff --git a/src/test/shell/integration/execution_strategies_test.sh b/src/test/shell/integration/execution_strategies_test.sh
index c312be660f9c3a..5e81b6d63eb017 100755
--- a/src/test/shell/integration/execution_strategies_test.sh
+++ b/src/test/shell/integration/execution_strategies_test.sh
@@ -44,16 +44,22 @@ fi
source "$(rlocation "io_bazel/src/test/shell/integration_test_setup.sh")" \
|| { echo "integration_test_setup.sh not found!" >&2; exit 1; }
-# Tests that you have to opt-in to list based strategy selection via an incompatible flag.
+# Tests that you cat opt-out from a list based strategy selection via an incompatible flag.
function test_incompatible_flag_required() {
- bazel build --spawn_strategy=worker,local --debug_print_action_contexts &> $TEST_log || true
+ bazel build --spawn_strategy=worker,local --debug_print_action_contexts \
+ --incompatible_list_based_execution_strategy_selection=false &> $TEST_log || true
expect_log "incompatible_list_based_execution_strategy_selection was not enabled"
}
+# Tests that a list based strategy selection is enabled by default
+function test_incompatible_flag_flipped() {
+ bazel build --spawn_strategy=worker,local --debug_print_action_contexts &> $TEST_log || fail
+ expect_not_log "incompatible_list_based_execution_strategy_selection was not enabled"
+}
+
# Tests that you can set the spawn strategy flags to a list of strategies.
function test_multiple_strategies() {
- bazel build --incompatible_list_based_execution_strategy_selection \
- --spawn_strategy=worker,local --debug_print_action_contexts &> $TEST_log || fail
+ bazel build --spawn_strategy=worker,local --debug_print_action_contexts &> $TEST_log || fail
# Can't test for exact strategy names here, because they differ between platforms and products.
expect_log "\"\" = \[.*, .*\]"
}
@@ -61,8 +67,7 @@ function test_multiple_strategies() {
# Tests that the hardcoded Worker strategies are not introduced with the new
# strategy selection
function test_no_worker_defaults() {
- bazel build --incompatible_list_based_execution_strategy_selection \
- --debug_print_action_contexts &> $TEST_log || fail
+ bazel build --debug_print_action_contexts &> $TEST_log || fail
# Can't test for exact strategy names here, because they differ between platforms and products.
expect_not_log "\"Closure\""
expect_not_log "\"DexBuilder\""
@@ -71,21 +76,18 @@ function test_no_worker_defaults() {
# Tests that Bazel catches an invalid strategy list that has an empty string as an element.
function test_empty_strategy_in_list_is_forbidden() {
- bazel build --incompatible_list_based_execution_strategy_selection \
- --spawn_strategy=worker,,local --debug_print_action_contexts &> $TEST_log || true
+ bazel build --spawn_strategy=worker,,local --debug_print_action_contexts &> $TEST_log || true
expect_log "--spawn_strategy=worker,,local: Empty values are not allowed as part of this comma-separated list of options"
}
# Test that when you set a strategy to the empty string, it gets removed from the map of strategies
# and thus results in the default strategy being used (the one set via --spawn_strategy=).
function test_empty_strategy_means_default() {
- bazel build --incompatible_list_based_execution_strategy_selection \
- --spawn_strategy=worker,local --strategy=FooBar=local \
+ bazel build --spawn_strategy=worker,local --strategy=FooBar=local \
--debug_print_action_contexts &> $TEST_log || fail
expect_log "\"FooBar\" = "
- bazel build --incompatible_list_based_execution_strategy_selection \
- --spawn_strategy=worker,local --strategy=FooBar=local --strategy=FooBar= \
+ bazel build --spawn_strategy=worker,local --strategy=FooBar=local --strategy=FooBar= \
--debug_print_action_contexts &> $TEST_log || fail
expect_not_log "\"FooBar\" = "
}
| train | train | 2019-05-10T11:03:48 | "2019-02-20T14:45:07Z" | philwo | test |
bazelbuild/bazel/7486_7646 | bazelbuild/bazel | bazelbuild/bazel/7486 | bazelbuild/bazel/7646 | [
"timestamp(timedelta=1.0, similarity=0.8981737770239935)"
] | 85c70fbd0df0a0ba0d38dfa249c589c4dcb73b89 | c2cb0e0d28da02aa397b121b4841a74efcd06918 | [
"Seems like the flag has been flipped to true in https://github.com/bazelbuild/bazel/commit/2029b1a2332b336f64ee8d9f6433b205aecefc91. I'm closing the issue. ",
"The flag is not yet flipped: https://github.com/bazelbuild/bazel/blob/b137071ea03537ac00592a572dc0140fab985c53/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java#L618\r\n\r\nhttps://github.com/bazelbuild/bazel/commit/2029b1a2332b336f64ee8d9f6433b205aecefc91 was merged a testing branch, not master, to run the \"Bazel / Bazel@HEAD + Downstream\" pipeline on CI.",
"Ah, I did think the PR looked weird :)\r\nThanks for clarifying",
"I think it was released in 0.26 (https://blog.bazel.build/2019/05/28/bazel-0.26.0.html)."
] | [] | "2019-03-06T14:15:37Z" | [
"area-Windows",
"incompatible-change",
"team-OSS"
] | incompatible_windows_escape_jvm_flags: on Windows, enables tokenization and escaping of jvm_flags | # Description
Add --incompatible_windows_escape_jvm_flags flag (default: false). This flag only affects builds on Windows.
This flag has no effect on Linux/macOS/non-Windows.
## Background
When you build a java_binary or java_test on Windows, one of the outputs is an .exe file. This is called the launcher, and this is what you run with "bazel run" and "bazel test". The launcher's purpose is to set up the environment, compute the JVM command line (classpath, JVM flags, etc.) and launch the JVM.
The target-specific data (such as the classpath, main class name, but also the `jvm_flags` attribute from the BUILD-file) are embedded into the launcher as binary data. When you run the launcher, it will compute the command line to run the JVM as a subprocess (using the CreateProcessW system call), and that involves escaping the JVM flags so they can safely be passed to the subprcoess.
## The new flag
The --incompatible_windows_escape_jvm_flags flag affects how Bazel builds the launcher:
- whether or not Bazel will Bash-tokenize the jvm_flags before embedding them in the launcher, and
- whether the launcher will escape these flags using the [correct escaping logic](https://github.com/bazelbuild/bazel/blob/d19d4bae21d8706ae35a151b3135a6220189baa7/src/tools/launcher/util/launcher_util.cc#L182) or the [buggy one](https://github.com/bazelbuild/bazel/blob/d19d4bae21d8706ae35a151b3135a6220189baa7/src/tools/launcher/util/launcher_util.cc#L263).
When the flag is enabled:
- Bazel will Bash-tokenize java_binary.jvm_flags and java_test.jvm_flags (as documented by the Build Encyclopedia) before embedding them into the launcher.
- The launcher will properly escape these flags when it runs the JVM as a subprocess (using launcher_util::WindowsEscapeArg2).
- The result is that the jvm_flags declared in the BUILD file will arrive to the Java program as intended.
When the flag is disabled:
- Bazel does not Bash-tokenize the jvm_flags before embedding them in the launcher.
- The launcher escapes the flags with a Bash-like escaping logic (launcher_util::WindowsEscapeArg)
which cannot properly quote and escape everything.
- The result is that the jvm_flags declared in the BUILD file might get messed up as they are passed to the JVM, or the launcher may not even be able to run the JVM.
Related bug: https://github.com/bazelbuild/bazel/issues/7072
# Example
BUILD file:
```
java_binary(
name = "x",
srcs = ["A.java"],
main_class = "A",
jvm_flags = [
"-Darg0='hello world'",
r"-Darg1=\"C:\\Program\ Files\\\"",
],
)
```
A.java:
```
public class A {
public static void main(String[] args) {
System.out.printf(
"arg0=(%s)%narg1=(%s)%n",
System.getProperty("arg0"),
System.getProperty("arg1"));
}
}
```
The expected output of running the binary is:
```
arg0=(hello world)
arg1=("C:\Program Files\")
```
Currently the output is something like:
```
Error: Could not find or load main class
```
# Migration recipe
None, as of 2019-02-21.
We don't expect any breakages when this flag is enabled. However if it breaks your build or **if it breaks your java_binaries or java_tests**, please let us know so we can help fixing it and provide a migration recipe.
# Rollout plan
* Bazel 0.23.0 will not support this flag.
* Bazel 0.24.0 is expected to support this flag, with default value being `false`.
* Bazel 0.25.0 is expected to flip this flag to true. | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
index 53420f5ad18524..7d1d28590db9d9 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
@@ -643,7 +643,7 @@ public ImportDepsCheckingLevelConverter() {
@Option(
name = "incompatible_windows_escape_jvm_flags",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.OUTPUT_PARAMETERS,
effectTags = {
OptionEffectTag.ACTION_COMMAND_LINES,
| null | train | train | 2019-03-06T15:13:27 | "2019-02-21T10:29:19Z" | laszlocsomor | test |
bazelbuild/bazel/7502_8116 | bazelbuild/bazel | bazelbuild/bazel/7502 | bazelbuild/bazel/8116 | [
"timestamp(timedelta=0.0, similarity=0.8546884341422669)"
] | 137019fe22d88f04840e04a2c2a9db8a783a4cbe | a8b6c5b5e9e050c808be85f5d6ed6f968a8e25c9 | [
"Making a change in android_common jars will typically incur a lot of changes internally - please let us (@ahumesky / myself) know if you stumble upon any roadblocks. ",
"@jin to be clear: I still count on you / the Android team to work on unbundling the tools (#1055).\r\nThis issue is to keep track of the removal of the module itself and the outstanding blockers.",
"Ah, my bad, I misunderstood the assignment on this issue as you taking it up :) Thanks for clarifying! Unbundling the mobile tools will definitely be part of the ongoing Android Starlark migration (and land in bazelbuild/tools_android)."
] | [] | "2019-04-23T11:05:25Z" | [
"P2",
"team-Performance"
] | Remove dependency on the java.desktop module | It contributes 13MB to the the size of the embedded JDK which is ~40MB in total right now.
This list describes the paths in the `server.jar` which contain classes that depend on the java.desktop module:
- [x] `javax/xml/bind`
- [x] `com/android/ddmlib`
- [ ] `com/android/ide/common/util`
- [ ] `com/android/ide/common/rendering`
- [ ] `com/android/ide/common/rendering/api`
- [ ] `com/android/ide/common/vectordrawable`
- [ ] `com/android/tools/lint/checks`
- [ ] `com/android/sdklib/devices`
- [ ] `com/android/builder/png`
- [x] `lombok/ast/ecj`
- [x] `lombok/ast/grammar`
In turn `javax.xml.bind` is used by maven_jar (see #6799) and by the android_common dependency of `android_sdk_repository`.
`lombok/.*` comes from `third_party/android_common/com.android.tools.external.lombok_lombok-ast_0.2.3.jar`.
| [
"WORKSPACE"
] | [
"WORKSPACE"
] | [] | diff --git a/WORKSPACE b/WORKSPACE
index 5f03fb422aa173..607da272ad6b9d 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -192,9 +192,9 @@ http_file(
http_file(
name = "openjdk_linux_minimal",
downloaded_file_path = "zulu-linux-minimal.tar.gz",
- sha256 = "734cbfc9a5264e6cff4877d6694acb2305359531a503748879a84d4996b24932",
+ sha256 = "5123bc8dd21886761d1fd9ca0fb1898b3372d7243064a070ec81ca9c9d1a6791",
urls = [
- "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-linux_x64-minimal-7a3af9f6f98ce69c1ebd2931817c2664a18cf279-1552657479.tar.gz",
+ "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-linux_x64-minimal-524ae2ca2a782c9f15e00f08bd35b3f8ceacbd7f-1556011926.tar.gz",
],
)
@@ -231,9 +231,9 @@ http_file(
http_file(
name = "openjdk_macos_minimal",
downloaded_file_path = "zulu-macos-minimal.tar.gz",
- sha256 = "fd2a39d8947c53879f3d809c2ff783fc279d96f4ef2cccefb34d1d1b9cc6165f",
+ sha256 = "ac56e44db46fd56ac78b39b6823daed4faa74a2677ac340c7d217f863884ec0f",
urls = [
- "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-macosx_x64-minimal-7a3af9f6f98ce69c1ebd2931817c2664a18cf279-1552657467.tar.gz",
+ "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-macosx_x64-minimal-524ae2ca2a782c9f15e00f08bd35b3f8ceacbd7f-1556003114.tar.gz",
],
)
@@ -258,9 +258,9 @@ http_file(
http_file(
name = "openjdk_win_minimal",
downloaded_file_path = "zulu-win-minimal.zip",
- sha256 = "ce063face0ca9d539084731edf2ec92a3faa3c1d1b6915cf5ec1a09facbf52ac",
+ sha256 = "8e5dada6e9ebcc9ce29b4d051449bb95d3ee1e620e166da862224bbf15211f8b",
urls = [
- "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-win_x64-minimal-7a3af9f6f98ce69c1ebd2931817c2664a18cf279-1552657495.zip",
+ "https://mirror.bazel.build/openjdk/azul-zulu11.29.3-ca-jdk11.0.2/zulu11.29.3-ca-jdk11.0.2-win_x64-minimal-524ae2ca2a782c9f15e00f08bd35b3f8ceacbd7f-1556003136.zip",
],
)
| null | val | train | 2019-04-23T11:24:54 | "2019-02-22T09:01:15Z" | meisterT | test |
bazelbuild/bazel/7517_8401 | bazelbuild/bazel | bazelbuild/bazel/7517 | bazelbuild/bazel/8401 | [
"timestamp(timedelta=0.0, similarity=0.8626522113942371)"
] | ce8d52834c9acf9e1bda4f342d073d8cfd5a6737 | ca225c06177ed198c1457e6851895214e2e6b23e | [
"I notice that Bazel already uses ASM 7.0, which is the main dep of jacoco. Maybe upgrading wouldn't be a huge yak shave?",
"I've tried modifying Bazel to upgrade the jar myself, locally, but there's one jar I can't figure out how it was created: https://github.com/bazelbuild/bazel/tree/master/third_party/java/jacoco , `jacocoagent.jar`. It was checked in with the rest, but does not seem to correspond to any of the rest.",
"Any update? I'd like to get coverage working, its one of the key blockers to switching.",
"Thanks for the report, @dhalperi. I'm running into the same problem. I believe this completely breaks `bazel coverage` when used with jdk9+ due to https://github.com/jacoco/jacoco/pull/434.",
"I'll try to update tomorrow to jacoco 0.8.3.",
"Thank you @iirina !\r\n\r\nIs this still a recommended command to look at the code coverage output?\r\n\r\n```\r\nbazel coverage //... \\\r\n--combined_report=lcov --test_keep_going \\\r\n--coverage_report_generator=@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator:Main \\\r\n&& genhtml -o coverage bazel-out/_coverage/_coverage_report.dat && open coverage/index.html\r\n```\r\n\r\n(Still getting a ton of crashes, but elsewhere.)",
"@dhalperi Yes, that's right. Can you please open new issues for the other crashes? Thanks!",
"@iirina - will open other issues, if they are in Bazel. May well be in other libraries not working with java11 now. Just making sure I'm on good footing. Thanks again!"
] | [] | "2019-05-20T09:45:34Z" | [
"P1",
"team-Rules-Java"
] | bazel coverage crashes, likely due to old jacoco | ### Description of the problem / feature request:
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
`bazel coverage //projects/batfish-common-protocol/...` crashes in https://github.com/batfish/batfish/
The stack trace includes the following
```
91) testGetPartialMatchesSpecifierComplete(org.batfish.specifier.parboiled.ParserUtilsTest)
java.lang.IllegalAccessError: tried to access method org.batfish.specifier.parboiled.CommonParser.$jacocoInit()[Z from class org.batfish.specifier.parboiled.TestParser$$parboiled
at org.batfish.specifier.parboiled.TestParser$$parboiled.input(Unknown Source)
at org.batfish.specifier.parboiled.ParserUtilsTest.getRunner(ParserUtilsTest.java:25)
at org.batfish.specifier.parboiled.ParserUtilsTest.testGetPartialMatchesSpecifierComplete(ParserUtilsTest.java:132)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
```
which it looks like has been fixed by jacoco 0.7.8.
### What operating system are you running Bazel on?
macOS 10.14.3
### What's the output of `bazel info release`?
development version
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
built from bazel head using `bazel build //src:bazel && cp -f bazel-bin/src/bazel`
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
```
[email protected]:bazelbuild/bazel.git
2a1d99076eb46510484bd0bcbee0c607c03d4943
2a1d99076eb46510484bd0bcbee0c607c03d4943
```
### Have you found anything relevant by searching the web?
Yes.
* JaCoCo reports having fixed this issue in the 0.7.8 release notes. https://github.com/jacoco/jacoco/releases/tag/v0.7.8
* I also came across this related Bazel issue filed by Android team: https://github.com/bazelbuild/bazel/issues/3471
But that issue was apparently triaged in such a way that it was decided coverage/bazel were unimplicated and instead Android team should apply a workaround. I saw no discussion of whether Bazel can upgrade or why/why not, so I'm hoping there will be new discussion here.
As it's a third-party library causing the issue in our case, we're not able to apply the same workaround.
cc: @iirina | [
"src/java_tools/buildjar/java/com/google/devtools/build/buildjar/BUILD"
] | [
"src/java_tools/buildjar/java/com/google/devtools/build/buildjar/BUILD"
] | [
"src/java_tools/junitrunner/java/com/google/testing/coverage/BUILD",
"src/java_tools/junitrunner/java/com/google/testing/coverage/BranchDetailAnalyzer.java",
"src/java_tools/junitrunner/java/com/google/testing/coverage/MethodProbesMapper.java",
"src/test/java/com/google/devtools/build/android/desugar/BUILD"
] | diff --git a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/BUILD b/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/BUILD
index 2abd4be4544179..c1c859445a04d6 100644
--- a/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/BUILD
+++ b/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/BUILD
@@ -86,7 +86,7 @@ java_library(
"//src/main/protobuf:worker_protocol_java_proto",
"//third_party:guava",
"//third_party:jsr305",
- "//third_party/java/jacoco:core",
+ "//third_party/java/jacoco:core-0.8.3",
"//third_party/java/jdk/langtools:javac",
],
)
@@ -158,7 +158,7 @@ bootstrap_java_library(
"//third_party:bootstrap_guava_and_error_prone-jars",
"//third_party:jsr305-jars",
"//third_party/protobuf:protobuf-jars",
- "//third_party/java/jacoco:core-jars",
+ "//third_party/java/jacoco:core-jars-0.8.3",
"//third_party/grpc:bootstrap-grpc-jars",
"//third_party:tomcat_annotations_api-jars",
],
| diff --git a/src/java_tools/junitrunner/java/com/google/testing/coverage/BUILD b/src/java_tools/junitrunner/java/com/google/testing/coverage/BUILD
index 3be31af97b56e0..1a39e31d735ac1 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/coverage/BUILD
+++ b/src/java_tools/junitrunner/java/com/google/testing/coverage/BUILD
@@ -29,9 +29,9 @@ java_binary(
deps = [
":bitfield",
"//third_party:guava",
- "//third_party/java/jacoco:blaze-agent",
- "//third_party/java/jacoco:core",
- "//third_party/java/jacoco:report",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
+ "//third_party/java/jacoco:core-0.8.3",
+ "//third_party/java/jacoco:report-0.8.3",
],
)
diff --git a/src/java_tools/junitrunner/java/com/google/testing/coverage/BranchDetailAnalyzer.java b/src/java_tools/junitrunner/java/com/google/testing/coverage/BranchDetailAnalyzer.java
index 7ccd843d3ce96e..6ffb874987c31d 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/coverage/BranchDetailAnalyzer.java
+++ b/src/java_tools/junitrunner/java/com/google/testing/coverage/BranchDetailAnalyzer.java
@@ -52,7 +52,7 @@ public void visitCoverage(IClassCoverage coverage) {
public void analyzeClass(final ClassReader reader) {
final Map<Integer, BranchExp> lineToBranchExp = mapProbes(reader);
- long classid = CRC64.checksum(reader.b);
+ long classid = CRC64.classId(reader.b);
ExecutionData classData = executionData.get(classid);
if (classData == null) {
return;
diff --git a/src/java_tools/junitrunner/java/com/google/testing/coverage/MethodProbesMapper.java b/src/java_tools/junitrunner/java/com/google/testing/coverage/MethodProbesMapper.java
index 6900a37f71e416..f025ed127f09f2 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/coverage/MethodProbesMapper.java
+++ b/src/java_tools/junitrunner/java/com/google/testing/coverage/MethodProbesMapper.java
@@ -19,8 +19,8 @@
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import org.jacoco.core.internal.analysis.Instruction;
import org.jacoco.core.internal.flow.IFrame;
-import org.jacoco.core.internal.flow.Instruction;
import org.jacoco.core.internal.flow.LabelInfo;
import org.jacoco.core.internal.flow.MethodProbesVisitor;
import org.objectweb.asm.Handle;
@@ -60,7 +60,6 @@ public class MethodProbesMapper extends MethodProbesVisitor {
// Result
private Map<Integer, BranchExp> lineToBranchExp = new TreeMap();
-
public Map<Integer, BranchExp> result() {
return lineToBranchExp;
}
@@ -93,7 +92,7 @@ private void visitInsn() {
Instruction instruction = new Instruction(currentLine);
instructions.add(instruction);
if (lastInstruction != null) {
- instruction.setPredecessor(lastInstruction); // Update branch of lastInstruction
+ lastInstruction.addBranch(instruction, 0); // the first branch from last instruction
predecessors.put(instruction, lastInstruction); // Update local cache
}
@@ -131,12 +130,14 @@ public void visitFieldInsn(int opcode, String owner, String name, String desc) {
}
@Override
- public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
+ public void visitMethodInsn(int opcode, String owner, String name,
+ String desc, boolean itf) {
visitInsn();
}
@Override
- public void visitInvokeDynamicInsn(String name, String desc, Handle handle, Object... args) {
+ public void visitInvokeDynamicInsn(String name, String desc, Handle handle,
+ Object... args) {
visitInsn();
}
@@ -155,11 +156,12 @@ public void visitMultiANewArrayInsn(String desc, int dims) {
visitInsn();
}
+
// Methods that need to update the states
@Override
public void visitJumpInsn(int opcode, Label label) {
visitInsn();
- jumps.add(new Jump(lastInstruction, label));
+ jumps.add(new Jump(lastInstruction, label, 1));
}
@Override
@@ -181,14 +183,15 @@ private void visitSwitchInsn(Label dflt, Label[] labels) {
// Handle default transition
LabelInfo.resetDone(dflt);
- jumps.add(new Jump(lastInstruction, dflt));
+ int branch = 0;
+ jumps.add(new Jump(lastInstruction, dflt, branch));
LabelInfo.setDone(dflt);
// Handle other transitions
LabelInfo.resetDone(labels);
for (Label label : labels) {
if (!LabelInfo.isDone(label)) {
- jumps.add(new Jump(lastInstruction, label));
+ jumps.add(new Jump(lastInstruction, label, branch));
LabelInfo.setDone(label);
}
}
@@ -207,7 +210,7 @@ public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
private void addProbe(int probeId) {
// We do not add probes to the flow graph, but we need to update
// the branch count of the predecessor of the probe
- lastInstruction.addBranch();
+ lastInstruction.addBranch(false, 0);
probeToInsn.put(probeId, lastInstruction);
}
@@ -217,7 +220,7 @@ public void visitProbe(int probeId) {
// This function is only called when visiting a merge node which
// is a successor.
// It adds an probe point to the last instruction
- assert (lastInstruction != null);
+ assert(lastInstruction != null);
addProbe(probeId);
lastInstruction = null; // Merge point should have no predecessor.
@@ -236,14 +239,14 @@ public void visitInsnWithProbe(int opcode, int probeId) {
}
@Override
- public void visitTableSwitchInsnWithProbes(
- int min, int max, Label dflt, Label[] labels, IFrame frame) {
+ public void visitTableSwitchInsnWithProbes(int min, int max,
+ Label dflt, Label[] labels, IFrame frame) {
visitSwitchInsnWithProbes(dflt, labels);
}
@Override
- public void visitLookupSwitchInsnWithProbes(
- Label dflt, int[] keys, Label[] labels, IFrame frame) {
+ public void visitLookupSwitchInsnWithProbes(Label dflt,
+ int[] keys, Label[] labels, IFrame frame) {
visitSwitchInsnWithProbes(dflt, labels);
}
@@ -251,18 +254,18 @@ private void visitSwitchInsnWithProbes(Label dflt, Label[] labels) {
visitInsn();
LabelInfo.resetDone(dflt);
LabelInfo.resetDone(labels);
-
- visitTargetWithProbe(dflt);
+ int branch = 0;
+ visitTargetWithProbe(dflt, branch);
for (Label l : labels) {
- visitTargetWithProbe(l);
+ visitTargetWithProbe(l, branch);
}
}
- private void visitTargetWithProbe(Label label) {
+ private void visitTargetWithProbe(Label label, int branch) {
if (!LabelInfo.isDone(label)) {
int id = LabelInfo.getProbeId(label);
if (id == LabelInfo.NO_PROBE) {
- jumps.add(new Jump(lastInstruction, label));
+ jumps.add(new Jump(lastInstruction, label, branch));
} else {
// Note, in this case the instrumenter should insert intermediate labels
// for the probes. These probes will be added for the switch instruction.
@@ -276,7 +279,7 @@ private void visitTargetWithProbe(Label label) {
// If a CovExp of pred is ProbeExp, create a single-branch BranchExp and put it in the map.
// Also update the index of insn.
- private BranchExp getPredBranchExp(Instruction predecessor, Instruction insn) {
+ private BranchExp getPredBranchExp(Instruction predecessor) {
BranchExp result = null;
CovExp exp = insnToCovExp.get(predecessor);
if (exp instanceof ProbeExp) {
@@ -292,7 +295,8 @@ private BranchExp getPredBranchExp(Instruction predecessor, Instruction insn) {
}
// Update a branch predecessor and returns whether the BranchExp of the predecessor is new.
- private boolean updateBranchPredecessor(Instruction predecessor, Instruction insn, CovExp exp) {
+ private boolean updateBranchPredecessor(Instruction predecessor, Instruction insn,
+ CovExp exp) {
CovExp predExp = insnToCovExp.get(predecessor);
if (predExp == null) {
BranchExp branchExp = new BranchExp(exp);
@@ -301,7 +305,7 @@ private boolean updateBranchPredecessor(Instruction predecessor, Instruction ins
return true;
}
- BranchExp branchExp = getPredBranchExp(predecessor, insn);
+ BranchExp branchExp = getPredBranchExp(predecessor);
Integer branchIdx = insnToIdx.get(insn);
if (branchIdx == null) {
// Keep track of the instructions in the branches that are already added
@@ -319,7 +323,7 @@ public void visitEnd() {
for (Jump jump : jumps) {
Instruction insn = labelToInsn.get(jump.target);
- insn.setPredecessor(jump.source);
+ jump.source.addBranch(insn, jump.branch);
predecessors.put(insn, jump.source);
}
@@ -345,7 +349,7 @@ public void visitEnd() {
// has a probe, but the branch count is not > 1.
}
} else {
- if (insn.getBranches() > 1) {
+ if (insn.getBranchCounter().getTotalCount() > 1) {
exp = new BranchExp(exp);
}
insnToCovExp.put(insn, exp);
@@ -353,7 +357,7 @@ public void visitEnd() {
Instruction predecessor = predecessors.get(insn);
while (predecessor != null) {
- if (predecessor.getBranches() > 1) {
+ if (predecessor.getBranchCounter().getTotalCount() > 1) {
boolean isNewBranch = updateBranchPredecessor(predecessor, insn, exp);
if (!isNewBranch) {
// If the branch already exists, no need to visit predecessors any more.
@@ -371,7 +375,7 @@ public void visitEnd() {
// Merge branches in the instructions on the same line
for (Instruction insn : instructions) {
- if (insn.getBranches() > 1) {
+ if (insn.getBranchCounter().getTotalCount() > 1) {
CovExp insnExp = insnToCovExp.get(insn);
if (insnExp != null && (insnExp instanceof BranchExp)) {
BranchExp exp = (BranchExp) insnExp;
@@ -390,14 +394,18 @@ public void visitEnd() {
}
}
- /** Jumps between instructions and labels */
+ /**
+ * Jumps between instructions and labels
+ */
class Jump {
public final Instruction source;
public final Label target;
+ public final int branch;
- public Jump(Instruction i, Label l) {
+ public Jump(Instruction i, Label l, int b) {
source = i;
target = l;
+ branch = b;
}
}
-}
+}
\ No newline at end of file
diff --git a/src/test/java/com/google/devtools/build/android/desugar/BUILD b/src/test/java/com/google/devtools/build/android/desugar/BUILD
index 4780ad39155499..1812ef52748abe 100644
--- a/src/test/java/com/google/devtools/build/android/desugar/BUILD
+++ b/src/test/java/com/google/devtools/build/android/desugar/BUILD
@@ -329,7 +329,7 @@ java_test(
jvm_flags = [
# TODO (b/72181101): -Xbootclasspath/p is removed in JDK 9.
"-XX:+IgnoreUnrecognizedVMOptions",
- "-Xbootclasspath/a:$(location :testdata_desugared_core_library):$(location //third_party/java/jacoco:blaze-agent)",
+ "-Xbootclasspath/a:$(location :testdata_desugared_core_library):$(location //third_party/java/jacoco:blaze-agent-0.8.3)",
"--patch-module=java.base=$(location :testdata_desugared_core_library)",
],
tags = ["no_windows"],
@@ -341,7 +341,7 @@ java_test(
"//third_party:truth",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
],
)
@@ -351,7 +351,7 @@ java_test(
srcs = [
"StackMapBugTest.java",
],
- jvm_flags = ["-Xbootclasspath/a:$(location //third_party/java/jacoco:blaze-agent)"],
+ jvm_flags = ["-Xbootclasspath/a:$(location //third_party/java/jacoco:blaze-agent-0.8.3)"],
tags = ["no_windows"],
deps = [
":testdata_desugared_core_library", # Make tests run against desugared library
@@ -360,7 +360,7 @@ java_test(
"//third_party:truth",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
],
)
@@ -376,7 +376,7 @@ java_test(
],
jvm_flags = [
"-DDefaultMethodClassFixerTest.bootclasspath=$(location :android_jar_for_testing)",
- "-DDefaultMethodClassFixerTest.classpath=$(location :separate):$(location //third_party:guava-jars):$(location //third_party/java/jacoco:blaze-agent)",
+ "-DDefaultMethodClassFixerTest.classpath=$(location :separate):$(location //third_party:guava-jars):$(location //third_party/java/jacoco:blaze-agent-0.8.3)",
"-DDefaultMethodClassFixerTest.input=$(location :testdata_java8)",
],
tags = ["no_windows"],
@@ -389,7 +389,7 @@ java_test(
"//third_party:guava",
"//third_party:junit4",
"//third_party:truth",
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
],
)
@@ -821,7 +821,7 @@ genrule(
":testdata",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared.jar"],
@@ -829,7 +829,7 @@ genrule(
"--nodesugar_interface_method_bodies_if_needed -i $(location :testdata) -o $@ " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -850,13 +850,13 @@ genrule(
srcs = [
":generate_lambda_with_constant_arguments_in_test_data",
# Depend on Jacoco runtime in case testdata was built with coverage instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugar_generate_lambda_with_constant_arguments.jar"],
cmd = "$(location //src/tools/android/java/com/google/devtools/build/android/desugar:Desugar) " +
"-i $(location :generate_lambda_with_constant_arguments_in_test_data) -o $@ " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -889,7 +889,7 @@ genrule(
":separate",
":generate_synthetic_methods_with_lambda_names_in_test_data",
# Depend on Jacoco runtime in case testdata was built with coverage instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_with_synthetic_methods_with_lambda_names.jar"],
@@ -897,7 +897,7 @@ genrule(
"--nodesugar_interface_method_bodies_if_needed -i $(location :generate_synthetic_methods_with_lambda_names_in_test_data) -o $@ " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -911,7 +911,7 @@ genrule(
":testdata_desugared.jar",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_twice.jar"],
@@ -919,7 +919,7 @@ genrule(
"--nodesugar_interface_method_bodies_if_needed -i $(location :testdata_desugared.jar) -o $@ " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -936,7 +936,7 @@ genrule(
":testdata",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_without_lambda_desugared.jar"],
@@ -945,7 +945,7 @@ genrule(
"--nodesugar_try_with_resources_if_needed " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar) " +
"--only_desugar_javac9_for_lint",
tags = ["no_windows"],
@@ -1112,7 +1112,7 @@ genrule(
":testdata_java8",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_java8.jar"],
@@ -1122,7 +1122,7 @@ genrule(
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location :separate_java8) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1137,7 +1137,7 @@ genrule(
":testdata_java8_like_in_android_studio",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_java8_like_in_android_studio.jar"],
@@ -1149,7 +1149,7 @@ genrule(
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location :separate_java8) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1164,7 +1164,7 @@ genrule(
":testdata_java8",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_default_methods.jar"],
@@ -1174,7 +1174,7 @@ genrule(
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location :separate_java8) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1186,14 +1186,14 @@ genrule(
":separate_java8",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["separate_java8_desugared_default_methods.jar"],
cmd = "$(location //src/tools/android/java/com/google/devtools/build/android/desugar:Desugar) " +
"-i $(location :separate_java8) -o $@ " +
"--emit_dependency_metadata_as_needed " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1208,7 +1208,7 @@ genrule(
":testdata_java8",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_default_methods.output.txt"],
@@ -1218,7 +1218,7 @@ genrule(
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location :separate_java8) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar) " +
" &> $@",
tags = ["no_windows"],
@@ -1234,7 +1234,7 @@ genrule(
":testdata_desugared_default_methods.jar",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_default_methods_twice.jar"],
@@ -1243,7 +1243,7 @@ genrule(
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location :separate_java8) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1255,13 +1255,13 @@ genrule(
":testdata_core_library",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_core_library.jar"],
cmd = "$(location //src/tools/android/java/com/google/devtools/build/android/desugar:Desugar) " +
"--core_library -i $(location :testdata_core_library) -o $@ " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1275,7 +1275,7 @@ genrule(
":testdata_like_in_android_studio",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_like_in_android_studio.jar"],
@@ -1287,7 +1287,7 @@ genrule(
"--copy_bridges_from_classpath " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1301,7 +1301,7 @@ genrule(
":testdata_like_in_android_studio",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = [
@@ -1315,7 +1315,7 @@ genrule(
"--copy_bridges_from_classpath " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1329,7 +1329,7 @@ genrule(
":testdata_like_in_android_studio",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = [
@@ -1346,7 +1346,7 @@ genrule(
--copy_bridges_from_classpath \
--classpath_entry $(location :separate) \
--classpath_entry $(location //third_party:guava-jars) \
- --classpath_entry $(location //third_party/java/jacoco:blaze-agent) \
+ --classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) \
--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)
rm -rf $$tmpdir
""",
@@ -1365,7 +1365,7 @@ genrule(
":testdata_like_in_android_studio",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = [
@@ -1383,7 +1383,7 @@ genrule(
--copy_bridges_from_classpath \
--classpath_entry $(location :separate) \
--classpath_entry $(location //third_party:guava-jars) \
- --classpath_entry $(location //third_party/java/jacoco:blaze-agent) \
+ --classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) \
--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)
pushd $$tmpdirOut
$$pwddir/$(location //tools/zip:zipper) c $$pwddir/$(location testdata_desugared_from_directory_to_directory.jar) $$(find *)
@@ -1406,7 +1406,7 @@ genrule(
":testdata_like_in_android_studio",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = [
@@ -1423,7 +1423,7 @@ genrule(
--copy_bridges_from_classpath \
--classpath_entry $$tmpdir \
--classpath_entry $(location //third_party:guava-jars) \
- --classpath_entry $(location //third_party/java/jacoco:blaze-agent) \
+ --classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) \
--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)
rm -rf $$tmpdir
""",
@@ -1444,7 +1444,7 @@ genrule(
":testdata",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_for_try_with_resources.jar"],
@@ -1453,7 +1453,7 @@ genrule(
"--min_sdk_version 17 --desugar_try_with_resources_if_needed " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1466,7 +1466,7 @@ genrule(
name = "desugar_default_method_with_legacy_coverage",
srcs = [
"jacoco_0_7_5_default_method.jar",
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["jacoco_0_7_5_default_method_desugared.jar"],
@@ -1475,7 +1475,7 @@ genrule(
"--legacy_jacoco_fix " +
"--min_sdk_version 19 " +
"-i $(location :jacoco_0_7_5_default_method.jar) -o $@ " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1490,7 +1490,7 @@ genrule(
":testdata",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_for_NO_desugaring_try_with_resources.jar"],
@@ -1499,7 +1499,7 @@ genrule(
"--min_sdk_version 19 --desugar_try_with_resources_if_needed " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1513,7 +1513,7 @@ genrule(
":desugar_testdata_by_desugaring_try_with_resources",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_for_try_with_resources_twice.jar"],
@@ -1522,7 +1522,7 @@ genrule(
"--min_sdk_version 17 --desugar_try_with_resources_if_needed " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1821,13 +1821,13 @@ genrule(
":capture_lambda",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["capture_lambda_desugared.jar"],
cmd = "$(location //src/tools/android/java/com/google/devtools/build/android/desugar:Desugar) " +
"-i $(location :capture_lambda) -o $@ " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -1839,13 +1839,13 @@ genrule(
":capture_lambda_desugared.jar",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["capture_lambda_desugared_twice.jar"],
cmd = "$(location //src/tools/android/java/com/google/devtools/build/android/desugar:Desugar) " +
"-i $(location :capture_lambda_desugared.jar) -o $@ " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tags = ["no_windows"],
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
@@ -2008,7 +2008,7 @@ genrule(
":separate",
":testdata_java8",
"//third_party:guava-jars",
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["testdata_desugared_with_missing_dep.jar"],
@@ -2017,7 +2017,7 @@ genrule(
"--emit_dependency_metadata_as_needed " +
"--classpath_entry $(location :separate) " +
"--classpath_entry $(location //third_party:guava-jars) " +
- "--classpath_entry $(location //third_party/java/jacoco:blaze-agent) " +
+ "--classpath_entry $(location //third_party/java/jacoco:blaze-agent-0.8.3) " +
"--bootclasspath_entry $(location @bazel_tools//tools/android:android_jar)",
tools = ["//src/tools/android/java/com/google/devtools/build/android/desugar:Desugar"],
)
@@ -2027,7 +2027,7 @@ genrule(
srcs = [
":b68049457_caller",
":b68049457_interface",
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["b68049457_caller_desugared.jar"],
@@ -2096,7 +2096,7 @@ genrule(
"//third_party:guava-jars",
# Depend on Jacoco runtime in case testdata was built with coverage
# instrumentation
- "//third_party/java/jacoco:blaze-agent",
+ "//third_party/java/jacoco:blaze-agent-0.8.3",
"@bazel_tools//tools/android:android_jar",
],
outs = ["guava_at_head_desugared.jar"],
| train | train | 2019-05-20T12:44:06 | "2019-02-22T21:48:49Z" | dhalperi | test |
bazelbuild/bazel/7580_7581 | bazelbuild/bazel | bazelbuild/bazel/7580 | bazelbuild/bazel/7581 | [
"timestamp(timedelta=0.0, similarity=0.9072992591320629)"
] | 4b79c5311417c1ffbccfce0dbcd871e8c97ff90c | 765cb061ab1f9a0c14db0e2925d91655bc28ae7f | [
"Similar error in `incremental_install.py`:\r\n```\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 839, in <module>\r\n main()\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 828, in main\r\n extra_adb_args=FLAGS.extra_adb_arg)\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 756, in IncrementalInstall\r\n UploadDexes(adb, execroot, app_dir, temp_dir, dexmanifest, bool(apk))\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 367, in UploadDexes\r\n adb.Mkdir(dex_dir)\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 288, in Mkdir\r\n self._Shell(\"mkdir -p %s\" % d)\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 312, in _Shell\r\n return self._Exec([\"shell\", cmd])\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 182, in _Exec\r\n elif MultipleDevicesError.CheckError(stderr):\r\n File \"\\\\?\\c:\\tmp\\Bazel.runfiles_fbx84su6\\runfiles\\bazel_tools\\tools\\android\\incremental_install.py\", line 102, in CheckError\r\n return re.search(\"more than one (device and emulator|device|emulator)\", s)\r\n File \"c:\\Python37\\lib\\re.py\", line 183, in search\r\n return _compile(pattern, flags).search(string)\r\nTypeError: cannot use a string pattern on a bytes-like object\r\nTarget //src/main:app failed to build\r\nINFO: Elapsed time: 6.184s, Critical Path: 5.19s\r\nINFO: 1 process: 1 local.\r\nFAILED: Build did NOT complete successfully\r\n```"
] | [] | "2019-02-28T12:12:58Z" | [
"type: bug",
"P2",
"team-Android"
] | Android, Windows: mobile-install fails with Python3 | ### Description of the problem / feature request:
> Replace this line with your answer.
### Feature requests: what underlying problem are you trying to solve with this feature?
> Replace this line with your answer.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
Follow the Android Tutorial on bazel.build until "Run the App": https://docs.bazel.build/versions/master/tutorial/android-app.html#run-the-app
If you have Python3 on the `PATH`, it will fail like so:
```
C:\src\bazel-examples\android\tutorial>bazel mobile-install //src/main:app
INFO: Reading 'startup' options from c:\users\laszlocsomor\.bazelrc: --output_user_root=c:/_bazel
INFO: Options provided by the client:
Inherited 'common' options: --isatty=1 --terminal_columns=95
INFO: Options provided by the client:
Inherited 'build' options: --python_path=c:/Python37/python.exe
INFO: Reading rc options for 'mobile-install' from c:\users\laszlocsomor\.bazelrc:
Inherited 'build' options: --verbose_failures --announce_rc
INFO: Analysed target //src/main:app (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
ERROR: C:/src/bazel-examples/android/tutorial/src/main/BUILD:1:1: Injecting mobile install stub application failed (Exit 1): stubify_manifest.exe failed: error executing command
cd C:/_bazel/t5swfuxe/execroot/__main__
bazel-out/host/bin/external/bazel_tools/tools/android/stubify_manifest.exe --mode=mobile_install --input_manifest bazel-out/x64_windows-fastbuild/bin/src/main/_merged/app/AndroidManifest.xml --output_manifest bazel-out/x64_windows-fastbuild/bin/src/main/app_files/mobile_install/AndroidManifest.xml --output_datafile bazel-out/x64_windows-fastbuild/bin/src/main/app_files/stub_application_data/stub_application_data.txt
Execution platform: @bazel_tools//platforms:host_platform
Traceback (most recent call last):
File "\\?\c:\tmp\Bazel.runfiles_j8q3jcn7\runfiles\bazel_tools\tools\android\stubify_manifest.py", line 167, in <module>
main()
File "\\?\c:\tmp\Bazel.runfiles_j8q3jcn7\runfiles\bazel_tools\tools\android\stubify_manifest.py", line 154, in main
output_file.write("\n".join([old_application, app_package]))
TypeError: a bytes-like object is required, not 'str'
Target //src/main:app failed to build
INFO: Elapsed time: 2.607s, Critical Path: 1.37s
INFO: 7 processes: 5 local, 2 worker.
FAILED: Build did NOT complete successfully
```
It works with Python2.
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
`release 0.23.0`
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
```
$ git remote get-url origin ; git rev-parse master ; git rev-parse HEAD
[email protected]:bazelbuild/examples.git
b76d50e6719fe76cc6190d73aabb88822b71c4a5
b76d50e6719fe76cc6190d73aabb88822b71c4a5
``` | [
"tools/android/incremental_install.py",
"tools/android/stubify_manifest.py"
] | [
"tools/android/incremental_install.py",
"tools/android/stubify_manifest.py"
] | [] | diff --git a/tools/android/incremental_install.py b/tools/android/incremental_install.py
index 0638c1b34a4235..d7b9c48d7f29cc 100644
--- a/tools/android/incremental_install.py
+++ b/tools/android/incremental_install.py
@@ -173,6 +173,8 @@ def _Exec(self, adb_args):
# Check these first so that the more specific error gets raised instead of
# the more generic AdbError.
+ stdout = stdout.decode()
+ stderr = stderr.decode()
if "device not found" in stderr:
raise DeviceNotFoundError()
elif "device unauthorized" in stderr:
diff --git a/tools/android/stubify_manifest.py b/tools/android/stubify_manifest.py
index d07287e3fdf201..f2e8a48f0fe89e 100644
--- a/tools/android/stubify_manifest.py
+++ b/tools/android/stubify_manifest.py
@@ -151,7 +151,7 @@ def main():
output_xml.write(new_manifest)
with open(FLAGS.output_datafile, "wb") as output_file:
- output_file.write("\n".join([old_application, app_package]))
+ output_file.write("\n".join([old_application, app_package]).encode())
elif FLAGS.mode == "instant_run":
with open(FLAGS.input_manifest, "rb") as input_manifest:
| null | train | train | 2019-02-28T11:49:27 | "2019-02-28T11:54:14Z" | laszlocsomor | test |
bazelbuild/bazel/7705_7712 | bazelbuild/bazel | bazelbuild/bazel/7705 | bazelbuild/bazel/7712 | [
"timestamp(timedelta=66892.0, similarity=0.8556415768193818)"
] | 7901dd9f6d84ea0342261e17706ad9c1e14b999d | 38fa0725eae5770cff51f051e8415cfdd6f9460b | [
"/cc @asuffield"
] | [] | "2019-03-13T16:30:51Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Windows, Bazel client: envvars cannot have UNC paths | ### Description of the problem / feature request:
Bazel mishandles envvars with UNC paths.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
C:\src\tmp>set java
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_162
C:\src\tmp>set JAVA_HOME=\\?\%JAVA_HOME%
C:\src\tmp>set java
JAVA_HOME=\\?\C:\Program Files\Java\jdk1.8.0_162
C:\src\tmp>bazel run :foo
WARNING: Ignoring JAVA_HOME, because it must point to a JDK, not a JRE.
```
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
release 0.23.1 | [
"src/main/cpp/util/file_windows.cc",
"src/main/cpp/util/path_platform.h",
"src/main/cpp/util/path_windows.cc",
"src/main/tools/build-runfiles-windows.cc"
] | [
"src/main/cpp/util/file_windows.cc",
"src/main/cpp/util/path_platform.h",
"src/main/cpp/util/path_windows.cc",
"src/main/tools/build-runfiles-windows.cc"
] | [
"src/test/cpp/util/path_windows_test.cc"
] | diff --git a/src/main/cpp/util/file_windows.cc b/src/main/cpp/util/file_windows.cc
index 62a19f6f21ac63..9fd150e2851612 100644
--- a/src/main/cpp/util/file_windows.cc
+++ b/src/main/cpp/util/file_windows.cc
@@ -625,17 +625,7 @@ string MakeCanonical(const char* path) {
return "";
}
- // Convert the path to lower-case.
- size_t size =
- wcslen(long_realpath.get()) - (HasUncPrefix(long_realpath.get()) ? 4 : 0);
- unique_ptr<WCHAR[]> lcase_realpath(new WCHAR[size + 1]);
- const WCHAR* p_from = RemoveUncPrefixMaybe(long_realpath.get());
- WCHAR* p_to = lcase_realpath.get();
- while (size-- > 0) {
- *p_to++ = towlower(*p_from++);
- }
- *p_to = 0;
- return string(WstringToCstring(lcase_realpath.get()).get());
+ return string(WstringToCstring(RemoveUncPrefixMaybe(long_realpath.get())).get());
}
static bool CanReadFileW(const wstring& path) {
@@ -799,12 +789,6 @@ bool MakeDirectories(const string& path, unsigned int mode) {
return MakeDirectoriesW(wpath, mode);
}
-static inline void ToLowerW(WCHAR* p) {
- while (*p) {
- *p++ = towlower(*p);
- }
-}
-
std::wstring GetCwdW() {
static constexpr size_t kBufSmall = MAX_PATH;
WCHAR buf[kBufSmall];
@@ -816,7 +800,6 @@ std::wstring GetCwdW() {
}
if (len < kBufSmall) {
- ToLowerW(buf);
return std::wstring(buf);
}
@@ -827,7 +810,6 @@ std::wstring GetCwdW() {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "GetCurrentDirectoryW failed (error " << err << ")";
}
- ToLowerW(buf_big.get());
return std::wstring(buf_big.get());
}
diff --git a/src/main/cpp/util/path_platform.h b/src/main/cpp/util/path_platform.h
index 329380f7b9adaa..8d4086a8e6aa55 100644
--- a/src/main/cpp/util/path_platform.h
+++ b/src/main/cpp/util/path_platform.h
@@ -136,7 +136,7 @@ template bool AsAbsoluteWindowsPath<char>(const char *, std::wstring *,
template bool AsAbsoluteWindowsPath<wchar_t>(const wchar_t *, std::wstring *,
std::string *);
-// Same as `AsWindowsPath`, but returns a lowercase 8dot3 style shortened path.
+// Same as `AsWindowsPath`, but returns a 8dot3 style shortened path.
// Result will never have a UNC prefix, nor a trailing "/" or "\".
// Works also for non-existent paths; shortens as much of them as it can.
// Also works for non-existent drives.
diff --git a/src/main/cpp/util/path_windows.cc b/src/main/cpp/util/path_windows.cc
index 0f4227674cdc78..45a932eb44c39e 100644
--- a/src/main/cpp/util/path_windows.cc
+++ b/src/main/cpp/util/path_windows.cc
@@ -65,12 +65,12 @@ std::string ConvertPath(const std::string& path) {
// The path may not be Windows-style and may not be normalized, so convert it.
std::string converted_path;
std::string error;
- if (!blaze_util::AsWindowsPath(path, &converted_path, &error)) {
+ if (!blaze_util::AsWindowsPath(
+ HasUncPrefix(path.c_str()) ? path.substr(4) : path, &converted_path,
+ &error)) {
BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
<< "ConvertPath(" << path << "): AsWindowsPath failed: " << error;
}
- std::transform(converted_path.begin(), converted_path.end(),
- converted_path.begin(), ::tolower);
return converted_path;
}
@@ -83,7 +83,6 @@ std::string MakeAbsolute(const std::string& path) {
<< "MakeAbsolute(" << path
<< "): AsAbsoluteWindowsPath failed: " << error;
}
- std::transform(wpath.begin(), wpath.end(), wpath.begin(), ::towlower);
return std::string(
WstringToCstring(RemoveUncPrefixMaybe(wpath.c_str())).get());
}
@@ -115,7 +114,9 @@ std::string MakeAbsoluteAndResolveEnvvars(const std::string& path) {
}
bool CompareAbsolutePaths(const std::string& a, const std::string& b) {
- return ConvertPath(a) == ConvertPath(b);
+ std::string aa = ConvertPath(a);
+ std::string bb = ConvertPath(b);
+ return aa.size() == bb.size() && _stricmp(aa.c_str(), bb.c_str()) == 0;
}
std::string PathAsJvmFlag(const std::string& path) {
@@ -530,7 +531,6 @@ bool AsShortWindowsPath(const std::string& path, std::string* result,
}
result->assign(WstringToCstring(wresult.c_str()).get());
- ToLower(result);
return true;
}
@@ -570,7 +570,8 @@ static char GetCurrentDrive() {
std::wstring cwd = GetCwdW();
wchar_t wdrive = RemoveUncPrefixMaybe(cwd.c_str())[0];
wchar_t offset = wdrive >= L'A' && wdrive <= L'Z' ? L'A' : L'a';
- return 'a' + wdrive - offset;
+ bool upper = wdrive >= L'A' && wdrive <= L'Z';
+ return (upper ? 'A' : 'a') + wdrive - offset;
}
namespace testing {
diff --git a/src/main/tools/build-runfiles-windows.cc b/src/main/tools/build-runfiles-windows.cc
index edb1c916605baf..f371411ab8f455 100644
--- a/src/main/tools/build-runfiles-windows.cc
+++ b/src/main/tools/build-runfiles-windows.cc
@@ -278,9 +278,7 @@ class RunfilesCreator {
if (expected_target == manifest_file_map.end() ||
expected_target->second.empty()
- // Both paths are normalized paths in lower case, we can compare
- // them directly.
- || target != expected_target->second.c_str() ||
+ || !_wcsicmp(target.c_str(), expected_target->second.c_str()) ||
blaze_util::IsDirectoryW(target) != is_dir) {
if (is_dir) {
RemoveDirectoryOrDie(subpath);
| diff --git a/src/test/cpp/util/path_windows_test.cc b/src/test/cpp/util/path_windows_test.cc
index ef29083dfd962c..28c7514597ed02 100644
--- a/src/test/cpp/util/path_windows_test.cc
+++ b/src/test/cpp/util/path_windows_test.cc
@@ -245,13 +245,13 @@ TEST(PathWindowsTest, TestAsWindowsPath) {
EXPECT_TRUE(error.find("Unix-style") != string::npos);
// Absolute-on-current-drive path gets a drive letter.
- ASSERT_TRUE(AsWindowsPath("\\foo", &actual, nullptr));
- ASSERT_EQ(wstring(1, GetCwd()[0]) + L":\\foo", actual);
+ ASSERT_TRUE(AsWindowsPath("\\Foo", &actual, nullptr));
+ ASSERT_EQ(wstring(1, GetCwd()[0]) + L":\\Foo", actual);
// Even for long paths, AsWindowsPath doesn't add a "\\?\" prefix (it's the
// caller's duty to do so).
- wstring wlongpath(L"dummy_long_path\\");
- string longpath("dummy_long_path/");
+ wstring wlongpath(L"DUMMY_long_path\\");
+ string longpath("DUMMY_long_path/");
while (longpath.size() <= MAX_PATH) {
wlongpath += wlongpath;
longpath += longpath;
@@ -299,7 +299,7 @@ TEST(PathWindowsTest, TestAsShortWindowsPath) {
ASSERT_EQ(string("NUL"), actual);
ASSERT_TRUE(AsShortWindowsPath("C://", &actual, nullptr));
- ASSERT_EQ(string("c:\\"), actual);
+ ASSERT_EQ(string("C:\\"), actual);
string error;
ASSERT_FALSE(AsShortWindowsPath("/C//", &actual, &error));
@@ -308,6 +308,9 @@ TEST(PathWindowsTest, TestAsShortWindowsPath) {
// The A drive usually doesn't exist but AsShortWindowsPath should still work.
// Here we even have multiple trailing slashes, that should be handled too.
ASSERT_TRUE(AsShortWindowsPath("A://", &actual, nullptr));
+ ASSERT_EQ(string("A:\\"), actual);
+
+ ASSERT_TRUE(AsShortWindowsPath("a://", &actual, nullptr));
ASSERT_EQ(string("a:\\"), actual);
// Assert that we can shorten the TEST_TMPDIR.
@@ -327,17 +330,17 @@ TEST(PathWindowsTest, TestAsShortWindowsPath) {
ASSERT_NE(actual.back(), '/');
ASSERT_NE(actual.back(), '\\');
- // Assert shortening another long path, and that the result is lowercased.
+ // Assert shortening another long path, and that the result is not lowercased.
string dirname(JoinPath(short_tmpdir, "LONGpathNAME"));
ASSERT_EQ(0, mkdir(dirname.c_str()));
ASSERT_TRUE(PathExists(dirname));
ASSERT_TRUE(AsShortWindowsPath(dirname, &actual, nullptr));
- ASSERT_EQ(short_tmpdir + "\\longpa~1", actual);
+ ASSERT_EQ(short_tmpdir + "\\LONGPA~1", actual);
- // Assert shortening non-existent paths.
+ // Assert shortening non-existent paths. Case is preserved.
ASSERT_TRUE(AsShortWindowsPath(JoinPath(tmpdir, "NonExistent/FOO"), &actual,
nullptr));
- ASSERT_EQ(short_tmpdir + "\\nonexistent\\foo", actual);
+ ASSERT_EQ(short_tmpdir + "\\NonExistent\\FOO", actual);
}
TEST(PathWindowsTest, TestMsysRootRetrieval) {
@@ -371,23 +374,22 @@ TEST(PathWindowsTest, IsWindowsDevNullTest) {
}
TEST(PathWindowsTest, ConvertPathTest) {
- EXPECT_EQ("c:\\foo", ConvertPath("C:\\FOO"));
+ EXPECT_EQ("C:\\FOO", ConvertPath("C:\\FOO"));
EXPECT_EQ("c:\\", ConvertPath("c:/"));
- EXPECT_EQ("c:\\foo\\bar", ConvertPath("c:/../foo\\BAR\\.\\"));
+ EXPECT_EQ("c:\\foo\\BAR", ConvertPath("c:/../foo\\BAR\\.\\"));
}
TEST(PathWindowsTest, MakeAbsolute) {
- EXPECT_EQ("c:\\foo\\bar", MakeAbsolute("C:\\foo\\BAR"));
- EXPECT_EQ("c:\\foo\\bar", MakeAbsolute("C:/foo/bar"));
- EXPECT_EQ("c:\\foo\\bar", MakeAbsolute("C:\\foo\\bar\\"));
- EXPECT_EQ("c:\\foo\\bar", MakeAbsolute("C:/foo/bar/"));
- EXPECT_EQ(blaze_util::AsLower(blaze_util::GetCwd()) + "\\foo",
- MakeAbsolute("foo"));
-
- EXPECT_EQ("nul", MakeAbsolute("NUL"));
- EXPECT_EQ("nul", MakeAbsolute("Nul"));
- EXPECT_EQ("nul", MakeAbsolute("nul"));
- EXPECT_EQ("nul", MakeAbsolute("/dev/null"));
+ EXPECT_EQ("C:\\foo\\BAR", MakeAbsolute("C:\\foo\\BAR"));
+ EXPECT_EQ("C:\\foo\\Bar", MakeAbsolute("C:/foo/Bar"));
+ EXPECT_EQ("C:\\foo\\Bar", MakeAbsolute("C:\\foo\\Bar\\"));
+ EXPECT_EQ("C:\\foo\\Bar", MakeAbsolute("C:/foo/Bar/"));
+ EXPECT_EQ(blaze_util::GetCwd() + "\\Foo", MakeAbsolute("Foo"));
+
+ EXPECT_EQ("NUL", MakeAbsolute("NUL"));
+ EXPECT_EQ("NUL", MakeAbsolute("Nul"));
+ EXPECT_EQ("NUL", MakeAbsolute("nul"));
+ EXPECT_EQ("NUL", MakeAbsolute("/dev/null"));
EXPECT_EQ("", MakeAbsolute(""));
}
@@ -399,16 +401,16 @@ TEST(PathWindowsTest, MakeAbsoluteAndResolveEnvvars_WithTmpdir) {
char buf[MAX_PATH] = {0};
DWORD len = ::GetEnvironmentVariableA("TEST_TMPDIR", buf, MAX_PATH);
const std::string tmpdir = buf;
- const std::string expected_tmpdir_bar = ConvertPath(tmpdir + "\\bar");
+ const std::string expected_tmpdir_bar = ConvertPath(tmpdir + "\\Bar");
EXPECT_EQ(expected_tmpdir_bar,
- MakeAbsoluteAndResolveEnvvars("%TEST_TMPDIR%\\bar"));
+ MakeAbsoluteAndResolveEnvvars("%TEST_TMPDIR%\\Bar"));
EXPECT_EQ(expected_tmpdir_bar,
- MakeAbsoluteAndResolveEnvvars("%Test_Tmpdir%\\bar"));
+ MakeAbsoluteAndResolveEnvvars("%Test_Tmpdir%\\Bar"));
EXPECT_EQ(expected_tmpdir_bar,
- MakeAbsoluteAndResolveEnvvars("%test_tmpdir%\\bar"));
+ MakeAbsoluteAndResolveEnvvars("%test_tmpdir%\\Bar"));
EXPECT_EQ(expected_tmpdir_bar,
- MakeAbsoluteAndResolveEnvvars("%test_tmpdir%/bar"));
+ MakeAbsoluteAndResolveEnvvars("%test_tmpdir%/Bar"));
}
TEST(PathWindowsTest, MakeAbsoluteAndResolveEnvvars_LongPaths) {
@@ -418,4 +420,25 @@ TEST(PathWindowsTest, MakeAbsoluteAndResolveEnvvars_LongPaths) {
EXPECT_EQ(long_path, MakeAbsoluteAndResolveEnvvars("%long%"));
}
+TEST(PathWindowsTest, CompareAbsolutePathsTest) {
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "c:/foo"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "c:/foo/"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "C:\\FOO"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "C:\\FOO\\"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "\\\\?\\C:\\FOO"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "\\\\?\\C:\\FOO\\"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "C:\\BAR\\..\\FOO"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "C:\\BAR\\..\\FOO\\"));
+ EXPECT_TRUE(CompareAbsolutePaths("c:\\foo", "C:\\BAR\\..\\FOO\\"));
+
+ EXPECT_TRUE(CompareAbsolutePaths("NUL", "Nul"));
+ EXPECT_TRUE(CompareAbsolutePaths("NUL", "nul"));
+ EXPECT_TRUE(CompareAbsolutePaths("NUL", "/dev/null"));
+
+ EXPECT_FALSE(CompareAbsolutePaths("c:\\foo", "c:\\foo."));
+ EXPECT_FALSE(CompareAbsolutePaths("c:\\foo", "c:\\foo "));
+ EXPECT_FALSE(CompareAbsolutePaths("c:\\foo", "\\\\?\\c:\\foo."));
+ EXPECT_FALSE(CompareAbsolutePaths("c:\\foo", "c:\\bar"));
+}
+
} // namespace blaze_util
| train | train | 2019-03-13T17:31:02 | "2019-03-13T09:32:39Z" | laszlocsomor | test |
bazelbuild/bazel/7767_7785 | bazelbuild/bazel | bazelbuild/bazel/7767 | bazelbuild/bazel/7785 | [
"timestamp(timedelta=0.0, similarity=0.911151360643512)"
] | 15b70bb63e5495290900de9303cbebb0ff12210b | 36ef38d1c62cfc2a84a8a5596eefaf18c80fa6a2 | [
"@iirina could you take a look please?",
"You can use a newer version of jarjar with the following repos/build targets:\r\n```python\r\nJCENTER = \"http://jcenter.bintray.com\"\r\njvm_maven_import_external(\r\n name = \"com_google_jarjar\",\r\n licenses = [\"notice\"],\r\n artifact = \"org.pantsbuild:jarjar:1.6.6\",\r\n artifact_sha256 = \"965ab4c68b7ff6164841d7034cf5b0d5397205e35903c372db981a3660ad72f1\",\r\n server_urls = [JCENTER],\r\n deps = [\r\n \"@org_ow2_asm_asm\",\r\n ],\r\n)\r\njvm_maven_import_external(\r\n name = \"org_ow2_asm_asm\",\r\n licenses = [\"notice\"],\r\n artifact = \"org.ow2.asm:asm:6.2\",\r\n server_urls = [JCENTER],\r\n deps = [\r\n \"@org_ow2_asm_asm_commons\",\r\n ],\r\n)\r\njvm_maven_import_external(\r\n name = \"org_ow2_asm_asm_commons\",\r\n licenses = [\"notice\"],\r\n artifact = \"org.ow2.asm:asm-commons:6.2\",\r\n server_urls = [JCENTER],\r\n)\r\n\r\n\r\njava_binary(\r\n name = \"jarjar\",\r\n create_executable = True,\r\n main_class = \"org.pantsbuild.jarjar.Main\",\r\n visibility = [\"//visibility:public\"],\r\n runtime_deps = [\r\n \"@com_google_jarjar\",\r\n ]\r\n)\r\n```",
"@brettchabot indeed jarjar was moved out of the bazel binary as part of the effort to move the Java tools to a remote repository. I'll send a PR to re-add the targets, but they will refrence JarJar from the remote tools.",
"@iirina what is the new target one should use ?",
"@steeve you can use `@remote_java_tools_linux//:JarJar`",
"@iirina it seems on my machine (macos) it's `@remote_java_tools_darwin//:JarJar`. It makes it hard to depend on since the repo name has the os inside :(",
"You can add an alias if you want:\r\n\r\n```\r\nalias(\r\n name = JarJar,\r\n actual = select({\r\n \"@bazel_tools//src/conditions:linux_x86_64\": [\"@remote_java_tools_linux//:JarJar\"],\r\n \"@bazel_tools//src/conditions:darwin\": [\"@remote_java_tools_darwin//:JarJar\"],\r\n \"@bazel_tools//src/conditions:darwin_x86_64\": [\"@remote_java_tools_darwin//:JarJar\"],\r\n \"@bazel_tools//src/conditions:windows\": [\"@remote_java_tools_windows//:JarJar\"],\r\n # Any repository can be used.\r\n \"@bazel_tools//conditions:default\": [\"@remote_java_tools_linux//:JarJar\"],\r\n })\r\n)\r\n```\r\n\r\nor use any of the repos since JarJar is a deploy jar and is platform agnostic:\r\n\r\n```\r\nalias(\r\n name = \"JarJar\",\r\n actual = \"@remote_java_tools_darwin//:JarJar\"\r\n)\r\n",
"That's great thank you !",
"> @steeve you can use `@remote_java_tools_linux//:JarJar`\r\n\r\n@iirina , I am not able to see the JarJar target now. I can see only the below\r\n\r\njenkins@bazel5-d57575cd6-sdxvb:~/repo$ tools/bazel query \"@remote_java_tools_linux//:*\"\r\nAnother command (pid=29262) is running. Waiting for it to complete on the server (server_pid=9187)...\r\n@remote_java_tools_linux//:BUILD\r\n@remote_java_tools_linux//:ijar_prebuilt_binary\r\n@remote_java_tools_linux//:java_tools/ijar/ijar\r\n@remote_java_tools_linux//:java_tools/ijar/ijar.exe\r\n@remote_java_tools_linux//:java_tools/src/tools/singlejar/singlejar_local\r\n@remote_java_tools_linux//:java_tools/src/tools/singlejar/singlejar_local.exe\r\n@remote_java_tools_linux//:prebuilt_singlejar\r\n@remote_java_tools_linux//:windows\r\nLoading: 1 packages loaded\r\njenkins@bazel5-d57575cd6-sdxvb:~/repo$ \r\n\r\nDid this get moved somewhere else?\r\nI am using bazel 6.4.0"
] | [] | "2019-03-20T22:35:46Z" | [
"P1",
"team-Rules-Java"
] | @bazel_tools//third_party/jarjar was removed | ### Description of the problem / feature request:
androidx.test (github/android/android_test) is broken HEAD with bazel 0.23.2 with the following error:
Step #2: ERROR: /workspace/ext/junit/java/androidx/test/ext/junit/BUILD.bazel:38:1: no such package '@bazel_tools//third_party/jarjar': BUILD file not found on package path and referenced by '//ext/junit/java/androidx/test/ext/junit:junit_release_jarjared'
It looks like @bazel_tools//third_party/jarjar has moved.
I chatted with @jin , he suggested filing an issue since this is a breaking change
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
See https://github.com/android/android-test/blob/master/CONTRIBUTING.md
bazel build :axt_m2repository
### What operating system are you running Bazel on?
linux
### What's the output of `bazel info release`?
release 0.23.2
### Any other information, logs, or outputs that you want to share?
| [
"src/BUILD",
"src/create_embedded_tools.py",
"third_party/jarjar/BUILD",
"tools/jdk/BUILD"
] | [
"src/BUILD",
"src/create_embedded_tools.py",
"third_party/jarjar/BUILD",
"third_party/jarjar/BUILD.tools",
"tools/jdk/BUILD"
] | [] | diff --git a/src/BUILD b/src/BUILD
index 111a1e26e7b2f3..ec9c7870096f28 100644
--- a/src/BUILD
+++ b/src/BUILD
@@ -124,6 +124,7 @@ JAVA_TOOLS = [
"//src/tools/singlejar:embedded_tools",
"//src/java_tools/import_deps_checker/java/com/google/devtools/build/importdeps:embedded_tools",
"//third_party/java/jacoco:srcs",
+ "//third_party/jarjar:embedded_build_and_license",
] + select({
"//src/conditions:arm": [],
"//conditions:default": [
diff --git a/src/create_embedded_tools.py b/src/create_embedded_tools.py
index dfb7b11c98ac0e..3d64886898d85c 100644
--- a/src/create_embedded_tools.py
+++ b/src/create_embedded_tools.py
@@ -44,6 +44,8 @@
('*def_parser.exe', lambda x: 'tools/def_parser/def_parser.exe'),
('*zipper.exe', lambda x: 'tools/zip/zipper/zipper.exe'),
('*zipper', lambda x: 'tools/zip/zipper/zipper'),
+ ('*third_party/jarjar/BUILD.tools', lambda x: 'third_party/jarjar/BUILD'),
+ ('*third_party/jarjar/LICENSE', lambda x: 'third_party/jarjar/LICENSE'),
('*src/objc_tools/*',
lambda x: 'tools/objc/precomp_' + os.path.basename(x)),
('*xcode*StdRedirect.dylib', lambda x: 'tools/objc/StdRedirect.dylib'),
diff --git a/third_party/jarjar/BUILD b/third_party/jarjar/BUILD
index 6dc81a18e414d9..2d25947b9fdab8 100644
--- a/third_party/jarjar/BUILD
+++ b/third_party/jarjar/BUILD
@@ -7,6 +7,14 @@ filegroup(
srcs = glob(["**"]),
)
+filegroup(
+ name = "embedded_build_and_license",
+ srcs = [
+ "BUILD.tools",
+ "LICENSE",
+ ],
+)
+
# jarjar_bin
java_binary(
name = "jarjar_command",
diff --git a/third_party/jarjar/BUILD.tools b/third_party/jarjar/BUILD.tools
new file mode 100644
index 00000000000000..3c759aa63c03ae
--- /dev/null
+++ b/third_party/jarjar/BUILD.tools
@@ -0,0 +1,19 @@
+package(default_visibility = ["//visibility:public"])
+
+licenses(["notice"]) # Apache 2.0
+
+load(
+ "//tools/jdk:remote_java_tools_aliases.bzl",
+ "remote_java_tools_java_import",
+)
+
+remote_java_tools_java_import(
+ name = "jarjar_import",
+ target = ":JarJar",
+)
+
+java_binary(
+ name = "jarjar_bin",
+ main_class = "com.tonicsystems.jarjar.Main",
+ runtime_deps = [":jarjar_import"],
+)
diff --git a/tools/jdk/BUILD b/tools/jdk/BUILD
index ecd2fa784a5b51..15376a4dba3c47 100644
--- a/tools/jdk/BUILD
+++ b/tools/jdk/BUILD
@@ -1,17 +1,17 @@
load(
"//tools/jdk:default_java_toolchain.bzl",
- "default_java_toolchain",
- "java_runtime_files",
"JDK8_JVM_OPTS",
"bootclasspath",
+ "default_java_toolchain",
+ "java_runtime_files",
)
load(
"//tools/jdk:java_toolchain_alias.bzl",
- "java_toolchain_alias",
- "java_runtime_alias",
"java_host_runtime_alias",
- "legacy_java_toolchain_alias",
+ "java_runtime_alias",
+ "java_toolchain_alias",
"legacy_java_runtime_alias",
+ "legacy_java_toolchain_alias",
)
load(
"//tools/jdk:remote_java_tools_aliases.bzl",
@@ -405,9 +405,9 @@ alias(
actual = "//third_party/java/jacoco:blaze-agent",
)
-java_import(
+remote_java_tools_java_import(
name = "JarJar",
- jars = [":jarjar_command_deploy.jar"],
+ target = ":JarJar",
)
test_suite(
| null | train | train | 2019-03-20T23:20:12 | "2019-03-19T16:40:04Z" | brettchabot | test |
bazelbuild/bazel/7794_7796 | bazelbuild/bazel | bazelbuild/bazel/7794 | bazelbuild/bazel/7796 | [
"timestamp(timedelta=1.0, similarity=0.883872832229377)"
] | 074c9c494b6d4d1252a1f8d31094da3f36b30fdf | b0b058d65be8dabad673e8c0e54b3498532097e5 | [
"Does this issue only happen when `test.log` is very large?",
"no it's independent of the test.log size.",
"The workaround for this issue is to use `--experimental_split_xml_generation=false`"
] | [] | "2019-03-21T14:54:14Z" | [
"P1",
"team-Remote-Exec"
] | pass platform and execution requirements to xml generating spawn | The fix for https://github.com/bazelbuild/bazel/issues/4608 splits a test action into two spawns. The first spawn runs the actual test and the second spawn declares the `test.log` as an input and produces a test.xml file.
We found an issue where a `sh_test` target was marked as `no-remote` but the test.xml-generating spawn would not get this tag passed along and would thus run remotely.
The proposed fix is to pass along the execution requirements and platform of the test spawn to the test.xml-generating spawn. | [
"src/main/java/com/google/devtools/build/lib/exec/StandaloneTestStrategy.java"
] | [
"src/main/java/com/google/devtools/build/lib/exec/StandaloneTestStrategy.java"
] | [
"src/test/java/com/google/devtools/build/lib/exec/StandaloneTestStrategyTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/exec/StandaloneTestStrategy.java b/src/main/java/com/google/devtools/build/lib/exec/StandaloneTestStrategy.java
index 43e72787d289c8..cc483672c9d046 100644
--- a/src/main/java/com/google/devtools/build/lib/exec/StandaloneTestStrategy.java
+++ b/src/main/java/com/google/devtools/build/lib/exec/StandaloneTestStrategy.java
@@ -465,7 +465,9 @@ private Spawn createXmlGeneratingSpawn(TestRunnerAction action, SpawnResult resu
"TEST_TOTAL_SHARDS", Integer.toString(action.getExecutionSettings().getTotalShards()),
"TEST_NAME", action.getTestName(),
"TEST_BINARY", testBinaryName),
- ImmutableMap.of(),
+ // Pass the execution info of the action which is identical to the supported tags set on the
+ // test target. In particular, this does not set the test timeout on the spawn.
+ ImmutableMap.copyOf(action.getExecutionInfo()),
null,
ImmutableMap.of(),
/*inputs=*/ ImmutableList.of(action.getTestXmlGeneratorScript(), action.getTestLog()),
| diff --git a/src/test/java/com/google/devtools/build/lib/exec/StandaloneTestStrategyTest.java b/src/test/java/com/google/devtools/build/lib/exec/StandaloneTestStrategyTest.java
index 771958614fb948..219d89e041e650 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/StandaloneTestStrategyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/StandaloneTestStrategyTest.java
@@ -519,6 +519,7 @@ public void testThatTestLogAndOutputAreReturnedWithSplitXmlGeneration() throws E
" name = \"failing_test\",",
" size = \"small\",",
" srcs = [\"failing_test.sh\"],",
+ " tags = [\"local\"],",
")");
TestRunnerAction testRunnerAction = getTestAction("//standalone:failing_test");
@@ -538,6 +539,8 @@ public void testThatTestLogAndOutputAreReturnedWithSplitXmlGeneration() throws E
.thenAnswer(
(invocation) -> {
Spawn spawn = invocation.getArgument(0);
+ // Test that both spawns have the local tag attached as a execution info
+ assertThat(spawn.getExecutionInfo()).containsKey("local");
ActionExecutionContext context = invocation.getArgument(1);
FileOutErr outErr = context.getFileOutErr();
called.add(outErr);
| train | train | 2019-03-21T14:49:42 | "2019-03-21T12:48:05Z" | buchgr | test |
bazelbuild/bazel/7848_8251 | bazelbuild/bazel | bazelbuild/bazel/7848 | bazelbuild/bazel/8251 | [
"timestamp(timedelta=0.0, similarity=0.8714233050078801)"
] | 21521541d5e7e7d786a160af5c3b4c7c8fce82e9 | c357eb0400b2de0bd9dfdd8e0d0dd2b637e554a0 | [] | [] | "2019-05-07T12:37:10Z" | [
"type: bug",
"P4",
"area-Windows",
"team-OSS"
] | Windows: Bazel binary has no icon | ### Description of the problem / feature request:
Regression from earlier versions.
The Bazel binary no longer has an icon on Windows.
See message thread: https://github.com/bazelbuild/bazel/commit/f8128c3ce2160e5d6243a2dfd94b399d11ee282e
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
0.24.0 | [
"src/main/cpp/BUILD",
"src/main/native/windows/BUILD"
] | [
"src/main/cpp/BUILD",
"src/main/native/windows/BUILD"
] | [] | diff --git a/src/main/cpp/BUILD b/src/main/cpp/BUILD
index 483df2cd70925f..fea97a8d6b7014 100644
--- a/src/main/cpp/BUILD
+++ b/src/main/cpp/BUILD
@@ -79,7 +79,7 @@ cc_binary(
"global_variables.h",
"main.cc",
] + select({
- "//src/conditions:windows": ["//src/main/native/windows:resources"],
+ "//src/conditions:windows": ["resources.o"],
"//conditions:default": [],
}),
copts = select({
diff --git a/src/main/native/windows/BUILD b/src/main/native/windows/BUILD
index 8567b35b2e861b..e1e14249107d8f 100644
--- a/src/main/native/windows/BUILD
+++ b/src/main/native/windows/BUILD
@@ -78,14 +78,6 @@ cc_binary(
],
)
-# Directly re-export resources.o so it can be consumed in the client.
-cc_library(
- name = "resources",
- srcs = ["resources.o"],
- linkstatic = 1,
- visibility = ["//src/main/cpp:__pkg__"],
-)
-
filegroup(
name = "embedded_java_tools",
srcs = [
| null | train | train | 2019-05-07T14:02:19 | "2019-03-27T09:12:50Z" | laszlocsomor | test |
bazelbuild/bazel/7886_8100 | bazelbuild/bazel | bazelbuild/bazel/7886 | bazelbuild/bazel/8100 | [
"timestamp(timedelta=0.0, similarity=0.8459304991416536)"
] | 375f72b29ab28db3df093531b978c4370b059d54 | dca6527e02f1b1f811883f02d46e6ae5b6e34d99 | [
"Is this really EngProd or RulesServer? That's a trick question, all package building should be a separate project and not part of Bazel itself.\r\n\r\nThat aside. I think the least cost way to get there is to add a depends_file attribute. Implement just like version/version_file.\r\n\r\n- the user still needs a genrule to get the depends file from VERSION, so maybe ugly.\r\n- we can mitigate that by creating a rule set that does easy template expansion. Imagine \r\n ```\r\nexpand_template(\r\n name=\"x\",\r\n srcs = [\"//:VERSION\"],\r\n template = \"A ($(content //:VERSION))\" \r\n )\r\n```\r\n$(content label) is like the $(location label) syntax in a genrule, but expands the content.\r\nsomeone could spend months making this. It would be a huge boon for cross platform tooling,\r\nbecause we would not have to assume a whole bunch of unix tools on windows.\r\n\r\nI would be happy to review a PR for adding @depends_file. I'm not going to have a lot of time to do it myself \r\n\r\nI would also be happy to review a proposal to move packaging rules to a new repo. They need a lot of work for performance and portability. We could innovate better if this was shared by the community rather than part of core bazel.\r\n\r\n"
] | [] | "2019-04-19T13:27:17Z" | [
"area-EngProd",
"untriaged",
"team-OSS"
] | pkg_deb should support a way of embedding version into control fields | ### Description of the problem / feature request:
Cannot add `pkg_deb`'s version from `version_file` into Debian control field (i.e. `Depends:`)
### Feature requests: what underlying problem are you trying to solve with this feature?
I have several dependent packages (say, `A` and `B` depending on `A`) which I'm building at once. I want to specify dependency from `B` (of version `$version`) to `A` (of same `$version`). However, as I'm using `version_file` to specify version, I'm not able to specify `depends` = [`A (=<$version — how would I get it?>)`]
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
```
load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_deb")
pkg_deb(package = "A", version_file = "//:VERSION")
pkg_deb(package = "B", version_file = "//:VERSION", depends=["A (=version)"]) # <-- how can I make `A` the same version as in `//:VERSION` here?
```
### What operating system are you running Bazel on?
macOS Mojave 10.14.4
### What's the output of `bazel info release`?
`release 0.23.0`
### Have you found anything relevant by searching the web?
#7474 is probably relevant
| [
"tools/build_defs/pkg/make_deb.py",
"tools/build_defs/pkg/pkg.bzl"
] | [
"tools/build_defs/pkg/make_deb.py",
"tools/build_defs/pkg/pkg.bzl"
] | [] | diff --git a/tools/build_defs/pkg/make_deb.py b/tools/build_defs/pkg/make_deb.py
index 47056754a16e35..f58e920654f5ee 100644
--- a/tools/build_defs/pkg/make_deb.py
+++ b/tools/build_defs/pkg/make_deb.py
@@ -329,7 +329,7 @@ def main(unused_argv):
maintainer=FLAGS.maintainer,
section=FLAGS.section,
architecture=FLAGS.architecture,
- depends=FLAGS.depends,
+ depends=GetFlagValues(FLAGS.depends),
suggests=FLAGS.suggests,
enhances=FLAGS.enhances,
preDepends=FLAGS.pre_depends,
diff --git a/tools/build_defs/pkg/pkg.bzl b/tools/build_defs/pkg/pkg.bzl
index 1e1391cff24cf8..2ff0779d2c4775 100644
--- a/tools/build_defs/pkg/pkg.bzl
+++ b/tools/build_defs/pkg/pkg.bzl
@@ -184,6 +184,14 @@ def _pkg_deb_impl(ctx):
elif ctx.attr.built_using:
args += ["--built_using=" + ctx.attr.built_using]
+ if ctx.attr.depends_file:
+ if ctx.file.depends:
+ fail("Both depends and depends_file attributes were specified")
+ args += ["--depends=@" + ctx.attr.depends_file.path]
+ files += [ctx.file.depends_file]
+ elif ctx.attr.depends:
+ args += ["--depends=" + d for d in ctx.attr.depends]
+
if ctx.attr.priority:
args += ["--priority=" + ctx.attr.priority]
if ctx.attr.section:
@@ -193,7 +201,6 @@ def _pkg_deb_impl(ctx):
args += ["--distribution=" + ctx.attr.distribution]
args += ["--urgency=" + ctx.attr.urgency]
- args += ["--depends=" + d for d in ctx.attr.depends]
args += ["--suggests=" + d for d in ctx.attr.suggests]
args += ["--enhances=" + d for d in ctx.attr.enhances]
args += ["--conflicts=" + d for d in ctx.attr.conflicts]
@@ -299,6 +306,7 @@ _pkg_deb = rule(
"section": attr.string(),
"homepage": attr.string(),
"depends": attr.string_list(default = []),
+ "depends_file": attr.label(allow_single_file=True),
"suggests": attr.string_list(default = []),
"enhances": attr.string_list(default = []),
"conflicts": attr.string_list(default = []),
| null | train | train | 2019-04-18T23:30:09 | "2019-03-29T10:44:54Z" | vmax | test |
bazelbuild/bazel/7893_7894 | bazelbuild/bazel | bazelbuild/bazel/7893 | bazelbuild/bazel/7894 | [
"timestamp(timedelta=162812.0, similarity=0.8754590941708571)"
] | 46b180f1873a77d55345b440036c7d37268d2f78 | 98b6498be546a4493b3b3e4325d33d6022994ff5 | [] | [] | "2019-03-29T13:55:25Z" | [] | bazel_repository_cache_test is very flaky | Latest example:
https://buildkite.com/bazel/google-bazel-presubmit/builds/17442#111594d7-068e-4e24-abaa-d57840e067af
I'll remove this test from the presubmit pipeline since it takes 20 minutes. | [
".bazelci/presubmit.yml"
] | [
".bazelci/presubmit.yml"
] | [] | diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
index e39fbeb5e3b034..90b5176d937116 100644
--- a/.bazelci/presubmit.yml
+++ b/.bazelci/presubmit.yml
@@ -24,6 +24,8 @@ platforms:
- "-//src/test/shell/bazel:bazel_determinism_test"
# Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/4663
- "-//src/test/shell/bazel/android:android_ndk_integration_test"
+ # Re-enable once it's no longer flaky: https://github.com/bazelbuild/bazel/issues/7893
+ - "-//src/test/shell/bazel:bazel_repository_cache_test"
ubuntu1604:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -48,6 +50,8 @@ platforms:
- "-//src/test/shell/bazel:bazel_determinism_test"
# Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/4663
- "-//src/test/shell/bazel/android:android_ndk_integration_test"
+ # Re-enable once it's no longer flaky: https://github.com/bazelbuild/bazel/issues/7893
+ - "-//src/test/shell/bazel:bazel_repository_cache_test"
ubuntu1804:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -72,6 +76,8 @@ platforms:
- "-//src/test/shell/bazel:bazel_determinism_test"
# Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/4663
- "-//src/test/shell/bazel/android:android_ndk_integration_test"
+ # Re-enable once it's no longer flaky: https://github.com/bazelbuild/bazel/issues/7893
+ - "-//src/test/shell/bazel:bazel_repository_cache_test"
ubuntu1804_nojava:
build_flags:
- "--javabase=@openjdk_linux_archive//:runtime"
@@ -134,6 +140,8 @@ platforms:
- "-//src/test/shell/integration:stub_finds_runfiles_test"
- "-//src/test/shell/integration:test_test"
- "-//src/tools/singlejar:zip64_test"
+ # Re-enable once it's no longer flaky: https://github.com/bazelbuild/bazel/issues/7893
+ - "-//src/test/shell/bazel:bazel_repository_cache_test"
ubuntu1804_java9:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -158,6 +166,8 @@ platforms:
- "-//src/test/shell/bazel:bazel_determinism_test"
# Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/4663
- "-//src/test/shell/bazel/android:android_ndk_integration_test"
+ # Re-enable once it's no longer flaky: https://github.com/bazelbuild/bazel/issues/7893
+ - "-//src/test/shell/bazel:bazel_repository_cache_test"
ubuntu1804_java10:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -182,6 +192,8 @@ platforms:
- "-//src/test/shell/bazel:bazel_determinism_test"
# Re-enable once fixed: https://github.com/bazelbuild/bazel/issues/4663
- "-//src/test/shell/bazel/android:android_ndk_integration_test"
+ # Re-enable once it's no longer flaky: https://github.com/bazelbuild/bazel/issues/7893
+ - "-//src/test/shell/bazel:bazel_repository_cache_test"
ubuntu1804_java11:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
@@ -211,6 +223,8 @@ platforms:
- "-//src/test/shell/bazel:maven_test"
# Re-enable once bootstrap works with Java 11
- "-//src/test/shell/bazel:bazel_bootstrap_distfile_test"
+ # Re-enable once it's no longer flaky: https://github.com/bazelbuild/bazel/issues/7893
+ - "-//src/test/shell/bazel:bazel_repository_cache_test"
macos:
shell_commands:
- sed -i.bak -e 's/^# android_sdk_repository/android_sdk_repository/' -e 's/^#
| null | train | train | 2019-03-29T14:54:12 | "2019-03-29T13:53:05Z" | fweikert | test |
bazelbuild/bazel/7895_8276 | bazelbuild/bazel | bazelbuild/bazel/7895 | bazelbuild/bazel/8276 | [
"timestamp(timedelta=0.0, similarity=0.8984530232799471)"
] | 1df1635b0db2175191998d993052b8e37dadae7c | a68f135b19ac77b9150ea6b0c6b861cf48026500 | [] | [] | "2019-05-09T13:11:43Z" | [
"team-Remote-Exec"
] | Remove deprecated remote flags | As Part of #7205 a few flags got deprecated, for instance, `exeprimental_retry-*`
Those flags have to be removed, including related functionality/tests (see TODOs in the code). | [
"src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java"
] | [] | diff --git a/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java b/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java
index 755b6e5ea7da18..c5a72a1bbbd133 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/options/RemoteOptions.java
@@ -120,36 +120,6 @@ public final class RemoteOptions extends OptionsBase {
help = "Value to pass as instance_name in the remote execution API.")
public String remoteInstanceName;
- @Deprecated
- @Option(
- name = "experimental_remote_retry",
- defaultValue = "true",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public boolean experimentalRemoteRetry;
-
- @Deprecated
- @Option(
- name = "experimental_remote_retry_start_delay_millis",
- defaultValue = "100",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.UNKNOWN},
- help = "The initial delay before retrying a transient error. Use --remote_retries instead.")
- public long experimentalRemoteRetryStartDelayMillis;
-
- @Deprecated
- @Option(
- name = "experimental_remote_retry_max_delay_millis",
- defaultValue = "5000",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public long experimentalRemoteRetryMaxDelayMillis;
-
@Option(
name = "remote_retries",
oldName = "experimental_remote_retry_max_attempts",
@@ -161,26 +131,6 @@ public final class RemoteOptions extends OptionsBase {
+ "If set to 0, retries are disabled.")
public int remoteMaxRetryAttempts;
- @Deprecated
- @Option(
- name = "experimental_remote_retry_multiplier",
- defaultValue = "2",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public double experimentalRemoteRetryMultiplier;
-
- @Deprecated
- @Option(
- name = "experimental_remote_retry_jitter",
- defaultValue = "0.1",
- documentationCategory = OptionDocumentationCategory.REMOTE,
- deprecationWarning = "Deprecated. Use --remote_retries instead.",
- effectTags = {OptionEffectTag.NO_OP},
- help = "This flag is deprecated and has no effect. Use --remote_retries instead.")
- public double experimentalRemoteRetryJitter;
-
@Option(
name = "disk_cache",
defaultValue = "null",
| null | train | train | 2019-05-09T14:50:15 | "2019-03-29T14:11:53Z" | ishikhman | test |
bazelbuild/bazel/7907_7909 | bazelbuild/bazel | bazelbuild/bazel/7907 | bazelbuild/bazel/7909 | [
"timestamp(timedelta=75653.0, similarity=0.9415962211982463)"
] | 976876d21de9f502bd64156b1acd9967028d2e95 | f9de95b026af74b9ae7469bdec11be0db82617f5 | [] | [] | "2019-04-01T14:21:23Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Windows: Path.readSymbolicLink fails for junctions | ### Description of the problem / feature request:
Path.readSymbolicLink calls FileSystem.readSymbolicLink:
https://github.com/bazelbuild/bazel/blob/d7aa53ec68f573f9f130be18ac3ac1350d1d6be6/src/main/java/com/google/devtools/build/lib/vfs/Path.java#L599
On Windows, this calls into JavaIoFileSystem, which calls java.nio.file.Files.readSymbolicLink, which is unaware of junctions.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
The bug is rooted in java.nio, so here's an out-of-bazel repro:
BUILD:
```
java_binary(
name = "x",
srcs = ["ReadJunc.java"],
main_class = "ReadJunc",
)
```
ReadJunc.java:
```
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class ReadJunc {
public static void main(String[] args) throws Exception {
System.err.println("Hello ReadJunc");
Path path = FileSystems.getDefault().getPath("c:\\src\\bazel-releases\\current");
System.err.printf("path=(%s) isdir=%d%n",
path, path.toFile().isDirectory() ? 1 : 0);
Path path2 = Files.readSymbolicLink(path);
System.err.printf("path2=(%s)%n", path2);
}
}
```
output:
```
C:\src\tmp>bazel run x
...
path=(c:\src\bazel-releases\current) isdir=1
Exception in thread "main" java.nio.file.NotLinkException: Reparse point is not a symbolic link
at sun.nio.fs.WindowsLinkSupport.readLinkImpl(WindowsLinkSupport.java:318)
at sun.nio.fs.WindowsLinkSupport.readLink(WindowsLinkSupport.java:59)
at sun.nio.fs.WindowsFileSystemProvider.readSymbolicLink(WindowsFileSystemProvider.java:628)
at java.nio.file.Files.readSymbolicLink(Files.java:1432)
at ReadJunc.main(ReadJunc.java:13)
```
The particular path:
```
C:\src\tmp>dir c:\src\bazel-releases
...
2019-03-27 11:12 <JUNCTION> current [C:\src\bazel-releases\0.24.0]
```
### What operating system are you running Bazel on?
Windows 10 | [
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
index d39173a5dba482..8244c7565b7ddf 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
@@ -89,6 +89,12 @@ protected void createSymbolicLink(Path linkPath, PathFragment targetFragment) th
}
}
+ @Override
+ protected PathFragment readSymbolicLink(Path path) throws IOException {
+ java.nio.file.Path nioPath = getNioPath(path);
+ return PathFragment.create(WindowsFileOperations.readJunction(nioPath.toString()));
+ }
+
@Override
public boolean supportsSymbolicLinksNatively(Path path) {
return false;
diff --git a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
index c8243e485986d6..32154db922518c 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
@@ -44,12 +44,12 @@ private WindowsFileOperations() {
private static final int MAX_PATH = 260;
- // Keep IS_JUNCTION_* values in sync with src/main/native/windows/file.cc.
+ // Keep IS_JUNCTION_* values in sync with src/main/native/windows/file.h.
private static final int IS_JUNCTION_YES = 0;
private static final int IS_JUNCTION_NO = 1;
private static final int IS_JUNCTION_ERROR = 2;
- // Keep CREATE_JUNCTION_* values in sync with src/main/native/windows/file.cc.
+ // Keep CREATE_JUNCTION_* values in sync with src/main/native/windows/file.h.
private static final int CREATE_JUNCTION_SUCCESS = 0;
private static final int CREATE_JUNCTION_ERROR = 1;
private static final int CREATE_JUNCTION_TARGET_NAME_TOO_LONG = 2;
@@ -58,7 +58,14 @@ private WindowsFileOperations() {
private static final int CREATE_JUNCTION_ACCESS_DENIED = 5;
private static final int CREATE_JUNCTION_DISAPPEARED = 6;
- // Keep DELETE_PATH_* values in sync with src/main/native/windows/file.cc.
+ // Keep READ_JUNCTION_* values in sync with src/main/native/windows/file.h.
+ private static final int READ_JUNCTION_SUCCESS = 0;
+ private static final int READ_JUNCTION_ERROR = 1;
+ private static final int READ_JUNCTION_DOES_NOT_EXIST = 2;
+ private static final int READ_JUNCTION_ACCESS_DENIED = 3;
+ private static final int READ_JUNCTION_NOT_A_JUNCTION = 4;
+
+ // Keep DELETE_PATH_* values in sync with src/main/native/windows/file.h.
private static final int DELETE_PATH_SUCCESS = 0;
private static final int DELETE_PATH_ERROR = 1;
private static final int DELETE_PATH_DOES_NOT_EXIST = 2;
@@ -71,6 +78,8 @@ private WindowsFileOperations() {
private static native int nativeCreateJunction(String name, String target, String[] error);
+ private static native int nativeReadJunction(String path, String[] result, int[] DEBUG_target_len, String[] error);
+
private static native int nativeDeletePath(String path, String[] error);
/** Determines whether `path` is a junction point or directory symlink. */
@@ -166,10 +175,41 @@ public static void createJunction(String name, String target) throws IOException
}
}
+ public static String readJunction(String path) throws IOException {
+ WindowsJniLoader.loadJni();
+ String[] target = new String[] {null};
+ int[] DEBUG_target_len = new int[] { 0 };
+ String[] error = new String[] {null};
+
+ path = asLongPath(path);
+ int result = nativeReadJunction(path, target, DEBUG_target_len, error);
+ if (result == READ_JUNCTION_SUCCESS) {
+ error[0] = removeUncPrefixAndUseSlashes(target[0]);
+ System.err.printf(" | DEBUG | readJunc(%s) -> (%s) %d %d (%s)%n",
+ path, target[0], DEBUG_target_len[0], target[0].length(), error[0]);
+ return error[0];
+ } else {
+ switch (result) {
+ case READ_JUNCTION_DOES_NOT_EXIST:
+ error[0] = "path does not exist";
+ break;
+ case READ_JUNCTION_ACCESS_DENIED:
+ error[0] = "access is denied";
+ break;
+ case READ_JUNCTION_NOT_A_JUNCTION:
+ error[0] = "not a junction";
+ break;
+ default:
+ break;
+ }
+ throw new IOException(String.format("Cannot read junction '%s': %s", path, error[0]));
+ }
+ }
+
public static boolean deletePath(String path) throws IOException {
WindowsJniLoader.loadJni();
String[] error = new String[] {null};
- int result = nativeDeletePath(asLongPath(path.replace('/', '\\')), error);
+ int result = nativeDeletePath(asLongPath(path), error);
switch (result) {
case DELETE_PATH_SUCCESS:
return true;
diff --git a/src/main/native/windows/file-jni.cc b/src/main/native/windows/file-jni.cc
index 09934ec5af6e68..03c59d137288c3 100644
--- a/src/main/native/windows/file-jni.cc
+++ b/src/main/native/windows/file-jni.cc
@@ -97,6 +97,32 @@ Java_com_google_devtools_build_lib_windows_jni_WindowsFileOperations_nativeCreat
return result;
}
+extern "C" JNIEXPORT jint JNICALL
+Java_com_google_devtools_build_lib_windows_jni_WindowsFileOperations_nativeReadJunction(
+ JNIEnv* env, jclass clazz, jstring path, jobjectArray result_holder,
+ jintArray DEBUG_result_len_holder, jobjectArray error_msg_holder) {
+ std::wstring target, error;
+ int DEBUG_target_len;
+ std::wstring wpath(bazel::windows::GetJavaWstring(env, path));
+ int result = bazel::windows::ReadJunction(wpath, &target, &DEBUG_target_len, &error);
+ if (result == bazel::windows::ReadJunctionResult::kSuccess) {
+ env->SetObjectArrayElement(
+ result_holder, 0,
+ env->NewString(reinterpret_cast<const jchar*>(target.c_str()),
+ target.size()));
+ jint DEBUG_targetlen = DEBUG_target_len;
+ env->SetIntArrayRegion(DEBUG_result_len_holder, 0, 1, &DEBUG_targetlen);
+ } else {
+ if (!error.empty() && CanReportError(env, error_msg_holder)) {
+ ReportLastError(
+ bazel::windows::MakeErrorMessage(WSTR(__FILE__), __LINE__,
+ L"nativeReadJunction", wpath, error),
+ env, error_msg_holder);
+ }
+ }
+ return result;
+}
+
extern "C" JNIEXPORT jint JNICALL
Java_com_google_devtools_build_lib_windows_jni_WindowsFileOperations_nativeDeletePath(
JNIEnv* env, jclass clazz, jstring path, jobjectArray error_msg_holder) {
diff --git a/src/main/native/windows/file.cc b/src/main/native/windows/file.cc
index efe99c946400a2..1e223146a8ec8c 100644
--- a/src/main/native/windows/file.cc
+++ b/src/main/native/windows/file.cc
@@ -18,6 +18,7 @@
#include <windows.h>
#include <WinIoCtl.h>
+#include <fileapi.h>
#include <stdint.h> // uint8_t
@@ -143,8 +144,35 @@ typedef struct _JunctionDescription {
Descriptor descriptor;
WCHAR PathBuffer[ANYSIZE_ARRAY];
} JunctionDescription;
+
+typedef struct _AllocatedJunctionDescription {
+ union {
+ uint8_t raw_data[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+ JunctionDescription data;
+ };
+} AllocatedJunctionDescription;
#pragma pack(pop)
+static bool ReadJunctionByHandle(
+ HANDLE handle, JunctionDescription* reparse_buffer, WCHAR** target_path,
+ DWORD* target_path_len, DWORD* err) {
+ DWORD bytes_returned;
+ if (!::DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0,
+ reparse_buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
+ &bytes_returned, NULL)) {
+ *err = GetLastError();
+ return false;
+ }
+
+ *target_path = reparse_buffer->PathBuffer +
+ reparse_buffer->descriptor.SubstituteNameOffset +
+ /* "\??\" prefix */ 4;
+ *target_path_len =
+ reparse_buffer->descriptor.SubstituteNameLength / sizeof(WCHAR) -
+ /* "\??\" prefix */ 4;
+ return true;
+}
+
int CreateJunction(const wstring& junction_name, const wstring& junction_target,
wstring* error) {
if (!IsAbsoluteNormalizedWindowsPath(junction_name)) {
@@ -309,15 +337,14 @@ int CreateJunction(const wstring& junction_name, const wstring& junction_target,
}
}
- uint8_t reparse_buffer_bytes[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
- JunctionDescription* reparse_buffer =
- reinterpret_cast<JunctionDescription*>(reparse_buffer_bytes);
+ AllocatedJunctionDescription reparse_buffer_bytes;
+ JunctionDescription* reparse_buffer = &reparse_buffer_bytes.data;
if (create) {
// The junction doesn't exist yet, and we have an open handle to the
// candidate directory with write access and no sharing. Proceed to turn the
// directory into a junction.
- memset(reparse_buffer_bytes, 0, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
+ memset(&reparse_buffer_bytes, 0, sizeof(AllocatedJunctionDescription));
// "\??\" is meaningful to the kernel, it's a synomym for the "\DosDevices\"
// object path. (NOT to be confused with "\\?\" which is meaningful for the
@@ -372,25 +399,19 @@ int CreateJunction(const wstring& junction_name, const wstring& junction_target,
}
} else {
// The junction already exists. Check if it points to the right target.
-
- DWORD bytes_returned;
- if (!::DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0,
- reparse_buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE,
- &bytes_returned, NULL)) {
- DWORD err = GetLastError();
+ WCHAR* actual_target;
+ DWORD target_path_len, err;
+ if (!ReadJunctionByHandle(handle, reparse_buffer, &actual_target,
+ &target_path_len, &err)) {
// Some unknown error occurred.
if (error) {
- *error = MakeErrorMessage(WSTR(__FILE__), __LINE__, L"DeviceIoControl",
- name, err);
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__,
+ L"ReadJunctionByHandle", name, err);
}
return CreateJunctionResult::kError;
}
- WCHAR* actual_target = reparse_buffer->PathBuffer +
- reparse_buffer->descriptor.SubstituteNameOffset +
- /* "\??\" prefix */ 4;
- if (reparse_buffer->descriptor.SubstituteNameLength !=
- (/* "\??\" prefix */ 4 + target.size()) * sizeof(WCHAR) ||
+ if (target_path_len != target.size() ||
_wcsnicmp(actual_target, target.c_str(), target.size()) != 0) {
return CreateJunctionResult::kAlreadyExistsWithDifferentTarget;
}
@@ -399,6 +420,99 @@ int CreateJunction(const wstring& junction_name, const wstring& junction_target,
return CreateJunctionResult::kSuccess;
}
+static inline HANDLE OpenJunction(const wstring& path) {
+ return CreateFileW(
+ path.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
+ NULL, OPEN_EXISTING,
+ FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);
+}
+
+int ReadJunction(const wstring& path, wstring* result, int* DEBUG_result_len,
+ wstring* error) {
+ AutoHandle handle(OpenJunction(path));
+ if (!handle.IsValid()) {
+ DWORD err = GetLastError();
+ if (err == ERROR_SHARING_VIOLATION) {
+ // The junction is held open by another process.
+ return ReadJunctionResult::kAccessDenied;
+ } else if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
+ // The junction does not exist or one of its parent directories is not a
+ // directory.
+ return ReadJunctionResult::kDoesNotExist;
+ }
+
+ // The path seems to exist yet we cannot open it for metadata-reading.
+ // Report as much information as we have, then give up.
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__, L"CreateFileW", path,
+ err);
+ }
+ return ReadJunctionResult::kError;
+ }
+
+ BY_HANDLE_FILE_INFORMATION info;
+ if (!GetFileInformationByHandle(handle, &info)) {
+ DWORD err = GetLastError();
+ // Some unknown error occurred.
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__,
+ L"GetFileInformationByHandle", path, err);
+ }
+ return ReadJunctionResult::kError;
+ }
+
+ if (info.dwFileAttributes == INVALID_FILE_ATTRIBUTES) {
+ // Some unknown error occurred.
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__,
+ L"Failed to get attributes", path, 0);
+ }
+ return ReadJunctionResult::kError;
+ }
+
+ if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
+ return ReadJunctionResult::kNotAJunction;
+ }
+
+ AllocatedJunctionDescription junc;
+ memset(&junc, 0, sizeof(AllocatedJunctionDescription));
+
+ WCHAR* target_path;
+ DWORD target_path_len, err;
+ if (!ReadJunctionByHandle(handle, &junc.data, &target_path, &target_path_len,
+ &err)) {
+ if (err == ERROR_NOT_A_REPARSE_POINT) {
+ return ReadJunctionResult::kNotAJunction;
+ }
+
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__,
+ L"ReadJunctionByHandle", path, err);
+ }
+ return ReadJunctionResult::kError;
+ }
+
+ // DEBUG
+// {
+// FILE* fff=fopen("C:\\src\\bazel\\jni.log", "at");
+// fseek(fff, 0, SEEK_END);
+// fprintf(fff, "ReadJunc(%ls) -> %d %d %d (%ls) | %d %d (%ls)\n",
+// path.c_str(),
+// junc.data.descriptor.SubstituteNameOffset,
+// junc.data.descriptor.SubstituteNameLength,
+// (int) wcslen(junc.data.PathBuffer + junc.data.descriptor.SubstituteNameOffset),
+// junc.data.PathBuffer + junc.data.descriptor.SubstituteNameOffset,
+// target_path_len,
+// (int) wcslen(target_path),
+// target_path);
+// fclose(fff);
+// }
+
+ result->assign(target_path);
+ *DEBUG_result_len = target_path_len;
+ return ReadJunctionResult::kSuccess;
+}
+
struct DirectoryStatus {
enum {
kDoesNotExist = 0,
diff --git a/src/main/native/windows/file.h b/src/main/native/windows/file.h
index 84cbde3362ef51..3013a4e8cec996 100644
--- a/src/main/native/windows/file.h
+++ b/src/main/native/windows/file.h
@@ -77,6 +77,16 @@ struct CreateJunctionResult {
};
};
+struct ReadJunctionResult {
+ enum {
+ kSuccess = 0,
+ kError = 1,
+ kDoesNotExist = 2,
+ kAccessDenied = 3,
+ kNotAJunction = 4,
+ };
+};
+
// Determines whether `path` is a junction (or directory symlink).
//
// `path` should be an absolute, normalized, Windows-style path, with "\\?\"
@@ -124,6 +134,9 @@ wstring GetLongPath(const WCHAR* path, unique_ptr<WCHAR[]>* result);
int CreateJunction(const wstring& junction_name, const wstring& junction_target,
wstring* error);
+int ReadJunction(const wstring& path, wstring* result, int* DEBUG_result_len,
+ wstring* error);
+
// Deletes the file, junction, or empty directory at `path`.
// Returns DELETE_PATH_SUCCESS if it successfully deleted the path, otherwise
// returns one of the other DELETE_PATH_* constants (e.g. when the directory is
| diff --git a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
index e5470749b0ea68..c8a4343967f245 100644
--- a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
@@ -331,4 +331,42 @@ public String apply(File input) {
assertThat(p.isFile()).isTrue();
}
}
+
+ @Test
+ public void testReadJunction() throws Exception {
+ testUtil.scratchFile("dir\\hello.txt", "hello");
+ testUtil.createJunctions(ImmutableMap.of("junc", "dir"));
+
+ Path dirPath = testUtil.createVfsPath(fs, "dir");
+ Path juncPath = testUtil.createVfsPath(fs, "junc");
+
+ assertThat(dirPath.isDirectory()).isTrue();
+ assertThat(juncPath.isDirectory()).isTrue();
+
+ assertThat(dirPath.isSymbolicLink()).isFalse();
+ assertThat(juncPath.isSymbolicLink()).isTrue();
+
+ try {
+ testUtil.createVfsPath(fs, "does-not-exist").readSymbolicLink();
+ fail("expected exception");
+ } catch (IOException expected) {
+ assertThat(expected).hasMessageThat().matches(".*path does not exist");
+ }
+
+ try {
+ testUtil.createVfsPath(fs, "dir\\hello.txt").readSymbolicLink();
+ fail("expected exception");
+ } catch (IOException expected) {
+ assertThat(expected).hasMessageThat().matches(".*not a junction");
+ }
+
+ try {
+ dirPath.readSymbolicLink();
+ fail("expected exception");
+ } catch (IOException expected) {
+ assertThat(expected).hasMessageThat().matches(".*not a junction");
+ }
+
+ assertThat(juncPath.readSymbolicLink()).isEqualTo(dirPath.asFragment());
+ }
}
| test | train | 2019-04-01T16:09:08 | "2019-04-01T11:48:09Z" | laszlocsomor | test |
bazelbuild/bazel/7907_7929 | bazelbuild/bazel | bazelbuild/bazel/7907 | bazelbuild/bazel/7929 | [
"timestamp(timedelta=0.0, similarity=0.9161274648519767)"
] | 0f569b0783d4a64ef210c9f9ddfd515b965fc04a | 0ae1cd8e79be3bc5403fce7a1889ac39abe5adbf | [] | [
"Why comment here? Is `READ_SYMLINK_OR_JUNCTION_ERROR` set or used anywhere?",
"For documentation, and to indicate that the value exists. The variable is not used anywhere (handled by `switch.default`).\r\n\r\nRemoved.",
"Nit: maybe 1, 2, 3, 4,?",
"These values match constants in `src/main/native/windows/file.h`. Added comments."
] | "2019-04-03T13:18:02Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Windows: Path.readSymbolicLink fails for junctions | ### Description of the problem / feature request:
Path.readSymbolicLink calls FileSystem.readSymbolicLink:
https://github.com/bazelbuild/bazel/blob/d7aa53ec68f573f9f130be18ac3ac1350d1d6be6/src/main/java/com/google/devtools/build/lib/vfs/Path.java#L599
On Windows, this calls into JavaIoFileSystem, which calls java.nio.file.Files.readSymbolicLink, which is unaware of junctions.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
The bug is rooted in java.nio, so here's an out-of-bazel repro:
BUILD:
```
java_binary(
name = "x",
srcs = ["ReadJunc.java"],
main_class = "ReadJunc",
)
```
ReadJunc.java:
```
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class ReadJunc {
public static void main(String[] args) throws Exception {
System.err.println("Hello ReadJunc");
Path path = FileSystems.getDefault().getPath("c:\\src\\bazel-releases\\current");
System.err.printf("path=(%s) isdir=%d%n",
path, path.toFile().isDirectory() ? 1 : 0);
Path path2 = Files.readSymbolicLink(path);
System.err.printf("path2=(%s)%n", path2);
}
}
```
output:
```
C:\src\tmp>bazel run x
...
path=(c:\src\bazel-releases\current) isdir=1
Exception in thread "main" java.nio.file.NotLinkException: Reparse point is not a symbolic link
at sun.nio.fs.WindowsLinkSupport.readLinkImpl(WindowsLinkSupport.java:318)
at sun.nio.fs.WindowsLinkSupport.readLink(WindowsLinkSupport.java:59)
at sun.nio.fs.WindowsFileSystemProvider.readSymbolicLink(WindowsFileSystemProvider.java:628)
at java.nio.file.Files.readSymbolicLink(Files.java:1432)
at ReadJunc.main(ReadJunc.java:13)
```
The particular path:
```
C:\src\tmp>dir c:\src\bazel-releases
...
2019-03-27 11:12 <JUNCTION> current [C:\src\bazel-releases\0.24.0]
```
### What operating system are you running Bazel on?
Windows 10 | [
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
index d39173a5dba482..ee457b70652b5d 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
@@ -89,6 +89,12 @@ protected void createSymbolicLink(Path linkPath, PathFragment targetFragment) th
}
}
+ @Override
+ protected PathFragment readSymbolicLink(Path path) throws IOException {
+ java.nio.file.Path nioPath = getNioPath(path);
+ return PathFragment.create(WindowsFileOperations.readSymlinkOrJunction(nioPath.toString()));
+ }
+
@Override
public boolean supportsSymbolicLinksNatively(Path path) {
return false;
diff --git a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
index c8243e485986d6..82086181f0d2f6 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
@@ -44,33 +44,44 @@ private WindowsFileOperations() {
private static final int MAX_PATH = 260;
- // Keep IS_JUNCTION_* values in sync with src/main/native/windows/file.cc.
+ // Keep IS_JUNCTION_* values in sync with src/main/native/windows/file.h.
private static final int IS_JUNCTION_YES = 0;
private static final int IS_JUNCTION_NO = 1;
- private static final int IS_JUNCTION_ERROR = 2;
+ // IS_JUNCTION_ERROR = 2;
- // Keep CREATE_JUNCTION_* values in sync with src/main/native/windows/file.cc.
+ // Keep CREATE_JUNCTION_* values in sync with src/main/native/windows/file.h.
private static final int CREATE_JUNCTION_SUCCESS = 0;
- private static final int CREATE_JUNCTION_ERROR = 1;
+ // CREATE_JUNCTION_ERROR = 1;
private static final int CREATE_JUNCTION_TARGET_NAME_TOO_LONG = 2;
private static final int CREATE_JUNCTION_ALREADY_EXISTS_WITH_DIFFERENT_TARGET = 3;
private static final int CREATE_JUNCTION_ALREADY_EXISTS_BUT_NOT_A_JUNCTION = 4;
private static final int CREATE_JUNCTION_ACCESS_DENIED = 5;
private static final int CREATE_JUNCTION_DISAPPEARED = 6;
- // Keep DELETE_PATH_* values in sync with src/main/native/windows/file.cc.
+ // Keep DELETE_PATH_* values in sync with src/main/native/windows/file.h.
private static final int DELETE_PATH_SUCCESS = 0;
- private static final int DELETE_PATH_ERROR = 1;
+ // DELETE_PATH_ERROR = 1;
private static final int DELETE_PATH_DOES_NOT_EXIST = 2;
private static final int DELETE_PATH_DIRECTORY_NOT_EMPTY = 3;
private static final int DELETE_PATH_ACCESS_DENIED = 4;
+ // Keep READ_SYMLINK_OR_JUNCTION_* values in sync with src/main/native/windows/file.h.
+ private static final int READ_SYMLINK_OR_JUNCTION_SUCCESS = 0;
+ // READ_SYMLINK_OR_JUNCTION_ERROR = 1;
+ private static final int READ_SYMLINK_OR_JUNCTION_ACCESS_DENIED = 2;
+ private static final int READ_SYMLINK_OR_JUNCTION_DOES_NOT_EXIST = 3;
+ private static final int READ_SYMLINK_OR_JUNCTION_NOT_A_LINK = 4;
+ private static final int READ_SYMLINK_OR_JUNCTION_UNKNOWN_LINK_TYPE = 5;
+
private static native int nativeIsJunction(String path, String[] error);
private static native boolean nativeGetLongPath(String path, String[] result, String[] error);
private static native int nativeCreateJunction(String name, String target, String[] error);
+ private static native int nativeReadSymlinkOrJunction(
+ String name, String[] result, String[] error);
+
private static native int nativeDeletePath(String path, String[] error);
/** Determines whether `path` is a junction point or directory symlink. */
@@ -83,6 +94,7 @@ public static boolean isJunction(String path) throws IOException {
case IS_JUNCTION_NO:
return false;
default:
+ // This is IS_JUNCTION_ERROR. The JNI code puts a custom message in 'error[0]'.
throw new IOException(error[0]);
}
}
@@ -140,36 +152,63 @@ private static String removeUncPrefixAndUseSlashes(String p) {
public static void createJunction(String name, String target) throws IOException {
WindowsJniLoader.loadJni();
String[] error = new String[] {null};
- int result = nativeCreateJunction(name.replace('/', '\\'), target.replace('/', '\\'), error);
- if (result != CREATE_JUNCTION_SUCCESS) {
- switch (result) {
- case CREATE_JUNCTION_TARGET_NAME_TOO_LONG:
- error[0] = "target name is too long";
- break;
- case CREATE_JUNCTION_ALREADY_EXISTS_WITH_DIFFERENT_TARGET:
- error[0] = "junction already exists with different target";
- break;
- case CREATE_JUNCTION_ALREADY_EXISTS_BUT_NOT_A_JUNCTION:
- error[0] = "a file or directory already exists at the junction's path";
- break;
- case CREATE_JUNCTION_ACCESS_DENIED:
- error[0] = "access is denied";
- break;
- case CREATE_JUNCTION_DISAPPEARED:
- error[0] = "the junction's path got modified unexpectedly";
- break;
- default:
- break;
- }
- throw new IOException(
- String.format("Cannot create junction (name=%s, target=%s): %s", name, target, error[0]));
+ switch (nativeCreateJunction(asLongPath(name), asLongPath(target), error)) {
+ case CREATE_JUNCTION_SUCCESS:
+ return;
+ case CREATE_JUNCTION_TARGET_NAME_TOO_LONG:
+ error[0] = "target name is too long";
+ break;
+ case CREATE_JUNCTION_ALREADY_EXISTS_WITH_DIFFERENT_TARGET:
+ error[0] = "junction already exists with different target";
+ break;
+ case CREATE_JUNCTION_ALREADY_EXISTS_BUT_NOT_A_JUNCTION:
+ error[0] = "a file or directory already exists at the junction's path";
+ break;
+ case CREATE_JUNCTION_ACCESS_DENIED:
+ error[0] = "access is denied";
+ break;
+ case CREATE_JUNCTION_DISAPPEARED:
+ error[0] = "the junction's path got modified unexpectedly";
+ break;
+ default:
+ // This is CREATE_JUNCTION_ERROR (1). The JNI code puts a custom message in 'error[0]'.
+ break;
+ }
+ throw new IOException(
+ String.format("Cannot create junction (name=%s, target=%s): %s", name, target, error[0]));
+ }
+
+ public static String readSymlinkOrJunction(String name) throws IOException {
+ WindowsJniLoader.loadJni();
+ String[] target = new String[] {null};
+ String[] error = new String[] {null};
+ switch (nativeReadSymlinkOrJunction(asLongPath(name), target, error)) {
+ case READ_SYMLINK_OR_JUNCTION_SUCCESS:
+ return removeUncPrefixAndUseSlashes(target[0]);
+ case READ_SYMLINK_OR_JUNCTION_ACCESS_DENIED:
+ error[0] = "access is denied";
+ break;
+ case READ_SYMLINK_OR_JUNCTION_DOES_NOT_EXIST:
+ error[0] = "path does not exist";
+ break;
+ case READ_SYMLINK_OR_JUNCTION_NOT_A_LINK:
+ error[0] = "path is not a link";
+ break;
+ case READ_SYMLINK_OR_JUNCTION_UNKNOWN_LINK_TYPE:
+ error[0] = "unknown link type";
+ break;
+ default:
+ // This is READ_SYMLINK_OR_JUNCTION_ERROR (1). The JNI code puts a custom message in
+ // 'error[0]'.
+ break;
}
+ throw new IOException(String.format("Cannot read link (name=%s): %s", name, error[0]));
}
public static boolean deletePath(String path) throws IOException {
WindowsJniLoader.loadJni();
String[] error = new String[] {null};
- int result = nativeDeletePath(asLongPath(path.replace('/', '\\')), error);
+ int result = nativeDeletePath(asLongPath(path), error);
switch (result) {
case DELETE_PATH_SUCCESS:
return true;
@@ -180,6 +219,7 @@ public static boolean deletePath(String path) throws IOException {
case DELETE_PATH_ACCESS_DENIED:
throw new java.nio.file.AccessDeniedException(path);
default:
+ // This is DELETE_PATH_ERROR (1). The JNI code puts a custom message in 'error[0]'.
throw new IOException(String.format("Cannot delete path '%s': %s", path, error[0]));
}
}
diff --git a/src/main/native/windows/file-jni.cc b/src/main/native/windows/file-jni.cc
index 09934ec5af6e68..3befe0fe27fcdc 100644
--- a/src/main/native/windows/file-jni.cc
+++ b/src/main/native/windows/file-jni.cc
@@ -94,7 +94,30 @@ Java_com_google_devtools_build_lib_windows_jni_WindowsFileOperations_nativeCreat
wname + L", " + wtarget, error),
env, error_msg_holder);
}
- return result;
+ return static_cast<jint>(result);
+}
+
+extern "C" JNIEXPORT jint JNICALL
+Java_com_google_devtools_build_lib_windows_jni_WindowsFileOperations_nativeReadSymlinkOrJunction(
+ JNIEnv* env, jclass clazz, jstring name, jobjectArray target_holder,
+ jobjectArray error_msg_holder) {
+ std::wstring wname(bazel::windows::GetJavaWstring(env, name));
+ std::wstring target, error;
+ int result = bazel::windows::ReadSymlinkOrJunction(wname, &target, &error);
+ if (result == bazel::windows::ReadSymlinkOrJunctionResult::kSuccess) {
+ env->SetObjectArrayElement(
+ target_holder, 0,
+ env->NewString(reinterpret_cast<const jchar*>(target.c_str()),
+ target.size()));
+ } else {
+ if (!error.empty() && CanReportError(env, error_msg_holder)) {
+ ReportLastError(bazel::windows::MakeErrorMessage(
+ WSTR(__FILE__), __LINE__,
+ L"nativeReadSymlinkOrJunction", wname, error),
+ env, error_msg_holder);
+ }
+ }
+ return static_cast<jint>(result);
}
extern "C" JNIEXPORT jint JNICALL
diff --git a/src/main/native/windows/file.cc b/src/main/native/windows/file.cc
index 091f5274323116..47c5a52e1c8432 100644
--- a/src/main/native/windows/file.cc
+++ b/src/main/native/windows/file.cc
@@ -161,7 +161,7 @@ int CreateJunction(const wstring& junction_name, const wstring& junction_target,
WSTR(__FILE__), __LINE__, L"CreateJunction", junction_name,
L"expected an absolute Windows path for junction_name");
}
- CreateJunctionResult::kError;
+ return CreateJunctionResult::kError;
}
if (!IsAbsoluteNormalizedWindowsPath(junction_target)) {
if (error) {
@@ -169,7 +169,7 @@ int CreateJunction(const wstring& junction_name, const wstring& junction_target,
WSTR(__FILE__), __LINE__, L"CreateJunction", junction_target,
L"expected an absolute Windows path for junction_target");
}
- CreateJunctionResult::kError;
+ return CreateJunctionResult::kError;
}
const WCHAR* target = HasUncPrefix(junction_target.c_str())
@@ -420,6 +420,82 @@ int CreateJunction(const wstring& junction_name, const wstring& junction_target,
return CreateJunctionResult::kSuccess;
}
+int ReadSymlinkOrJunction(const wstring& path, wstring* result,
+ wstring* error) {
+ if (!IsAbsoluteNormalizedWindowsPath(path)) {
+ if (error) {
+ *error = MakeErrorMessage(
+ WSTR(__FILE__), __LINE__, L"ReadSymlinkOrJunction", path,
+ L"expected an absolute Windows path for 'path'");
+ }
+ return ReadSymlinkOrJunctionResult::kError;
+ }
+
+ AutoHandle handle(CreateFileW(
+ AddUncPrefixMaybe(path).c_str(), 0,
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
+ OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
+ NULL));
+ if (!handle.IsValid()) {
+ DWORD err = GetLastError();
+ if (err == ERROR_SHARING_VIOLATION) {
+ // The path is held open by another process.
+ return ReadSymlinkOrJunctionResult::kAccessDenied;
+ } else if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
+ // Path or a parent directory does not exist.
+ return ReadSymlinkOrJunctionResult::kDoesNotExist;
+ }
+
+ // The path seems to exist yet we cannot open it for metadata-reading.
+ // Report as much information as we have, then give up.
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__, L"CreateFileW",
+ path, err);
+ }
+ return ReadSymlinkOrJunctionResult::kError;
+ }
+
+ uint8_t raw_buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+ PREPARSE_DATA_BUFFER buf = reinterpret_cast<PREPARSE_DATA_BUFFER>(raw_buf);
+ DWORD bytes_returned;
+ if (!::DeviceIoControl(handle, FSCTL_GET_REPARSE_POINT, NULL, 0, buf,
+ MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &bytes_returned,
+ NULL)) {
+ DWORD err = GetLastError();
+ if (err == ERROR_NOT_A_REPARSE_POINT) {
+ return ReadSymlinkOrJunctionResult::kNotALink;
+ }
+
+ // Some unknown error occurred.
+ if (error) {
+ *error = MakeErrorMessage(WSTR(__FILE__), __LINE__, L"DeviceIoControl",
+ path, err);
+ }
+ return ReadSymlinkOrJunctionResult::kError;
+ }
+
+ switch (buf->ReparseTag) {
+ case IO_REPARSE_TAG_SYMLINK: {
+ wchar_t* p =
+ (wchar_t*) (((uint8_t*) buf->SymbolicLinkReparseBuffer.PathBuffer) +
+ buf->SymbolicLinkReparseBuffer.SubstituteNameOffset);
+ *result = wstring(p, buf->SymbolicLinkReparseBuffer.SubstituteNameLength /
+ sizeof(WCHAR));
+ return ReadSymlinkOrJunctionResult::kSuccess;
+ }
+ case IO_REPARSE_TAG_MOUNT_POINT: {
+ wchar_t* p =
+ (wchar_t*) (((uint8_t*) buf->MountPointReparseBuffer.PathBuffer) +
+ buf->MountPointReparseBuffer.SubstituteNameOffset);
+ *result = wstring(p, buf->MountPointReparseBuffer.SubstituteNameLength /
+ sizeof(WCHAR));
+ return ReadSymlinkOrJunctionResult::kSuccess;
+ }
+ default:
+ return ReadSymlinkOrJunctionResult::kUnknownLinkType;
+ }
+}
+
struct DirectoryStatus {
enum {
kDoesNotExist = 0,
diff --git a/src/main/native/windows/file.h b/src/main/native/windows/file.h
index 84cbde3362ef51..eb37c1b26b871b 100644
--- a/src/main/native/windows/file.h
+++ b/src/main/native/windows/file.h
@@ -77,6 +77,17 @@ struct CreateJunctionResult {
};
};
+struct ReadSymlinkOrJunctionResult {
+ enum {
+ kSuccess = 0,
+ kError = 1,
+ kAccessDenied = 2,
+ kDoesNotExist = 3,
+ kNotALink = 4,
+ kUnknownLinkType = 5,
+ };
+};
+
// Determines whether `path` is a junction (or directory symlink).
//
// `path` should be an absolute, normalized, Windows-style path, with "\\?\"
@@ -124,6 +135,9 @@ wstring GetLongPath(const WCHAR* path, unique_ptr<WCHAR[]>* result);
int CreateJunction(const wstring& junction_name, const wstring& junction_target,
wstring* error);
+int ReadSymlinkOrJunction(const wstring& path, wstring* result,
+ wstring* error);
+
// Deletes the file, junction, or empty directory at `path`.
// Returns DELETE_PATH_SUCCESS if it successfully deleted the path, otherwise
// returns one of the other DELETE_PATH_* constants (e.g. when the directory is
| diff --git a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
index e5470749b0ea68..b0c9454d5121dc 100644
--- a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
@@ -331,4 +331,42 @@ public String apply(File input) {
assertThat(p.isFile()).isTrue();
}
}
+
+ @Test
+ public void testReadJunction() throws Exception {
+ testUtil.scratchFile("dir\\hello.txt", "hello");
+ testUtil.createJunctions(ImmutableMap.of("junc", "dir"));
+
+ Path dirPath = testUtil.createVfsPath(fs, "dir");
+ Path juncPath = testUtil.createVfsPath(fs, "junc");
+
+ assertThat(dirPath.isDirectory()).isTrue();
+ assertThat(juncPath.isDirectory()).isTrue();
+
+ assertThat(dirPath.isSymbolicLink()).isFalse();
+ assertThat(juncPath.isSymbolicLink()).isTrue();
+
+ try {
+ testUtil.createVfsPath(fs, "does-not-exist").readSymbolicLink();
+ fail("expected exception");
+ } catch (IOException expected) {
+ assertThat(expected).hasMessageThat().matches(".*path does not exist");
+ }
+
+ try {
+ testUtil.createVfsPath(fs, "dir\\hello.txt").readSymbolicLink();
+ fail("expected exception");
+ } catch (IOException expected) {
+ assertThat(expected).hasMessageThat().matches(".*path is not a link");
+ }
+
+ try {
+ dirPath.readSymbolicLink();
+ fail("expected exception");
+ } catch (IOException expected) {
+ assertThat(expected).hasMessageThat().matches(".*path is not a link");
+ }
+
+ assertThat(juncPath.readSymbolicLink()).isEqualTo(dirPath.asFragment());
+ }
}
| train | train | 2019-04-04T11:07:47 | "2019-04-01T11:48:09Z" | laszlocsomor | test |
bazelbuild/bazel/7907_7931 | bazelbuild/bazel | bazelbuild/bazel/7907 | bazelbuild/bazel/7931 | [
"timestamp(timedelta=15588.0, similarity=0.8937945245048657)"
] | b9fd6f2c109c99d6523c0da92a5663f6ac4fdd69 | 69d575f35cb57d9a3d060712a18857d70083cc6f | [] | [] | "2019-04-03T15:26:42Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Windows: Path.readSymbolicLink fails for junctions | ### Description of the problem / feature request:
Path.readSymbolicLink calls FileSystem.readSymbolicLink:
https://github.com/bazelbuild/bazel/blob/d7aa53ec68f573f9f130be18ac3ac1350d1d6be6/src/main/java/com/google/devtools/build/lib/vfs/Path.java#L599
On Windows, this calls into JavaIoFileSystem, which calls java.nio.file.Files.readSymbolicLink, which is unaware of junctions.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
The bug is rooted in java.nio, so here's an out-of-bazel repro:
BUILD:
```
java_binary(
name = "x",
srcs = ["ReadJunc.java"],
main_class = "ReadJunc",
)
```
ReadJunc.java:
```
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.nio.file.Path;
public class ReadJunc {
public static void main(String[] args) throws Exception {
System.err.println("Hello ReadJunc");
Path path = FileSystems.getDefault().getPath("c:\\src\\bazel-releases\\current");
System.err.printf("path=(%s) isdir=%d%n",
path, path.toFile().isDirectory() ? 1 : 0);
Path path2 = Files.readSymbolicLink(path);
System.err.printf("path2=(%s)%n", path2);
}
}
```
output:
```
C:\src\tmp>bazel run x
...
path=(c:\src\bazel-releases\current) isdir=1
Exception in thread "main" java.nio.file.NotLinkException: Reparse point is not a symbolic link
at sun.nio.fs.WindowsLinkSupport.readLinkImpl(WindowsLinkSupport.java:318)
at sun.nio.fs.WindowsLinkSupport.readLink(WindowsLinkSupport.java:59)
at sun.nio.fs.WindowsFileSystemProvider.readSymbolicLink(WindowsFileSystemProvider.java:628)
at java.nio.file.Files.readSymbolicLink(Files.java:1432)
at ReadJunc.main(ReadJunc.java:13)
```
The particular path:
```
C:\src\tmp>dir c:\src\bazel-releases
...
2019-03-27 11:12 <JUNCTION> current [C:\src\bazel-releases\0.24.0]
```
### What operating system are you running Bazel on?
Windows 10 | [
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java",
"src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java",
"src/main/native/windows/file-jni.cc",
"src/main/native/windows/file.cc",
"src/main/native/windows/file.h"
] | [
"src/test/java/com/google/devtools/build/lib/windows/WindowsFileOperationsTest.java",
"src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java",
"src/test/native/windows/file_test.cc"
] | diff --git a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
index ee457b70652b5d..5b3669b8ed5a8c 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/WindowsFileSystem.java
@@ -108,7 +108,7 @@ public boolean isFilePathCaseSensitive() {
@Override
protected boolean fileIsSymbolicLink(File file) {
try {
- if (isJunction(file)) {
+ if (isSymlinkOrJunction(file)) {
return true;
}
} catch (IOException e) {
@@ -184,7 +184,7 @@ public long getNodeId() {
protected boolean isDirectory(Path path, boolean followSymlinks) {
if (!followSymlinks) {
try {
- if (isJunction(getIoFile(path))) {
+ if (isSymlinkOrJunction(getIoFile(path))) {
return false;
}
} catch (IOException e) {
@@ -214,8 +214,8 @@ protected boolean isDirectory(Path path, boolean followSymlinks) {
* they are dangling), though only directory junctions and directory symlinks are useful.
*/
@VisibleForTesting
- static boolean isJunction(File file) throws IOException {
- return WindowsFileOperations.isJunction(file.getPath());
+ static boolean isSymlinkOrJunction(File file) throws IOException {
+ return WindowsFileOperations.isSymlinkOrJunction(file.getPath());
}
private static DosFileAttributes getAttribs(File file, boolean followSymlinks)
diff --git a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
index 82086181f0d2f6..ba82a4f98bfb8b 100644
--- a/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
+++ b/src/main/java/com/google/devtools/build/lib/windows/jni/WindowsFileOperations.java
@@ -44,10 +44,10 @@ private WindowsFileOperations() {
private static final int MAX_PATH = 260;
- // Keep IS_JUNCTION_* values in sync with src/main/native/windows/file.h.
- private static final int IS_JUNCTION_YES = 0;
- private static final int IS_JUNCTION_NO = 1;
- // IS_JUNCTION_ERROR = 2;
+ // Keep IS_SYMLINK_OR_JUNCTION_* values in sync with src/main/native/windows/file.cc.
+ private static final int IS_SYMLINK_OR_JUNCTION_SUCCESS = 0;
+ // IS_SYMLINK_OR_JUNCTION_ERROR = 1;
+ private static final int IS_SYMLINK_OR_JUNCTION_DOES_NOT_EXIST = 2;
// Keep CREATE_JUNCTION_* values in sync with src/main/native/windows/file.h.
private static final int CREATE_JUNCTION_SUCCESS = 0;
@@ -73,7 +73,8 @@ private WindowsFileOperations() {
private static final int READ_SYMLINK_OR_JUNCTION_NOT_A_LINK = 4;
private static final int READ_SYMLINK_OR_JUNCTION_UNKNOWN_LINK_TYPE = 5;
- private static native int nativeIsJunction(String path, String[] error);
+ private static native int nativeIsSymlinkOrJunction(
+ String path, boolean[] result, String[] error);
private static native boolean nativeGetLongPath(String path, String[] result, String[] error);
@@ -85,18 +86,22 @@ private static native int nativeReadSymlinkOrJunction(
private static native int nativeDeletePath(String path, String[] error);
/** Determines whether `path` is a junction point or directory symlink. */
- public static boolean isJunction(String path) throws IOException {
+ public static boolean isSymlinkOrJunction(String path) throws IOException {
WindowsJniLoader.loadJni();
+ boolean[] result = new boolean[] {false};
String[] error = new String[] {null};
- switch (nativeIsJunction(asLongPath(path), error)) {
- case IS_JUNCTION_YES:
- return true;
- case IS_JUNCTION_NO:
- return false;
+ switch (nativeIsSymlinkOrJunction(asLongPath(path), result, error)) {
+ case IS_SYMLINK_OR_JUNCTION_SUCCESS:
+ return result[0];
+ case IS_SYMLINK_OR_JUNCTION_DOES_NOT_EXIST:
+ error[0] = "path does not exist";
+ break;
default:
- // This is IS_JUNCTION_ERROR. The JNI code puts a custom message in 'error[0]'.
- throw new IOException(error[0]);
+ // This is IS_SYMLINK_OR_JUNCTION_ERROR (1). The JNI code puts a custom message in
+ // 'error[0]'.
+ break;
}
+ throw new IOException(String.format("Cannot tell if '%s' is link: %s", path, error[0]));
}
/**
diff --git a/src/main/native/windows/file-jni.cc b/src/main/native/windows/file-jni.cc
index 3befe0fe27fcdc..b9be7ebe3bfa2a 100644
--- a/src/main/native/windows/file-jni.cc
+++ b/src/main/native/windows/file-jni.cc
@@ -40,20 +40,26 @@ static void ReportLastError(const std::wstring& error_str, JNIEnv* env,
}
extern "C" JNIEXPORT jint JNICALL
-Java_com_google_devtools_build_lib_windows_jni_WindowsFileOperations_nativeIsJunction(
- JNIEnv* env, jclass clazz, jstring path, jobjectArray error_msg_holder) {
+Java_com_google_devtools_build_lib_windows_jni_WindowsFileOperations_nativeIsSymlinkOrJunction(
+ JNIEnv* env, jclass clazz, jstring path, jbooleanArray result_holder,
+ jobjectArray error_msg_holder) {
std::wstring wpath(bazel::windows::GetJavaWstring(env, path));
std::wstring error;
- int result =
- bazel::windows::IsJunctionOrDirectorySymlink(wpath.c_str(), &error);
- if (result == bazel::windows::IS_JUNCTION_ERROR &&
- CanReportError(env, error_msg_holder)) {
- ReportLastError(
- bazel::windows::MakeErrorMessage(WSTR(__FILE__), __LINE__,
- L"nativeIsJunction", wpath, error),
- env, error_msg_holder);
+ bool is_sym = false;
+ int result = bazel::windows::IsSymlinkOrJunction(wpath.c_str(), &is_sym,
+ &error);
+ if (result == bazel::windows::IsSymlinkOrJunctionResult::kSuccess) {
+ jboolean is_sym_jbool = is_sym ? JNI_TRUE : JNI_FALSE;
+ env->SetBooleanArrayRegion(result_holder, 0, 1, &is_sym_jbool);
+ } else {
+ if (!error.empty() && CanReportError(env, error_msg_holder)) {
+ ReportLastError(
+ bazel::windows::MakeErrorMessage(WSTR(__FILE__), __LINE__,
+ L"nativeIsJunction", wpath, error),
+ env, error_msg_holder);
+ }
}
- return result;
+ return static_cast<jint>(result);
}
extern "C" JNIEXPORT jboolean JNICALL
diff --git a/src/main/native/windows/file.cc b/src/main/native/windows/file.cc
index e7cf81a78c4049..c3cbd63f62cad2 100644
--- a/src/main/native/windows/file.cc
+++ b/src/main/native/windows/file.cc
@@ -78,31 +78,31 @@ static wstring uint32asHexString(uint32_t value) {
return wstring(attr_str, 8);
}
-int IsJunctionOrDirectorySymlink(const WCHAR* path, wstring* error) {
+int IsSymlinkOrJunction(const WCHAR* path, bool* result, wstring* error) {
if (!IsAbsoluteNormalizedWindowsPath(path)) {
if (error) {
*error = MakeErrorMessage(WSTR(__FILE__), __LINE__,
- L"IsJunctionOrDirectorySymlink", path,
+ L"IsSymlinkOrJunction", path,
L"expected an absolute Windows path");
}
- return IS_JUNCTION_ERROR;
+ return IsSymlinkOrJunctionResult::kError;
}
DWORD attrs = ::GetFileAttributesW(path);
if (attrs == INVALID_FILE_ATTRIBUTES) {
DWORD err = GetLastError();
+ if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
+ return IsSymlinkOrJunctionResult::kDoesNotExist;
+ }
+
if (error) {
*error = MakeErrorMessage(WSTR(__FILE__), __LINE__,
- L"IsJunctionOrDirectorySymlink", path, err);
+ L"IsSymlinkOrJunction", path, err);
}
- return IS_JUNCTION_ERROR;
+ return IsSymlinkOrJunctionResult::kError;
} else {
- if ((attrs & FILE_ATTRIBUTE_DIRECTORY) &&
- (attrs & FILE_ATTRIBUTE_REPARSE_POINT)) {
- return IS_JUNCTION_YES;
- } else {
- return IS_JUNCTION_NO;
- }
+ *result = (attrs & FILE_ATTRIBUTE_REPARSE_POINT);
+ return IsSymlinkOrJunctionResult::kSuccess;
}
}
diff --git a/src/main/native/windows/file.h b/src/main/native/windows/file.h
index 87d5f0ade70c9c..0e0c41570047b4 100644
--- a/src/main/native/windows/file.h
+++ b/src/main/native/windows/file.h
@@ -48,10 +48,12 @@ std::wstring RemoveUncPrefixMaybe(const std::wstring& path);
bool IsAbsoluteNormalizedWindowsPath(const std::wstring& p);
// Keep in sync with j.c.g.devtools.build.lib.windows.WindowsFileOperations
-enum {
- IS_JUNCTION_YES = 0,
- IS_JUNCTION_NO = 1,
- IS_JUNCTION_ERROR = 2,
+struct IsSymlinkOrJunctionResult {
+ enum {
+ kSuccess = 0,
+ kError = 1,
+ kDoesNotExist = 2,
+ };
};
// Keep in sync with j.c.g.devtools.build.lib.windows.WindowsFileOperations
@@ -97,16 +99,7 @@ struct ReadSymlinkOrJunctionResult {
//
// To read about differences between junctions and directory symlinks,
// see http://superuser.com/a/343079. In Bazel we only ever create junctions.
-//
-// Returns:
-// - IS_JUNCTION_YES, if `path` exists and is either a directory junction or a
-// directory symlink
-// - IS_JUNCTION_NO, if `path` exists but is neither a directory junction nor a
-// directory symlink; also when `path` is a symlink to a directory but it was
-// created using "mklink" instead of "mklink /d", as such symlinks don't
-// behave the same way as directories (e.g. they can't be listed)
-// - IS_JUNCTION_ERROR, if `path` doesn't exist or some error occurred
-int IsJunctionOrDirectorySymlink(const WCHAR* path, std::wstring* error);
+int IsSymlinkOrJunction(const WCHAR* path, bool* result, wstring* error);
// Computes the long version of `path` if it has any 8dot3 style components.
// Returns the empty string upon success, or a human-readable error message upon
| diff --git a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileOperationsTest.java b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileOperationsTest.java
index c5a50d32ab7895..11ceed1d74192c 100644
--- a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileOperationsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileOperationsTest.java
@@ -90,32 +90,32 @@ public void testIsJunction() throws Exception {
testUtil.createJunctions(junctions);
- assertThat(WindowsFileOperations.isJunction(root + "\\shrtpath\\a")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\shrtpath\\b")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\shrtpath\\c")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\longlinkpath\\a")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\longlinkpath\\b")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\longlinkpath\\c")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\longli~1\\a")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\longli~1\\b")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\longli~1\\c")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\abbreviated\\a")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\abbreviated\\b")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\abbreviated\\c")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\abbrev~1\\a")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\abbrev~1\\b")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\abbrev~1\\c")).isTrue();
- assertThat(WindowsFileOperations.isJunction(root + "\\control\\a")).isFalse();
- assertThat(WindowsFileOperations.isJunction(root + "\\control\\b")).isFalse();
- assertThat(WindowsFileOperations.isJunction(root + "\\control\\c")).isFalse();
- assertThat(WindowsFileOperations.isJunction(root + "\\shrttrgt\\file1.txt")).isFalse();
- assertThat(WindowsFileOperations.isJunction(root + "\\longtargetpath\\file2.txt")).isFalse();
- assertThat(WindowsFileOperations.isJunction(root + "\\longta~1\\file2.txt")).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\shrtpath\\a")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\shrtpath\\b")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\shrtpath\\c")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longlinkpath\\a")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longlinkpath\\b")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longlinkpath\\c")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longli~1\\a")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longli~1\\b")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longli~1\\c")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\abbreviated\\a")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\abbreviated\\b")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\abbreviated\\c")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\abbrev~1\\a")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\abbrev~1\\b")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\abbrev~1\\c")).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\control\\a")).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\control\\b")).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\control\\c")).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\shrttrgt\\file1.txt")).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longtargetpath\\file2.txt")).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(root + "\\longta~1\\file2.txt")).isFalse();
try {
- WindowsFileOperations.isJunction(root + "\\non-existent");
+ WindowsFileOperations.isSymlinkOrJunction(root + "\\non-existent");
fail("expected to throw");
} catch (IOException e) {
- assertThat(e.getMessage()).contains("nativeIsJunction");
+ assertThat(e.getMessage()).contains("path does not exist");
}
assertThat(Arrays.asList(new File(root + "/shrtpath/a").list())).containsExactly("file1.txt");
assertThat(Arrays.asList(new File(root + "/shrtpath/b").list())).containsExactly("file2.txt");
@@ -141,14 +141,14 @@ public void testIsJunctionIsTrueForDanglingJunction() throws Exception {
File linkPath = new File(helloPath.getParent().getParent().toFile(), "link");
assertThat(Arrays.asList(linkPath.list())).containsExactly("hello.txt");
- assertThat(WindowsFileOperations.isJunction(linkPath.getAbsolutePath())).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(linkPath.getAbsolutePath())).isTrue();
assertThat(helloPath.toFile().delete()).isTrue();
assertThat(helloPath.getParent().toFile().delete()).isTrue();
assertThat(helloPath.getParent().toFile().exists()).isFalse();
assertThat(Arrays.asList(linkPath.getParentFile().list())).containsExactly("link");
- assertThat(WindowsFileOperations.isJunction(linkPath.getAbsolutePath())).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(linkPath.getAbsolutePath())).isTrue();
assertThat(
Files.exists(
linkPath.toPath(), WindowsFileSystem.symlinkOpts(/* followSymlinks */ false)))
@@ -167,22 +167,22 @@ public void testIsJunctionHandlesFilesystemChangesCorrectly() throws Exception {
// Assert that a file is identified as not a junction.
String longPath = helloFile.getAbsolutePath();
String shortPath = new File(helloFile.getParentFile(), "hellow~1.txt").getAbsolutePath();
- assertThat(WindowsFileOperations.isJunction(longPath)).isFalse();
- assertThat(WindowsFileOperations.isJunction(shortPath)).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(longPath)).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(shortPath)).isFalse();
// Assert that after deleting the file and creating a junction with the same path, it is
// identified as a junction.
assertThat(helloFile.delete()).isTrue();
testUtil.createJunctions(ImmutableMap.of("target\\helloworld.txt", "target"));
- assertThat(WindowsFileOperations.isJunction(longPath)).isTrue();
- assertThat(WindowsFileOperations.isJunction(shortPath)).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(longPath)).isTrue();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(shortPath)).isTrue();
// Assert that after deleting the file and creating a directory with the same path, it is
// identified as not a junction.
assertThat(helloFile.delete()).isTrue();
assertThat(helloFile.mkdir()).isTrue();
- assertThat(WindowsFileOperations.isJunction(longPath)).isFalse();
- assertThat(WindowsFileOperations.isJunction(shortPath)).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(longPath)).isFalse();
+ assertThat(WindowsFileOperations.isSymlinkOrJunction(shortPath)).isFalse();
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
index b0c9454d5121dc..7ca6e57656a18c 100644
--- a/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
+++ b/src/test/java/com/google/devtools/build/lib/windows/WindowsFileSystemTest.java
@@ -141,35 +141,35 @@ public void testIsJunction() throws Exception {
testUtil.createJunctions(junctions);
- assertThat(WindowsFileSystem.isJunction(new File(root, "shrtpath/a"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "shrtpath/b"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "shrtpath/c"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longlinkpath/a"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longlinkpath/b"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longlinkpath/c"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longli~1/a"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longli~1/b"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longli~1/c"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "abbreviated/a"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "abbreviated/b"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "abbreviated/c"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "abbrev~1/a"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "abbrev~1/b"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "abbrev~1/c"))).isTrue();
- assertThat(WindowsFileSystem.isJunction(new File(root, "control/a"))).isFalse();
- assertThat(WindowsFileSystem.isJunction(new File(root, "control/b"))).isFalse();
- assertThat(WindowsFileSystem.isJunction(new File(root, "control/c"))).isFalse();
- assertThat(WindowsFileSystem.isJunction(new File(root, "shrttrgt/file1.txt")))
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "shrtpath/a"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "shrtpath/b"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "shrtpath/c"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longlinkpath/a"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longlinkpath/b"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longlinkpath/c"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longli~1/a"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longli~1/b"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longli~1/c"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "abbreviated/a"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "abbreviated/b"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "abbreviated/c"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "abbrev~1/a"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "abbrev~1/b"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "abbrev~1/c"))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "control/a"))).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "control/b"))).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "control/c"))).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "shrttrgt/file1.txt")))
.isFalse();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longtargetpath/file2.txt")))
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longtargetpath/file2.txt")))
.isFalse();
- assertThat(WindowsFileSystem.isJunction(new File(root, "longta~1/file2.txt")))
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(root, "longta~1/file2.txt")))
.isFalse();
try {
- WindowsFileSystem.isJunction(new File(root, "non-existent"));
+ WindowsFileSystem.isSymlinkOrJunction(new File(root, "non-existent"));
fail("expected failure");
} catch (IOException e) {
- assertThat(e.getMessage()).contains("cannot find");
+ assertThat(e.getMessage()).contains("path does not exist");
}
assertThat(Arrays.asList(new File(root + "/shrtpath/a").list())).containsExactly("file1.txt");
@@ -196,14 +196,14 @@ public void testIsJunctionIsTrueForDanglingJunction() throws Exception {
File linkPath = new File(helloPath.getParent().getParent().toFile(), "link");
assertThat(Arrays.asList(linkPath.list())).containsExactly("hello.txt");
- assertThat(WindowsFileSystem.isJunction(linkPath)).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(linkPath)).isTrue();
assertThat(helloPath.toFile().delete()).isTrue();
assertThat(helloPath.getParent().toFile().delete()).isTrue();
assertThat(helloPath.getParent().toFile().exists()).isFalse();
assertThat(Arrays.asList(linkPath.getParentFile().list())).containsExactly("link");
- assertThat(WindowsFileSystem.isJunction(linkPath)).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(linkPath)).isTrue();
assertThat(
Files.exists(
linkPath.toPath(), WindowsFileSystem.symlinkOpts(/* followSymlinks */ false)))
@@ -219,18 +219,18 @@ public void testIsJunctionHandlesFilesystemChangesCorrectly() throws Exception {
File longPath =
testUtil.scratchFile("target\\helloworld.txt", "hello").toAbsolutePath().toFile();
File shortPath = new File(longPath.getParentFile(), "hellow~1.txt");
- assertThat(WindowsFileSystem.isJunction(longPath)).isFalse();
- assertThat(WindowsFileSystem.isJunction(shortPath)).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(longPath)).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(shortPath)).isFalse();
assertThat(longPath.delete()).isTrue();
testUtil.createJunctions(ImmutableMap.of("target\\helloworld.txt", "target"));
- assertThat(WindowsFileSystem.isJunction(longPath)).isTrue();
- assertThat(WindowsFileSystem.isJunction(shortPath)).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(longPath)).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(shortPath)).isTrue();
assertThat(longPath.delete()).isTrue();
assertThat(longPath.mkdir()).isTrue();
- assertThat(WindowsFileSystem.isJunction(longPath)).isFalse();
- assertThat(WindowsFileSystem.isJunction(shortPath)).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(longPath)).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(shortPath)).isFalse();
}
@Test
@@ -311,7 +311,7 @@ public void testCreateSymbolicLink() throws Exception {
fs.createSymbolicLink(link4, fs.getPath(scratchRoot).getRelative("bar.txt").asFragment());
// Assert that link1 and link2 are true junctions and have the right contents.
for (Path p : ImmutableList.of(link1, link2)) {
- assertThat(WindowsFileSystem.isJunction(new File(p.getPathString()))).isTrue();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(p.getPathString()))).isTrue();
assertThat(p.isSymbolicLink()).isTrue();
assertThat(
Iterables.transform(
@@ -326,7 +326,7 @@ public String apply(File input) {
}
// Assert that link3 and link4 are copies of files.
for (Path p : ImmutableList.of(link3, link4)) {
- assertThat(WindowsFileSystem.isJunction(new File(p.getPathString()))).isFalse();
+ assertThat(WindowsFileSystem.isSymlinkOrJunction(new File(p.getPathString()))).isFalse();
assertThat(p.isSymbolicLink()).isFalse();
assertThat(p.isFile()).isTrue();
}
diff --git a/src/test/native/windows/file_test.cc b/src/test/native/windows/file_test.cc
index ca7604d5f45409..c4a90227cac57e 100644
--- a/src/test/native/windows/file_test.cc
+++ b/src/test/native/windows/file_test.cc
@@ -81,8 +81,10 @@ TEST_F(WindowsFileOperationsTest, TestCreateJunction) {
wstring file1(target + L"\\foo");
EXPECT_TRUE(blaze_util::CreateDummyFile(file1));
- EXPECT_EQ(IS_JUNCTION_NO,
- IsJunctionOrDirectorySymlink(target.c_str(), nullptr));
+ bool is_link = true;
+ EXPECT_EQ(IsSymlinkOrJunctionResult::kSuccess,
+ IsSymlinkOrJunction(target.c_str(), &is_link, nullptr));
+ EXPECT_FALSE(is_link);
EXPECT_NE(INVALID_FILE_ATTRIBUTES, ::GetFileAttributesW(file1.c_str()));
wstring name(tmp + L"\\junc_name");
@@ -99,14 +101,22 @@ TEST_F(WindowsFileOperationsTest, TestCreateJunction) {
CreateJunctionResult::kSuccess);
// Assert creation of the junctions.
- ASSERT_EQ(IS_JUNCTION_YES,
- IsJunctionOrDirectorySymlink((name + L"1").c_str(), nullptr));
- ASSERT_EQ(IS_JUNCTION_YES,
- IsJunctionOrDirectorySymlink((name + L"2").c_str(), nullptr));
- ASSERT_EQ(IS_JUNCTION_YES,
- IsJunctionOrDirectorySymlink((name + L"3").c_str(), nullptr));
- ASSERT_EQ(IS_JUNCTION_YES,
- IsJunctionOrDirectorySymlink((name + L"4").c_str(), nullptr));
+ is_link = false;
+ ASSERT_EQ(IsSymlinkOrJunctionResult::kSuccess,
+ IsSymlinkOrJunction((name + L"1").c_str(), &is_link, nullptr));
+ ASSERT_TRUE(is_link);
+ is_link = false;
+ ASSERT_EQ(IsSymlinkOrJunctionResult::kSuccess,
+ IsSymlinkOrJunction((name + L"2").c_str(), &is_link, nullptr));
+ ASSERT_TRUE(is_link);
+ is_link = false;
+ ASSERT_EQ(IsSymlinkOrJunctionResult::kSuccess,
+ IsSymlinkOrJunction((name + L"3").c_str(), &is_link, nullptr));
+ ASSERT_TRUE(is_link);
+ is_link = false;
+ ASSERT_EQ(IsSymlinkOrJunctionResult::kSuccess,
+ IsSymlinkOrJunction((name + L"4").c_str(), &is_link, nullptr));
+ ASSERT_TRUE(is_link);
// Assert that the file is visible under all junctions.
ASSERT_NE(INVALID_FILE_ATTRIBUTES,
| val | train | 2019-04-04T13:00:02 | "2019-04-01T11:48:09Z" | laszlocsomor | test |
bazelbuild/bazel/7947_8440 | bazelbuild/bazel | bazelbuild/bazel/7947 | bazelbuild/bazel/8440 | [
"timestamp(timedelta=0.0, similarity=0.852926208408941)"
] | 207c24f04453ef026c202f2962e55d2a125e388f | 923c45faecaabd00e0214ff7d178507623958b37 | [
"cc @brandjon ",
"Ok, I played around with our windows sandbox vm and think I understand. The most likely situation is that your `py_runtime`'s `interpreter_path` attribute doesn't correctly identify a `Python.exe` binary. Please double check the path, and if you don't think that's the problem, please post the `py_runtime` definition here.\r\n\r\nFrom my experimentation, it doesn't look like the `PATH` environment variable affects whether or not the absolute path is able to resolve successfully at execution time (i.e. we're not sandboxing anything in Windows in a way that breaks this).\r\n\r\nThe error message is a little misleading: Our Python launcher [will first check](https://github.com/bazelbuild/bazel/blob/1f684e1b87cd8881a0a4b33e86ba66743e32d674/src/tools/launcher/python_launcher.cc#L30-L35) whether the given Python interpreter file exists, and if not, fall back on \"python.exe\" on its own. This means that the error message you see will always say it can't find \"python.exe\" even if you specified `interpreter_path = r\"C:\\my_custom_interpreter.exe\"` in your `py_runtime`.\r\n\r\n(Note the \"r\" raw string literal prefix in that last sentence. Depending on your path to the Python interpreter, it's possible you're using a single backslash before something that's interpreted as a valid escape sequence, producing a different string than you think. When in doubt, it's valid to replace backslashes with slashes in windows paths.)\r\n\r\nPlease let me know if this helps. If nothing else, we'll keep this issue open to track the bad error message in the Python launcher (or the removal of that fallback entirely).",
"Actually we are using an in-build runtime from an external dependency and finally I managed to setup a simple example here [pziggo/bazel_py_runtime_win_example](https://github.com/pziggo/bazel_py_runtime_win_example).\r\n\r\nI also debugged the issue a bit more and I think I'm getting closer to understand the root cause. Thanks for the link which was a good starting point.\r\n\r\nThe [python launcher](https://github.com/bazelbuild/bazel/blob/master/src/tools/launcher/python_launcher.cc#L34) checks if the given python interpreter exists by converting the `PYTHON_BIN_PATH` into an [absolute path on Windows](https://github.com/bazelbuild/bazel/blob/master/src/tools/launcher/util/launcher_util.cc#L99). In fact by using the in-build runtime from an external dependency, the constructed path really doesn't exists:\r\n```\r\nLAUNCHER ERROR: Pyhon binary: python3_windows/python.exe\r\nLAUNCHER ERROR: Absolute python binary path: \\\\?\\c:\\users\\me\\_bazel_me\\rsotqivv\\execroot\\bazel_py_runtime_win_example\\python3_windows\\python.exe\r\n```\r\nwhile the following path exists (note the \"external\" in the path):\r\n```\r\nC:\\Users\\me\\_bazel_me\\rsotqivv\\execroot\\bazel_py_runtime_win_example\\external\\python3_windows\r\n```\r\n\r\nSo, before handing over the `python_bin_path` to the python launcher [here](https://github.com/bazelbuild/bazel/blob/558b717e906156477b1c6bd29d049a0fb8e18b27/src/main/java/com/google/devtools/build/lib/bazel/rules/python/BazelPythonSemantics.java#L218), the path will be [modified](https://github.com/bazelbuild/bazel/blob/558b717e906156477b1c6bd29d049a0fb8e18b27/src/main/java/com/google/devtools/build/lib/bazel/rules/python/BazelPythonSemantics.java#L362) and the `external` part stripped for the [runfiles tree](https://github.com/bazelbuild/bazel/blob/5458e5bb9130a537d2d6c40f3d9e42c502e4276a/src/main/java/com/google/devtools/build/lib/actions/Artifact.java#L685). But in fact, on Windows the runfiles tree lives inside the resulting zip file and thus is not a valid path for running the packaged zip if I'm not mistaken.\r\nThat would mean, for `createWindowsExeLauncher()` the value of `pythonBinary` must be different then for the functions that build the content of the zip file / using the runfiles.",
"Thank you for the investigation and repro! I haven't run your repro yet, but if I understand correctly it sounds like the scope of this problem is anytime the `py_runtime` references an in-build interpreter from an external repo on Windows.",
"Yes, sounds about right.",
"But I wonder what would be a good change to solve the problem. Fixing the path could be relatively easy, but that would not work on remote execution if I’m not mistaken.\r\nSo, the interpreter should become a direct runtime dependency and available in the runfiles tree. But I think having the interpreter twice (in the runfiles and inside the zip) is not optimal either for the overall performance.",
"+@laszlocsomor FYI.\r\n\r\nSo to summarize: When an in-build interpreter is used on Windows, the Python launcher will take its workspace-relative path and use that in combination with its own working directory to construct the full (non-runfile) path to the interpreter. Due to a bug, this fails when the interpreter is defined in an external repo.\r\n\r\nI'm not sure what the plan is for remote execution and windows, but there are likely already other blockers within the Python rules. For instance, BazelPythonSemantics [checks](https://github.com/bazelbuild/bazel/blob/4c6fb96cebefa5fc2b0cb31d1fcd2292fb30e652/src/main/java/com/google/devtools/build/lib/bazel/rules/python/BazelPythonSemantics.java#L145) `OS.getCurrent` to decide whether to use a launcher, but that's not needed if the target platform isn't windows.\r\n\r\nAside from that, this behavior is another difference between unix and Windows. On unix, the shebang of the stub script is `#!/usr/bin/env python` regardless of what interpreter will later be used to execute the payload. But on Windows, this launcher behavior means that the stub script (in the zip file's `__main__.py`) will use whatever the payload's interpreter is, instead of always using a standard system interpreter to bootstrap. I don't see an obvious flaw in doing it that way, but it is a conceptual difference.\r\n\r\nYou can see an analogous version of this bug in google/subpar#98, where in-build interpreters caused the shebang to get a relative path.",
"Regarding priority: This issue prevents using many kinds of in-workspace Python runtimes on Windows, including interpreters provided by external repos (e.g. `@bazel_tools`) and interpreters that are generated artifacts as opposed to checked-in binaries. In particular, it blocks the addition of the autodetecting toolchain on Windows (#7844). However, it does not block the roll out of Python toolchains (#7899), because the default toolchain on Windows is a hack that preserves legacy behavior.\r\n\r\nTherefore, a fix for this won't be in 0.27, but it'd be great to have it for 0.28.\r\n\r\n---\r\n\r\nNow on to the actual design issue. As I alluded to above, on unix we use a two-phase approach to launching Python programs.\r\n\r\n1. A system interpreter is used to run the stub script or zip file, which initializes env vars, locates/extracts runfiles, etc. This interpreter is discovered by the shebang `#!/usr/bin/env python`.\r\n\r\n2. A separate interpreter is called by the stub logic to run the payload user code. This may be either a system interpreter or an in-workspace (i.e. runfiles) interpreter.\r\n\r\nThis separation into two separate phases is what enables us to use an in-workspace interpreter packaged within a zip file. The zip depends on a system interpreter to bootstrap and extract itself.\r\n\r\nOn Windows, this separation does not currently exist: Regardless of whether you're using a zip file or not, the Python launcher will try to run the stub script with the same interpreter that your toolchain requests to be used for payload user code. *This can be an interpreter in runfiles, which haven't been extracted yet.*\r\n\r\nThe way we currently get around this is by giving the launcher a path to the interpreter binary on disk, i.e. the actual checked-in source file or the built binary file in the output tree. This is pretty brittle. First, there's the breakage described above, when the path construction doesn't quite work out. But even if we fix that by passing an absolute path to the on-disk file, we'd end up in a situation where the resulting `py_binary` (launcher) executable breaks if you move your source files around or run `bazel clean`, even if you've already copied the exe and zip files elsewhere on your system.\r\n\r\nSo let's revisit our strategy: There's no reason we need to use the same interpreter for the zip file / stub script that we do for the payload code. We can assume the presence of a system Python interpreter for the purposes of bootstrapping. The launcher can hardcode that assumption, which could take different forms, for example:\r\n\r\n* `python.exe` is on PATH\r\n* `py.exe` is on PATH\r\n* I can locate a Python interpreter by doing some registry stuff\r\n\r\nIt's even possible to let the Python toolchain customize how the bootstrapping interpreter is found, just like you could let it parameterize the shebang string. But I don't see much value in this at the moment.\r\n\r\nSo right now, I think the goal should be to add `python.exe` / `py.exe` detection to the launcher, and no longer pass an interpreter to the launcher. Note that we write the stub script to target a lowest common denominator of reasonable Python interpreters, so it shouldn't matter what version interpreter the launcher comes up with.",
"Thanks for the summary!\r\n\r\n> on unix we use a two-phase approach to launching Python programs.\r\n\r\nIIUC we do so because the stub script itself is in Python, so the binary requires a system interpreter even in presence of a bundled interpreter. But isn't part of a bundled interpreter's goal to enable running without a system interpreter?\r\n\r\nThe analogous problem is running Bazel itself. The embedded JVM lets you run Bazel without a system JVM. Its launcher (the bazel client) is a native binary.\r\n\r\n> On Windows, this separation does not currently exist: Regardless of whether you're using a zip file or not, the Python launcher will try to run the stub script with the same interpreter that your toolchain requests to be used for payload user code. *This can be an interpreter in runfiles, which haven't been extracted yet.*\r\n\r\nSure, the launcher should begin with extracting the payload. We can fix that.\r\n\r\n> We can assume the presence of a system Python interpreter for the purposes of bootstrapping.\r\n\r\nDoesn't that partially beat the purpose of a bundled interpreter? If the stub weren't a python script but were part of the .exe launcher, we wouldn't need this assumption.\r\n\r\nMy questions:\r\n- what do you all think about my assessment that the bundled interpreter should enable the binary to run without a system interpreter?\r\n- what does the stub script do? could the native launcher do that instead?\r\n- the native launcher's `python_binary` field could either contain a runfile path (e.g. `runfile:python3_windows/python.exe`, meaning either a runfile path to be retrieved with rlocation or a path in the zip), or a basename (e.g. `python.exe`, meaning the current interpreter on the PATH, whatever it may be) -- WDYT?",
"> the native launcher's python_binary field could either contain a runfile path (e.g. runfile:python3_windows/python.exe, meaning either a runfile path to be retrieved with rlocation or a path in the zip)\r\n\r\nThis is true when using python toolchain or `--python_top`. That's why #8440 can fix this problem.",
"With #8440, I can run all commands in https://github.com/pziggo/bazel_py_runtime_win_example, but got error like this\r\n```\r\npcloudy@pcloudy0-w MSYS ~/workspace/bazel_py_runtime_win_example\r\n$ bazel build --python_top=//tools/python:py3_windows_runtime //:test\r\nExtracting Bazel installation...\r\nStarting local Bazel server and connecting to it...\r\nINFO: Reading 'startup' options from c:\\users\\pcloudy\\.bazelrc: --output_user_root=C:/src/tmp\r\nINFO: Options provided by the client:\r\n Inherited 'common' options: --isatty=1 --terminal_columns=320\r\nINFO: Options provided by the client:\r\n 'build' options: --python_path=C:/Python36/python.exe\r\nINFO: Reading rc options for 'build' from c:\\users\\pcloudy\\.bazelrc:\r\n 'build' options: --curses=yes --color=yes --verbose_failures --announce_rc\r\nINFO: Analyzed target //:test (14 packages loaded, 113 targets configured).\r\nINFO: Found 1 target...\r\nINFO: Deleting stale sandbox base C:/src/tmp/ewf7xl5y/sandbox\r\nERROR: C:/tools/msys64/home/pcloudy/workspace/bazel_py_runtime_win_example/BUILD:3:1: Generating file failed (Exit 1): generator.exe failed: error executing command\r\n cd C:/src/tmp/ewf7xl5y/execroot/bazel_py_runtime_win_example\r\nbazel-out/host/bin/tools/generator/generator.exe bazel-out/x64_windows-fastbuild/bin/file\r\nExecution platform: @bazel_tools//platforms:host_platform\r\nTraceback (most recent call last):\r\n File \"D:\\obj\\Windows-Release\\37amd64_Release\\msi_python\\zip_amd64\\runpy.py\", line 193, in _run_module_as_main\r\n File \"D:\\obj\\Windows-Release\\37amd64_Release\\msi_python\\zip_amd64\\runpy.py\", line 85, in _run_code\r\n File \"C:\\src\\tmp\\ewf7xl5y\\execroot\\bazel_py_runtime_win_example\\bazel-out\\host\\bin\\tools\\generator\\generator.zip\\__main__.py\", line 303, in <module>\r\n File \"C:\\src\\tmp\\ewf7xl5y\\execroot\\bazel_py_runtime_win_example\\bazel-out\\host\\bin\\tools\\generator\\generator.zip\\__main__.py\", line 282, in Main\r\nNameError: name 'exit' is not defined\r\nC:\\Users\\pcloudy\\AppData\\Local\\Temp\\Bazel.runfiles_s6rwiedn\\runfiles\\python3_windows\\python.exe\r\nTarget //:test failed to build\r\nINFO: Elapsed time: 5.256s, Critical Path: 0.47s\r\nINFO: 0 processes.\r\nFAILED: Build did NOT complete successfully\r\n```\r\nBut it's caused by the python binary we are using, not a Bazel bug.",
"> But isn't part of a bundled interpreter's goal to enable running without a system interpreter?\r\n\r\nI don't think this is something we need to prioritize, but it'd be nice to have in the future. With a bundled interpreter that requires the system interpreter for bootstrapping, you still get hermeticity once you're past the stub script phase.\r\n\r\n> The analogous problem is running Bazel itself. The embedded JVM lets you run Bazel without a system JVM. Its launcher (the bazel client) is a native binary.\r\n\r\nThen by that logic we could embed a native Python interpreter (perhaps miniaturized) into each py_binary artifact. But at that point perhaps it'd be worth rewriting the stub script in C++.\r\n\r\nAn alternative to embedding an extra interpreter into the artifact would be to have a way of extracting the payload user code's interpreter from runfiles without using Python... and again the way to do that would be essentially rewriting the stub in C++.\r\n\r\n> Sure, the launcher should begin with extracting the payload. We can fix that.\r\n\r\nSounds like we're arriving at similar conclusions.\r\n\r\n> what does the stub script do? could the native launcher do that instead?\r\n\r\nThe [stub script](https://github.com/bazelbuild/bazel/blob/6f38f345a1bd278a71170c5d80aba3928afdc6ec/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt#L221):\r\n\r\n1. locates the runfiles directory, or locates and extracts the zip to create the runfiles directory\r\n2. initializes environment variables, including for the runfiles library, and PYTHONPATH\r\n3. locates the main file (entry point of payload user code) and second-stage Python interpreter\r\n4. invokes the interpreter on the main file and cleans up the extracted zip contents\r\n\r\n> the native launcher's python_binary field could either contain a runfile path (e.g. runfile:python3_windows/python.exe, meaning either a runfile path to be retrieved with rlocation or a path in the zip), or a basename (e.g. python.exe, meaning the current interpreter on the PATH, whatever it may be) -- WDYT?\r\n\r\nIn principle the stub script should be runnable under any reasonable Python interpreter (with some hand wavyness around \"reasonable\"). So there shouldn't be a need to customize which system interpreter is used, whether it's `python2`, `python3`, `python.exe`, `py.exe` (the Python wrapper on Windows), etc. I'd like to avoid adding the ability to customize that until it proves to be appropriate and useful. Same goes for the unix shebang, which is currently hardcoded as `#!/usr/bin/env python`.\r\n\r\nHowever, if we're eliminating the dependency on a system interpreter and just using whatever interpreter is specified for the payload user code (whether system or runfiles based), then we'd just pass that along to the launcher, as we do today.",
"> But it's caused by the python binary we are using, not a Bazel bug.\r\n\r\n[Apparently](https://stackoverflow.com/a/6501134) the `exit()` function doesn't exist if you invoke Python with `-S`. We should change our calls to `exit()` in the stub script to instead use `sys.exit()`. I'll make a quick fix for that.",
"> > But isn't part of a bundled interpreter's goal to enable running without a system interpreter?\r\n> \r\n> I don't think this is something we need to prioritize, but it'd be nice to have in the future. With a bundled interpreter that requires the system interpreter for bootstrapping, you still get hermeticity once you're past the stub script phase.\r\n\r\nThanks for confirming. I just wanted to note that requiring an ambient Python interpreter might cause frustration. People were unhappy about Bazel requiring MSYS2 too.\r\n\r\n> > The analogous problem is running Bazel itself. The embedded JVM lets you run Bazel without a system JVM. Its launcher (the bazel client) is a native binary.\r\n> \r\n> Then by that logic we could embed a native Python interpreter (perhaps miniaturized) into each py_binary artifact. But at that point perhaps it'd be worth rewriting the stub script in C++.\r\n\r\nSounds reasonable.\r\n\r\n> An alternative to embedding an extra interpreter into the artifact would be to have a way of extracting the payload user code's interpreter from runfiles without using Python... and again the way to do that would be essentially rewriting the stub in C++.\r\n\r\nAgreed. The Bazel client does the same.\r\n\r\n> > Sure, the launcher should begin with extracting the payload. We can fix that.\r\n> \r\n> Sounds like we're arriving at similar conclusions.\r\n\r\nIndeed. :)\r\n\r\n> > what does the stub script do? could the native launcher do that instead?\r\n> \r\n> The [stub script](https://github.com/bazelbuild/bazel/blob/6f38f345a1bd278a71170c5d80aba3928afdc6ec/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt#L221):\r\n> \r\n> 1. locates the runfiles directory, or locates and extracts the zip to create the runfiles directory\r\n> 2. initializes environment variables, including for the runfiles library, and PYTHONPATH\r\n> 3. locates the main file (entry point of payload user code) and second-stage Python interpreter\r\n> 4. invokes the interpreter on the main file and cleans up the extracted zip contents\r\n\r\nThanks. None of that sounds daunting. I implemented the [test wrapper in C++](https://github.com/bazelbuild/bazel/blob/6f38f345a1bd278a71170c5d80aba3928afdc6ec/tools/test/windows/tw.cc). It solves similar problems, we could reuse it. (It's Windows-focused though.)",
"That all sounds good to me. I forked off #8446.\r\n\r\nIn the meantime, we should make the launcher better at detecting a system interpreter. We can track that in this bug.",
"Let's discuss the merits of the approach of #8440 here. That PR makes it so if a runfiles path is passed to the launcher, it uses rlocation to resolve that to its absolute path. Since when a zip file is used the runfiles are manifest-based rather than directory-based, this doesn't suffer the chicken-and-egg problem of accessing an interpreter in a zip.\r\n\r\nIt does suffer the problem where if the build is cleaned, the .exe artifact is broken, even if it is copied out of the output tree. Currently I believe the .exe only depends on having the .zip in the same directory. I'm ok with settling for this limitation for now as a fix of existing behavior. It'll be moot once the launcher extracts the zip.",
"Although, one consequence of this design is that if you have no system Python interpreter, but your build has a checked-in interpreter, it'll work on your development machine since the actual not-in-runfiles interpreter file is available, and then fail on a user's machine. But we don't have a better option before #8446, unless we want to fail fast on the development machine.",
"Indeed #8440 is just for making existing behavior that works on Linux also works on Windows. \r\n\r\nBeyond this, it's not a Windows only problem. Ideally we should move all logic in `python_stub_template.txt` to the python native launcher. I considered to do so when implementing the native launcher, but at that time we were still making many changes to `python_stub_template.txt` and native launcher is only for Windows (also true today).",
"@brandjon , @meteorcloudy : does any of you plan to work on this?",
"@brandjon has a change to enable more python toolchain integration tests on Windows, I will submit my fix for this issue afterwards.\r\n\r\nYet I have no plan to migrate the `python_stub_template.txt` to C++.",
"Thanks. I consider migrating it.\r\nCan anyone help me prioritize it?",
"My pending fix blocked on a failing test over the long weekend, looking at it again today.",
"My fix finally went through, merging the fix to this issue now."
] | [
"Can the input `bash_binary` ever be just `bash.exe` for example, which would mean \"whatever is on the PATH\"?",
"I think there are two ways to tell which shell binary to use, `BAZEL_SH` or `--shell_executable`. Both way requires user to set an absolute path. The only case `bash_binary` is a relative path (runfile path) is that when using shell toolchain (similar to python toolchain), but I'm not sure it's implemented.",
"But here, `python_binary` will just be `python` if nothing is specified.. I need to fix this.",
"Thanks, let me know when the PR is ready for another review.",
"Thanks for catching the problem! Please take a look again. ;)",
"Just checking: `bash_binary` can either be an absolute Bash path (from `BAZEL_SH` or `--shell_executable`), or (theoretically perhaps) a bash toolchain's runfiles-relative path. Correct?\r\n\r\nAnd it always ends with \"bash\" or \"bash.exe\" (so just \"bash\" without the extension), right?\r\n\r\nAny other option I'm missing?",
"What other values could `python_binary` have, and in what situations?",
"Everything you said I believe is true, I don't think there's any other option.",
"Similar to shell, we have\r\n\r\n1. `--python_path`, gives an absolute path\r\n2. `--python_top`, gives an runfile path\r\n3. python toolchain (`py_runtime`), gives a runfile path\r\n4. Default if nothing specified: `python`\r\n\r\n@brandjon Can confirm this.",
"Thanks for confirming that!",
"Could you please add a comment about this?",
"Thanks! Waiting for @brandjon to confirm before LGTM. Please add a comment in the code summarizing Jon's answer.",
"Will do that!",
"Oh, just realized I had a typo. It should be `GetBinaryPathWithoutExtension(bash_binary) != L\"bash\")`, `GetBinaryPathWithoutExtension` just strips out the ending `.exe` if there is any. I wanted to check if bash_binary is already `bash` or `bash.exe`. Similar for the python case.",
"Will add comment for this!",
"Both `--python_top` and Python toolchains select a `py_runtime` to use. `py_runtime` provides a runfiles path if its `interpreter` attribute is set, and an absolute path if its `interpreter_path` attribute is set (these attributes are exclusive).\r\n\r\n`--python_path` is validated to be an absolute path. If nothing is specified, the `python` default is passed along the same code path that `--python_path` uses but skips this validation check as a special case. It is intended that both of these approaches are deprecated and replaced by toolchains, with the `python` PATH lookup behavior provided by an autodetecting toolchain.",
"Thanks for the confirmation, I'll add those to comment",
"Rewrite comment as follows:\r\n\r\n> There are three kinds of values for `python_binary`:\r\n> 1. An absolute path to a system interpreter. This is the case if `--python_path` is set by the user, or if a `py_runtime` is used that has `interpreter_path` set.\r\n> 2. A runfile path to an in-workspace interpreter. This is the case if a `py_runtime` is used that has `interpreter` set.\r\n> 3. The special constant, \"python\". This is the default case if neither of the above apply.\r\n> Rlocation resolves runfiles paths to absolute paths, and if given an absolute path it leaves it alone, so it's suitable for cases 1 and 2.\r\n\r\nThere's a slight detail that the default toolchain's py_runtime on windows contains a sentinel value hack that tells bazel to use legacy --python_path, but I don't think we need to mention that in this comment.",
"Thanks for help with the comment!"
] | "2019-05-22T12:24:59Z" | [
"type: bug",
"P1",
"team-Rules-Python"
] | Neither python_top nor python toolchain works with starlark actions on windows | ### Description of the problem / feature request:
Trying to use a `py_binary()` target as executable with `actions.run()` fails on windows if `py_runtime()` is used. Error Message:
```
LAUNCHER ERROR: Cannot launch process: "python.exe" ${PATH}\my_py_binary.zip ${ARGS}
Reason: (error: 2): The system cannot find the file specified.
```
This issue happens with `python_top` and the new python toolchain feature. It works fine on Linux though.
### Feature requests: what underlying problem are you trying to solve with this feature?
Executing python actions during the build with a hermetic python environment.
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
see [here](https://github.com/pziggo/bazel_py_runtime_win_example)
### What operating system are you running Bazel on?
Windows 10
### What's the output of `bazel info release`?
`development version`
### If `bazel info release` returns "development version" or "(@non-git)", tell us how you built Bazel.
`bazel build //src:bazel_jdk_minimal` on Windows 10
### What's the output of `git remote get-url origin ; git rev-parse master ; git rev-parse HEAD` ?
https://github.com/bazelbuild/bazel.git
78d68315cb6dc2d7e747b444fa493a78cb2a6f09
78d68315cb6dc2d7e747b444fa493a78cb2a6f09
### Have you found anything relevant by searching the web?
Discussion has been started on Slack: https://bazelbuild.slack.com/archives/CA306CEV6/p1554299740008400
### Any other information, logs, or outputs that you want to share?
From the resulting `__main__.py`
```
PYTHON_BINARY = 'python3_windows/python.exe'
if IsWindows() and not HasWindowsExecutableExtension(PYTHON_BINARY):
PYTHON_BINARY = PYTHON_BINARY + '.exe'
```
from the rule definition:
```
"_generator": attr.label(
cfg = "host",
executable = True,
allow_files = False,
default = Label("//bazel/tools/generator:generator"),
),
```
and from the rule implementation
```
ctx.actions.run(
inputs = [],
outputs = [out_file],
executable = ctx.executable._generator,
arguments = [args],
)
```
| [
"src/tools/launcher/bash_launcher.cc",
"src/tools/launcher/python_launcher.cc"
] | [
"src/tools/launcher/bash_launcher.cc",
"src/tools/launcher/python_launcher.cc"
] | [] | diff --git a/src/tools/launcher/bash_launcher.cc b/src/tools/launcher/bash_launcher.cc
index 0020d5f92d55d3..67f0a5d53a2b51 100644
--- a/src/tools/launcher/bash_launcher.cc
+++ b/src/tools/launcher/bash_launcher.cc
@@ -30,6 +30,14 @@ static constexpr const char* BASH_BIN_PATH = "bash_bin_path";
ExitCode BashBinaryLauncher::Launch() {
wstring bash_binary = this->GetLaunchInfoByKey(BASH_BIN_PATH);
+
+ // If bash_binary is already "bash" or "bash.exe", that means we want to
+ // rely on the shell binary in PATH, no need to do Rlocation.
+ if (GetBinaryPathWithoutExtension(bash_binary) != L"bash") {
+ // Rlocation returns the original path if bash_binary is an absolute path.
+ bash_binary = this->Rlocation(bash_binary, true);
+ }
+
if (DoesFilePathExist(bash_binary.c_str())) {
wstring bash_bin_dir = GetParentDirFromPath(bash_binary);
wstring path_env;
diff --git a/src/tools/launcher/python_launcher.cc b/src/tools/launcher/python_launcher.cc
index c4d2d5c04670fd..be655cf1c4eeb2 100644
--- a/src/tools/launcher/python_launcher.cc
+++ b/src/tools/launcher/python_launcher.cc
@@ -30,6 +30,20 @@ static constexpr const char* WINDOWS_STYLE_ESCAPE_JVM_FLAGS = "escape_args";
ExitCode PythonBinaryLauncher::Launch() {
wstring python_binary = this->GetLaunchInfoByKey(PYTHON_BIN_PATH);
+
+ // There are three kinds of values for `python_binary`:
+ // 1. An absolute path to a system interpreter. This is the case if `--python_path` is set by the
+ // user, or if a `py_runtime` is used that has `interpreter_path` set.
+ // 2. A runfile path to an in-workspace interpreter. This is the case if a `py_runtime` is used
+ // that has `interpreter` set.
+ // 3. The special constant, "python". This is the default case if neither of the above apply.
+ // Rlocation resolves runfiles paths to absolute paths, and if given an absolute path it leaves
+ // it alone, so it's suitable for cases 1 and 2.
+ if (GetBinaryPathWithoutExtension(python_binary) != L"python") {
+ // Rlocation returns the original path if python_binary is an absolute path.
+ python_binary = this->Rlocation(python_binary, true);
+ }
+
// If specified python binary path doesn't exist, then fall back to
// python.exe and hope it's in PATH.
if (!DoesFilePathExist(python_binary.c_str())) {
| null | train | train | 2019-05-22T12:19:28 | "2019-04-04T19:31:03Z" | pziggo | test |
bazelbuild/bazel/7956_7957 | bazelbuild/bazel | bazelbuild/bazel/7956 | bazelbuild/bazel/7957 | [
"timestamp(timedelta=0.0, similarity=0.9244978617764588)"
] | 466bf40f3f41fa6edf66f6401c5c16cb9b53510d | 6d4223b51218f4f2ffad0f118006dee2f777a96e | [] | [] | "2019-04-05T14:10:44Z" | [
"type: bug",
"P2",
"area-Windows",
"team-OSS"
] | Windows: native test wrapper incorrectly escapes arguments [blocking #6622] | ### Description of the problem / feature request:
The Windows-native test wrapper should escape arguments when running the test.
To escape them, it should use https://github.com/bazelbuild/bazel/blob/afeb8d0b7fef619159fc8fbaaeb8bd41dd2619bd/src/tools/launcher/util/launcher_util.h#L61
### Bugs: what's the simplest, easiest way to reproduce this bug? Please provide a minimal example if possible.
`BUILD`:
```
py_test(
name = "testargs",
srcs = ["testargs.py"],
args = ["foo", "a b", "", r"c\ d", "\'\'", "bar"],
)
```
`testargs.py`:
```
from __future__ import print_function
import sys
for a in sys.argv[1:]:
print("arg=(%s)" % a)
```
Build Bazel from HEAD, e.g. afeb8d0b7fef619159fc8fbaaeb8bd41dd2619bd.
Then use this binary:
```
C:\src\tmp>c:\src\bazel\bazel-bin\src\bazel.exe --incompatible_windows_style_arg_escaping test --incompatible_windows_native_test_wrapper //:testargs -t- --test_output=all
(...)
==================== Test output for //:testargs:
arg=(foo)
arg=(a)
arg=(b)
arg=(c)
arg=(d)
arg=()
arg=(bar)
================================================================================
```
The desired output is:
```
arg=(foo)
arg=(a)
arg=(b)
arg=(c d)
arg=()
arg=(bar)
```
i.e. `c d` is one argument.
### What operating system are you running Bazel on?
windows 10
### What's the output of `bazel info release`?
I built bazel from HEAD (afeb8d0b7fef619159fc8fbaaeb8bd41dd2619bd).
### Any other information, logs, or outputs that you want to share?
This is blocking https://github.com/bazelbuild/bazel/issues/6622 | [
"src/tools/launcher/util/BUILD"
] | [
"src/tools/launcher/util/BUILD"
] | [
"src/test/py/bazel/BUILD",
"src/test/py/bazel/printargs.cc",
"src/test/py/bazel/test_wrapper_test.py",
"tools/test/BUILD",
"tools/test/windows/tw.cc"
] | diff --git a/src/tools/launcher/util/BUILD b/src/tools/launcher/util/BUILD
index 5077e2300775eb..e3aa79a8fe6ad7 100644
--- a/src/tools/launcher/util/BUILD
+++ b/src/tools/launcher/util/BUILD
@@ -1,6 +1,6 @@
package(default_visibility = ["//src/tools/launcher:__subpackages__"])
-load("//src/tools/launcher:win_rules.bzl", "cc_library", "cc_binary", "cc_test")
+load("//src/tools/launcher:win_rules.bzl", "cc_binary", "cc_library", "cc_test")
filegroup(
name = "srcs",
@@ -19,6 +19,10 @@ cc_library(
name = "util",
srcs = ["launcher_util.cc"],
hdrs = ["launcher_util.h"],
+ visibility = [
+ "//src/tools/launcher:__subpackages__",
+ "//tools/test:__pkg__",
+ ],
deps = ["//src/main/cpp/util:filesystem"],
)
| diff --git a/src/test/py/bazel/BUILD b/src/test/py/bazel/BUILD
index d5f59d680c4530..ae947e2c9ba5c8 100644
--- a/src/test/py/bazel/BUILD
+++ b/src/test/py/bazel/BUILD
@@ -164,6 +164,16 @@ py_test(
"//src/conditions:windows": [":test_base"],
"//conditions:default": [],
}),
+ data = select({
+ "//src/conditions:windows": [":printargs"],
+ "//conditions:default": [],
+ }),
+)
+
+cc_binary(
+ name = "printargs",
+ srcs = ["printargs.cc"],
+ testonly = 1,
)
py_test(
diff --git a/src/test/py/bazel/printargs.cc b/src/test/py/bazel/printargs.cc
new file mode 100644
index 00000000000000..745398b824be99
--- /dev/null
+++ b/src/test/py/bazel/printargs.cc
@@ -0,0 +1,7 @@
+#include <stdio.h>
+int main(int argc, char** argv) {
+ for (int i = 1; i < argc; ++i) {
+ printf("arg=(%s)\n", argv[i]);
+ }
+ return 0;
+}
diff --git a/src/test/py/bazel/test_wrapper_test.py b/src/test/py/bazel/test_wrapper_test.py
index 7665f6810d93f3..b214dac24628f1 100644
--- a/src/test/py/bazel/test_wrapper_test.py
+++ b/src/test/py/bazel/test_wrapper_test.py
@@ -81,9 +81,9 @@ def _CreateMockWorkspace(self):
' srcs = ["unexported.bat"],',
')',
'sh_test(',
- ' name = "testargs_test.bat",',
- ' srcs = ["testargs.bat"],',
- ' args = ["foo", "a b", "", "bar"],',
+ ' name = "testargs_test.exe",',
+ ' srcs = ["testargs.exe"],',
+ r' args = ["foo", "a b", "", "\"c d\"", "\"\"", "bar"],',
')',
'py_test(',
' name = "undecl_test",',
@@ -134,21 +134,11 @@ def _CreateMockWorkspace(self):
'@echo BAD=%TEST_UNDECLARED_OUTPUTS_MANIFEST%',
],
executable=True)
- self.ScratchFile(
- 'foo/testargs.bat',
- [
- '@echo arg=(%~nx0)', # basename of $0
- '@echo arg=(%1)',
- '@echo arg=(%2)',
- '@echo arg=(%3)',
- '@echo arg=(%4)',
- '@echo arg=(%5)',
- '@echo arg=(%6)',
- '@echo arg=(%7)',
- '@echo arg=(%8)',
- '@echo arg=(%9)',
- ],
- executable=True)
+
+ self.CopyFile(
+ src_path = self.Rlocation("io_bazel/src/test/py/bazel/printargs.exe"),
+ dst_path = "foo/testargs.exe",
+ executable = True)
# A single white pixel as an ".ico" file. /usr/bin/file should identify this
# as "image/x-icon".
@@ -385,7 +375,7 @@ def _AssertTestArgs(self, flag, expected):
exit_code, stdout, stderr = self.RunBazel([
'test',
- '//foo:testargs_test.bat',
+ '//foo:testargs_test.exe',
'-t-',
'--test_output=all',
'--test_arg=baz',
@@ -568,24 +558,20 @@ def testTestExecutionWithTestSetupSh(self):
self._AssertTestArgs(
flag,
[
- '(testargs_test.bat)',
'(foo)',
'(a)',
'(b)',
+ '(c d)',
+ '()',
'(bar)',
- # Note: debugging shows that test-setup.sh receives more-or-less
- # good arguments (let's ignore issues #6276 and #6277 for now), but
- # mangles the last few.
- # I (laszlocsomor@) don't know the reason (as of 2018-10-01) but
- # since I'm planning to phase out test-setup.sh on Windows in favor
- # of the native test wrapper, I don't intend to debug this further.
- # The test is here merely to guard against unwanted future change of
- # behavior.
'(baz)',
- '("\\"x)',
- '(y\\"")',
- '("\\\\\\")',
- '(qux")'
+ '("x y")',
+ # I (laszlocsomor@) don't know the exact reason (as of 2019-04-05)
+ # why () and (qux) are mangled as they are, but since I'm planning
+ # to phase out test-setup.sh on Windows in favor of the native test
+ # wrapper, I don't intend to debug this further. The test is here
+ # merely to guard against unwanted future change of behavior.
+ '(\\" qux)'
])
self._AssertUndeclaredOutputs(flag)
self._AssertUndeclaredOutputsAnnotations(flag)
@@ -606,7 +592,6 @@ def testTestExecutionWithTestWrapperExe(self):
self._AssertTestArgs(
flag,
[
- '(testargs_test.bat)',
'(foo)',
# TODO(laszlocsomor): assert that "a b" is passed as one argument,
# not two, after https://github.com/bazelbuild/bazel/issues/6277
@@ -616,12 +601,13 @@ def testTestExecutionWithTestWrapperExe(self):
# TODO(laszlocsomor): assert that the empty string argument is
# passed, after https://github.com/bazelbuild/bazel/issues/6276
# is fixed.
+ '(c d)',
+ '()',
'(bar)',
'(baz)',
'("x y")',
'("")',
'(qux)',
- '()'
])
self._AssertUndeclaredOutputs(flag)
self._AssertUndeclaredOutputsAnnotations(flag)
diff --git a/tools/test/BUILD b/tools/test/BUILD
index 735e2fbb0132e1..6deb7dde275004 100644
--- a/tools/test/BUILD
+++ b/tools/test/BUILD
@@ -80,6 +80,7 @@ cc_library(
"//src/main/cpp/util:strings",
"//src/main/native/windows:lib-file",
"//src/main/native/windows:lib-util",
+ "//src/tools/launcher/util",
"//third_party/ijar:zip",
"@bazel_tools//tools/cpp/runfiles",
],
diff --git a/tools/test/windows/tw.cc b/tools/test/windows/tw.cc
index aec0853c21eb46..cacbd66477084c 100644
--- a/tools/test/windows/tw.cc
+++ b/tools/test/windows/tw.cc
@@ -43,6 +43,7 @@
#include "src/main/cpp/util/strings.h"
#include "src/main/native/windows/file.h"
#include "src/main/native/windows/util.h"
+#include "src/tools/launcher/util/launcher_util.h"
#include "third_party/ijar/common.h"
#include "third_party/ijar/platform_utils.h"
#include "third_party/ijar/zip.h"
@@ -1118,7 +1119,7 @@ bool AddCommandLineArg(const wchar_t* arg, const size_t arg_size,
}
bool CreateCommandLine(const Path& path,
- const std::vector<const wchar_t*>& args,
+ const std::vector<std::wstring>& args,
std::unique_ptr<WCHAR[]>* result) {
// kMaxCmdline value: see lpCommandLine parameter of CreateProcessW.
static constexpr size_t kMaxCmdline = 32767;
@@ -1132,9 +1133,9 @@ bool CreateCommandLine(const Path& path,
return false;
}
- for (const auto arg : args) {
- if (!AddCommandLineArg(arg, wcslen(arg), false, result->get(), kMaxCmdline,
- &total_len)) {
+ for (const std::wstring& arg : args) {
+ if (!AddCommandLineArg(arg.c_str(), arg.size(), false, result->get(),
+ kMaxCmdline, &total_len)) {
return false;
}
}
@@ -1145,7 +1146,7 @@ bool CreateCommandLine(const Path& path,
return true;
}
-bool StartSubprocess(const Path& path, const std::vector<const wchar_t*>& args,
+bool StartSubprocess(const Path& path, const std::vector<std::wstring>& args,
const Path& outerr, std::unique_ptr<Tee>* tee,
LARGE_INTEGER* start_time,
bazel::windows::AutoHandle* process) {
@@ -1342,7 +1343,7 @@ bool CreateUndeclaredOutputsAnnotations(const Path& undecl_annot_dir,
bool ParseArgs(int argc, wchar_t** argv, Path* out_argv0,
std::wstring* out_test_path_arg,
- std::vector<const wchar_t*>* out_args) {
+ std::vector<std::wstring>* out_args) {
if (!out_argv0->Set(argv[0])) {
return false;
}
@@ -1358,7 +1359,7 @@ bool ParseArgs(int argc, wchar_t** argv, Path* out_argv0,
out_args->clear();
out_args->reserve(argc - 1);
for (int i = 1; i < argc; i++) {
- out_args->push_back(argv[i]);
+ out_args->push_back(bazel::launcher::WindowsEscapeArg2(argv[i]));
}
return true;
}
@@ -1434,7 +1435,7 @@ bool TeeImpl::MainFunc() const {
}
int RunSubprocess(const Path& test_path,
- const std::vector<const wchar_t*>& args,
+ const std::vector<std::wstring>& args,
const Path& test_outerr, Duration* test_duration) {
std::unique_ptr<Tee> tee;
bazel::windows::AutoHandle process;
@@ -1871,7 +1872,7 @@ int TestWrapperMain(int argc, wchar_t** argv) {
std::wstring test_path_arg;
Path test_path, exec_root, srcdir, tmpdir, test_outerr, xml_log;
UndeclaredOutputs undecl;
- std::vector<const wchar_t*> args;
+ std::vector<std::wstring> args;
if (!ParseArgs(argc, argv, &argv0, &test_path_arg, &args) ||
!PrintTestLogStartMarker() ||
!FindTestBinary(argv0, test_path_arg, &test_path) ||
| test | train | 2019-04-05T16:48:05 | "2019-04-05T13:53:47Z" | laszlocsomor | test |
bazelbuild/bazel/7990_8973 | bazelbuild/bazel | bazelbuild/bazel/7990 | bazelbuild/bazel/8973 | [
"timestamp(timedelta=0.0, similarity=0.9344735508098679)"
] | eab8ae8a33138f26abf25bd736065083d867ca44 | 3a7c1eb7db8ea1e1555b9c72e2997d0249680f65 | [
"Hi Liam, could you pls update this issue to follow https://bazel.build/breaking-changes-guide.html? (e.g. the title of the issue is not right, I could fix that myself but that link is quite nicely written and contains useful advice :).",
"The docs say the title should start with the name of the flag, which is `incompatible_require_java_toolchain_header_compiler_direct`. The [example](https://github.com/bazelbuild/bazel/issues/6611) has a similar title. Did you already update the title, or am I missing something?",
"Oh sorry for the confusion it was me who should read the docs. I thought the format has to be `<flag-name>: Description` (note the colon). Sorry again :/ "
] | [] | "2019-07-24T14:02:33Z" | [
"team-Rules-Java",
"incompatible-change"
] | incompatible_require_java_toolchain_header_compiler_direct | See: https://github.com/bazelbuild/bazel/commit/2ebb0a20b6caee1766820f17bf001350d5463e16. `java_toolchain.header_compiler_direct` should always be set when toolchain resolution is enabled.
No migration is needed for the built-in toolchains, or for custom toolchains using `default_java_toolchain`. | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [
"src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java"
] | [
"src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java",
"src/test/java/com/google/devtools/build/lib/testutil/FoundationTestCase.java"
] | diff --git a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
index b824ea67be7755..85059953a65ab3 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/java/JavaOptions.java
@@ -589,7 +589,7 @@ public ImportDepsCheckingLevelConverter() {
@Option(
name = "incompatible_require_java_toolchain_header_compiler_direct",
- defaultValue = "false",
+ defaultValue = "true",
documentationCategory = OptionDocumentationCategory.UNDOCUMENTED,
effectTags = {OptionEffectTag.UNKNOWN},
metadataTags = {
| diff --git a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
index 2b7c242d7f4729..2b1f235a28d652 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/mock/BazelAnalysisMock.java
@@ -139,6 +139,7 @@ public void setupMockClient(MockToolsConfig config, List<String> workspaceConten
" javac = [':langtools'],",
" javabuilder = ['JavaBuilder_deploy.jar'],",
" header_compiler = ['turbine_deploy.jar'],",
+ " header_compiler_direct = ['TurbineDirect_deploy.jar'],",
" singlejar = ['SingleJar_deploy.jar'],",
" genclass = ['GenClass_deploy.jar'],",
" ijar = ['ijar'],",
@@ -152,6 +153,7 @@ public void setupMockClient(MockToolsConfig config, List<String> workspaceConten
" javac = [':langtools'],",
" javabuilder = ['JavaBuilder_deploy.jar'],",
" header_compiler = ['turbine_deploy.jar'],",
+ " header_compiler_direct = ['TurbineDirect_deploy.jar'],",
" singlejar = ['SingleJar_deploy.jar'],",
" genclass = ['GenClass_deploy.jar'],",
" ijar = ['ijar'],",
@@ -194,7 +196,7 @@ public void setupMockClient(MockToolsConfig config, List<String> workspaceConten
"filegroup(name='JacocoCoverage', srcs = [])",
"exports_files(['JavaBuilder_deploy.jar','SingleJar_deploy.jar','TestRunner_deploy.jar',",
" 'JavaBuilderCanary_deploy.jar', 'ijar', 'GenClass_deploy.jar',",
- " 'turbine_deploy.jar','ExperimentalTestRunner_deploy.jar'])",
+ " 'turbine_deploy.jar', 'TurbineDirect_deploy.jar', 'ExperimentalTestRunner_deploy.jar'])",
"sh_binary(name = 'proguard_whitelister', srcs = ['empty.sh'])",
"toolchain_type(name = 'toolchain_type')",
"toolchain_type(name = 'runtime_toolchain_type')",
diff --git a/src/test/java/com/google/devtools/build/lib/testutil/FoundationTestCase.java b/src/test/java/com/google/devtools/build/lib/testutil/FoundationTestCase.java
index fc12bddba7604b..cbec362dd06682 100644
--- a/src/test/java/com/google/devtools/build/lib/testutil/FoundationTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/testutil/FoundationTestCase.java
@@ -140,6 +140,7 @@ protected void assertContainsEventsInOrder(String... expectedMessages) {
protected void writeBuildFileForJavaToolchain() throws Exception {
scratch.file("java/com/google/test/turbine_canary_deploy.jar");
+ scratch.file("java/com/google/test/turbine_direct_deploy.jar");
scratch.file("java/com/google/test/tzdata.jar");
scratch.overwriteFile(
"java/com/google/test/BUILD",
@@ -157,6 +158,7 @@ protected void writeBuildFileForJavaToolchain() throws Exception {
" javac = [':javac_canary.jar'],",
" javabuilder = [':JavaBuilderCanary_deploy.jar'],",
" header_compiler = [':turbine_canary_deploy.jar'],",
+ " header_compiler_direct = [':turbine_direct_deploy.jar'],",
" singlejar = ['SingleJar_deploy.jar'],",
" ijar = ['ijar'],",
" genclass = ['GenClass_deploy.jar'],",
| train | train | 2019-08-09T11:34:41 | "2019-04-10T06:07:57Z" | cushon | test |
Subsets and Splits