Remove need for exported_by or linked_statically_by

For now we will restrict allowed exports to the same package. At the same time
static_deps should be used to take into account what should be linked into a
shared library.

RELNOTES:none
PiperOrigin-RevId: 294668451
Change-Id: Ia087519106983bfa9a980e471d3102ab391a53eb
diff --git a/WORKSPACE b/WORKSPACE
index 709fbe7..0a83b0a 100644
--- a/WORKSPACE
+++ b/WORKSPACE
@@ -56,4 +56,10 @@
 rules_proto_toolchains()
 
 load("//cc:repositories.bzl", "rules_cc_toolchains")
+
 rules_cc_toolchains()
+
+local_repository(
+    name = "test_repo",
+    path = "examples/test_cc_shared_library2",
+)
diff --git a/cc/private/toolchain/BUILD b/cc/private/toolchain/BUILD
index f267fc0..70280af 100644
--- a/cc/private/toolchain/BUILD
+++ b/cc/private/toolchain/BUILD
@@ -1,3 +1,5 @@
+load("//cc:defs.bzl", "cc_flags_supplier", "cc_library", "compiler_flag")
+
 # Copyright 2018 The Bazel Authors. All rights reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,8 +18,6 @@
 
 licenses(["notice"])  # Apache 2.0
 
-load("//cc:defs.bzl", "cc_flags_supplier", "cc_library", "compiler_flag")
-
 # It is frequently necessary to constrain platforms based on the cc compiler type.
 constraint_setting(name = "cc_compiler")
 
@@ -80,7 +80,7 @@
 
 filegroup(
     name = "srcs",
-    srcs = glob(["**"])
+    srcs = glob(["**"]),
 )
 
 filegroup(
diff --git a/examples/experimental_cc_shared_library.bzl b/examples/experimental_cc_shared_library.bzl
index 80d4adc..4b41fd7 100644
--- a/examples/experimental_cc_shared_library.bzl
+++ b/examples/experimental_cc_shared_library.bzl
@@ -26,12 +26,12 @@
 CcSharedLibraryInfo = provider(
     fields = {
         "dynamic_deps": "All shared libraries depended on transitively",
+        "exports": "cc_libraries that are linked statically and exported",
         "linker_input": "the resulting linker input artifact for the shared library",
         "preloaded_deps": "cc_libraries needed by this cc_shared_library that should" +
                           " be linked the binary. If this is set, this cc_shared_library has to " +
                           " be a direct dependency of the cc_binary",
         "static_libs": "All libraries linked statically into this library",
-        "exports": "cc_libraries that are linked statically and exported",
     },
 )
 
@@ -50,10 +50,11 @@
             break
         node = all_children.pop(0)
 
-        if node.label in can_be_linked_dynamically:
-            link_dynamically_labels[node.label] = None
-        elif node.label not in preloaded_deps_direct_labels:
-            link_statically_labels[node.label] = node.linked_statically_by
+        node_label = str(node.label)
+        if node_label in can_be_linked_dynamically:
+            link_dynamically_labels[node_label] = None
+        elif node_label not in preloaded_deps_direct_labels:
+            link_statically_labels[node_label] = node.linked_statically_by
             all_children.extend(node.children)
     return (link_statically_labels, link_dynamically_labels)
 
@@ -137,6 +138,22 @@
         additional_inputs = depset(direct = linker_input.additional_inputs),
     )
 
+def _check_if_target_under_path(path, target, target_specified):
+    if not _same_package_or_above(path, target):
+        return False
+    if target_specified:
+        return path.name == target.name
+    return True
+
+def _is_target_specified(path):
+    if path.startswith("//") or path.startswith("@"):
+        if path.find(":") != -1:
+            return True
+        else:
+            return False
+    else:
+        return True
+
 def _filter_inputs(
         ctx,
         feature_configuration,
@@ -203,10 +220,12 @@
 
                 if not can_be_linked_statically:
                     for static_dep_path in ctx.attr.static_deps:
-                        if owner.startswith(static_dep_path):
+                        target_specified = _is_target_specified(static_dep_path)
+                        static_dep_path_label = ctx.label.relative(static_dep_path)
+                        owner_label = linker_input.owner
+                        if _check_if_target_under_path(linker_input.owner, static_dep_path_label, target_specified):
                             can_be_linked_statically = True
                             break
-
                 if can_be_linked_statically:
                     static_linker_inputs.append(linker_input)
                 else:
@@ -228,6 +247,18 @@
 
     return (static_linker_inputs, dynamic_linker_inputs)
 
+def _same_package_or_above(label_a, label_b):
+    if label_a.workspace_name != label_b.workspace_name:
+        return False
+    package_a_tokenized = label_a.package.split("/")
+    package_b_tokenized = label_b.package.split("/")
+    if len(package_b_tokenized) < len(package_a_tokenized):
+        return False
+    for i in range(len(package_a_tokenized)):
+        if package_a_tokenized[i] != package_b_tokenized[i]:
+            return False
+    return True
+
 def _cc_shared_library_impl(ctx):
     cc_toolchain = find_cc_toolchain(ctx)
     feature_configuration = cc_common.configure_features(
@@ -244,6 +275,11 @@
             fail("Trying to export a library already exported by a different shared library: " +
                  str(export.label))
 
+        if not _same_package_or_above(ctx.label, export[GraphNodeInfo].label):
+            fail(str(export.label) + " cannot be exported from " + str(ctx.label) +
+                 " because " + str(export.label) + " is not in the same package " +
+                 " or a sub-package")
+
     preloaded_deps_direct_labels = {}
     preloaded_dep_merged_cc_info = None
     if len(ctx.attr.preloaded_deps) != 0:
@@ -333,7 +369,7 @@
         linked_statically_by = [str(label) for label in ctx.rule.attr.linked_statically_by]
 
     return [GraphNodeInfo(
-        label = str(ctx.label),
+        label = ctx.label,
         linked_statically_by = linked_statically_by,
         children = children,
     )]
@@ -347,6 +383,7 @@
     implementation = _cc_shared_library_impl,
     attrs = {
         "dynamic_deps": attr.label_list(providers = [CcSharedLibraryInfo]),
+        "exports": attr.label_list(providers = [CcInfo], aspects = [graph_structure_aspect]),
         "preloaded_deps": attr.label_list(providers = [CcInfo]),
         # TODO(plf): Replaces linked_statically_by attribute. Instead of
         # linked_statically_by attribute in each cc_library we will have the
@@ -354,7 +391,6 @@
         "static_deps": attr.string_list(),
         "user_link_flags": attr.string_list(),
         "visibility_file": attr.label(allow_single_file = True),
-        "exports": attr.label_list(providers = [CcInfo], aspects = [graph_structure_aspect]),
         "_cc_toolchain": attr.label(default = "@bazel_tools//tools/cpp:current_cc_toolchain"),
     },
     toolchains = ["@rules_cc//cc:toolchain_type"],  # copybara-use-repo-external-label
diff --git a/examples/my_c_archive/my_c_archive.bzl b/examples/my_c_archive/my_c_archive.bzl
index bde0e5e..9c1c38b 100644
--- a/examples/my_c_archive/my_c_archive.bzl
+++ b/examples/my_c_archive/my_c_archive.bzl
@@ -85,8 +85,8 @@
 my_c_archive = rule(
     implementation = _my_c_archive_impl,
     attrs = {
-        "object": attr.label(mandatory = True, providers = [MyCCompileInfo]),
         "deps": attr.label_list(providers = [CcInfo]),
+        "object": attr.label(mandatory = True, providers = [MyCCompileInfo]),
         "_cc_toolchain": attr.label(default = Label("@bazel_tools//tools/cpp:current_cc_toolchain")),
     },
     fragments = ["cpp"],
diff --git a/examples/my_c_compile/BUILD b/examples/my_c_compile/BUILD
index f970895..efcabf4 100644
--- a/examples/my_c_compile/BUILD
+++ b/examples/my_c_compile/BUILD
@@ -1,3 +1,5 @@
+load("//examples/my_c_compile:my_c_compile.bzl", "my_c_compile")
+
 # Copyright 2019 The Bazel Authors. All rights reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,8 +17,6 @@
 # Example showing how to create a custom Starlark rule that just compiles C sources
 licenses(["notice"])
 
-load("//examples/my_c_compile:my_c_compile.bzl", "my_c_compile")
-
 my_c_compile(
     name = "foo",
     src = "foo.c",
diff --git a/examples/test_cc_shared_library/BUILD b/examples/test_cc_shared_library/BUILD
index 199fb7e..93090c4 100644
--- a/examples/test_cc_shared_library/BUILD
+++ b/examples/test_cc_shared_library/BUILD
@@ -77,6 +77,10 @@
 
 cc_shared_library(
     name = "bar_so",
+    static_deps = [
+        "//examples/test_cc_shared_library:barX",
+        "@test_repo//:bar",
+    ],
     visibility_file = "bar.lds",
     exports = [
         "bar",
@@ -85,9 +89,21 @@
 )
 
 cc_library(
+    name = "barX",
+    srcs = ["bar.cc"],
+    hdrs = ["bar.h"],
+    deps = [
+        "@test_repo//:bar",
+    ],
+)
+
+cc_library(
     name = "bar",
     srcs = ["bar.cc"],
     hdrs = ["bar.h"],
+    deps = [
+        "barX",
+    ],
 )
 
 cc_library(
diff --git a/examples/test_cc_shared_library2/BUILD b/examples/test_cc_shared_library2/BUILD
new file mode 100644
index 0000000..802d60f
--- /dev/null
+++ b/examples/test_cc_shared_library2/BUILD
@@ -0,0 +1,8 @@
+load("@rules_cc//cc:defs.bzl", "cc_library")
+
+cc_library(
+    name = "bar",
+    srcs = ["bar.cc"],
+    hdrs = ["bar.h"],
+    visibility = ["//visibility:public"],
+)
diff --git a/examples/test_cc_shared_library2/WORKSPACE b/examples/test_cc_shared_library2/WORKSPACE
new file mode 100644
index 0000000..838ce12
--- /dev/null
+++ b/examples/test_cc_shared_library2/WORKSPACE
@@ -0,0 +1 @@
+workspace(name = "test_repo")
diff --git a/examples/test_cc_shared_library2/bar.cc b/examples/test_cc_shared_library2/bar.cc
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/examples/test_cc_shared_library2/bar.cc
diff --git a/examples/test_cc_shared_library2/bar.h b/examples/test_cc_shared_library2/bar.h
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/examples/test_cc_shared_library2/bar.h
diff --git a/examples/write_cc_toolchain_cpu/BUILD b/examples/write_cc_toolchain_cpu/BUILD
index 07caa50..fcee153 100644
--- a/examples/write_cc_toolchain_cpu/BUILD
+++ b/examples/write_cc_toolchain_cpu/BUILD
@@ -1,3 +1,5 @@
+load("//examples/write_cc_toolchain_cpu:write_cc_toolchain_cpu.bzl", "write_cc_toolchain_cpu")
+
 # Copyright 2019 The Bazel Authors. All rights reserved.
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,6 +17,4 @@
 # Example showing how to get CcToolchainInfo in a custom starlark rule
 licenses(["notice"])
 
-load("//examples/write_cc_toolchain_cpu:write_cc_toolchain_cpu.bzl", "write_cc_toolchain_cpu")
-
 write_cc_toolchain_cpu(name = "write_me_the_cpu")
diff --git a/third_party/com/github/bazelbuild/bazel/src/main/protobuf/BUILD b/third_party/com/github/bazelbuild/bazel/src/main/protobuf/BUILD
index 77f3a7a..c08e13b 100644
--- a/third_party/com/github/bazelbuild/bazel/src/main/protobuf/BUILD
+++ b/third_party/com/github/bazelbuild/bazel/src/main/protobuf/BUILD
@@ -1,9 +1,9 @@
-licenses(["notice"])  # Apache 2.0
-
 load("@com_google_protobuf//:protobuf.bzl", "py_proto_library")
 load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
 load("@rules_proto//proto:defs.bzl", "proto_library")
 
+licenses(["notice"])  # Apache 2.0
+
 py_proto_library(
     name = "crosstool_config_py_pb2",
     srcs = ["crosstool_config.proto"],