blob: e69f3e26aaf309994ffc0113d804d27b1084733c [file] [log] [blame]
Bob Badoura99ac622021-10-25 16:21:00 -07001// Copyright 2021 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package compliance
16
17import (
18 "fmt"
19 "sort"
20 "strings"
21 "sync"
22)
23
24// LicenseGraph describes the immutable license metadata for a set of root
25// targets and the transitive closure of their dependencies.
26//
27// Alternatively, a graph is a set of edges. In this case directed, annotated
28// edges from targets to dependencies.
29//
30// A LicenseGraph provides the frame of reference for all of the other types
31// defined here. It is possible to have multiple graphs, and to have targets,
32// edges, and resolutions from multiple graphs. But it is an error to try to
33// mix items from different graphs in the same operation.
34// May panic if attempted.
35//
36// The compliance package assumes specific private implementations of each of
37// these interfaces. May panic if attempts are made to combine different
38// implementations of some interfaces with expected implementations of other
39// interfaces here.
40type LicenseGraph struct {
41 // rootFiles identifies the original set of files to read. (immutable)
42 //
43 // Defines the starting "top" for top-down walks.
44 //
45 // Alternatively, an instance of licenseGraphImp conceptually defines a scope within
46 // the universe of build graphs as a sub-graph rooted at rootFiles where all edges
47 // and targets for the instance are defined relative to and within that scope. For
48 // most analyses, the correct scope is to root the graph at all of the distributed
49 // artifacts.
50 rootFiles []string
51
52 // edges lists the directed edges in the graph from target to dependency. (guarded by mu)
53 //
54 // Alternatively, the graph is the set of `edges`.
Bob Badour103eb0f2022-01-10 13:50:57 -080055 edges TargetEdgeList
Bob Badoura99ac622021-10-25 16:21:00 -070056
Bob Badour103eb0f2022-01-10 13:50:57 -080057 // targets identifies, indexes, and describes the entire set of target node files.
Bob Badoura99ac622021-10-25 16:21:00 -070058 /// (guarded by mu)
59 targets map[string]*TargetNode
60
Bob Badour103eb0f2022-01-10 13:50:57 -080061 // wgBU becomes non-nil when the bottom-up resolve begins and reaches 0
62 // (i.e. Wait() proceeds) when the bottom-up resolve completes. (guarded by mu)
63 wgBU *sync.WaitGroup
Bob Badoura99ac622021-10-25 16:21:00 -070064
Bob Badour103eb0f2022-01-10 13:50:57 -080065 // wgTD becomes non-nil when the top-down resolve begins and reaches 0 (i.e. Wait()
66 // proceeds) when the top-down resolve completes. (guarded by mu)
67 wgTD *sync.WaitGroup
Bob Badoura99ac622021-10-25 16:21:00 -070068
69 // shippedNodes caches the results of a full walk of nodes identifying targets
70 // distributed either directly or as derivative works. (creation guarded by mu)
71 shippedNodes *TargetNodeSet
72
73 // mu guards against concurrent update.
74 mu sync.Mutex
75}
76
Bob Badoura99ac622021-10-25 16:21:00 -070077// Edges returns the list of edges in the graph. (unordered)
78func (lg *LicenseGraph) Edges() TargetEdgeList {
79 edges := make(TargetEdgeList, 0, len(lg.edges))
Bob Badour103eb0f2022-01-10 13:50:57 -080080 edges = append(edges, lg.edges...)
Bob Badoura99ac622021-10-25 16:21:00 -070081 return edges
82}
83
84// Targets returns the list of target nodes in the graph. (unordered)
85func (lg *LicenseGraph) Targets() TargetNodeList {
86 targets := make(TargetNodeList, 0, len(lg.targets))
Bob Badour103eb0f2022-01-10 13:50:57 -080087 for _, target := range lg.targets {
88 targets = append(targets, target)
Bob Badoura99ac622021-10-25 16:21:00 -070089 }
90 return targets
91}
92
93// compliance-only LicenseGraph methods
94
95// newLicenseGraph constructs a new, empty instance of LicenseGraph.
96func newLicenseGraph() *LicenseGraph {
97 return &LicenseGraph{
98 rootFiles: []string{},
Bob Badoura99ac622021-10-25 16:21:00 -070099 targets: make(map[string]*TargetNode),
100 }
101}
102
Bob Badoura99ac622021-10-25 16:21:00 -0700103// TargetEdge describes a directed, annotated edge from a target to a
104// dependency. (immutable)
105//
106// A LicenseGraph, above, is a set of TargetEdges.
107//
108// i.e. `Target` depends on `Dependency` in the manner described by
109// `Annotations`.
110type TargetEdge struct {
Bob Badour103eb0f2022-01-10 13:50:57 -0800111 // target and dependency identify the nodes connected by the edge.
112 target, dependency *TargetNode
Bob Badoura99ac622021-10-25 16:21:00 -0700113
Bob Badour103eb0f2022-01-10 13:50:57 -0800114 // annotations identifies the set of compliance-relevant annotations describing the edge.
115 annotations TargetEdgeAnnotations
Bob Badoura99ac622021-10-25 16:21:00 -0700116}
117
118// Target identifies the target that depends on the dependency.
119//
120// Target needs Dependency to build.
Bob Badour103eb0f2022-01-10 13:50:57 -0800121func (e *TargetEdge) Target() *TargetNode {
122 return e.target
Bob Badoura99ac622021-10-25 16:21:00 -0700123}
124
125// Dependency identifies the target depended on by the target.
126//
127// Dependency builds without Target, but Target needs Dependency to build.
Bob Badour103eb0f2022-01-10 13:50:57 -0800128func (e *TargetEdge) Dependency() *TargetNode {
129 return e.dependency
Bob Badoura99ac622021-10-25 16:21:00 -0700130}
131
132// Annotations describes the type of edge by the set of annotations attached to
133// it.
134//
135// Only annotations prescribed by policy have any meaning for licensing, and
136// the meaning for licensing is likewise prescribed by policy. Other annotations
137// are preserved and ignored by policy.
Bob Badour103eb0f2022-01-10 13:50:57 -0800138func (e *TargetEdge) Annotations() TargetEdgeAnnotations {
139 return e.annotations
140}
141
142// String returns a human-readable string representation of the edge.
143func (e *TargetEdge) String() string {
144 return fmt.Sprintf("%s -[%s]> %s", e.target.name, strings.Join(e.annotations.AsList(), ", "), e.dependency.name)
Bob Badoura99ac622021-10-25 16:21:00 -0700145}
146
147// TargetEdgeList orders lists of edges by target then dependency then annotations.
Bob Badour103eb0f2022-01-10 13:50:57 -0800148type TargetEdgeList []*TargetEdge
Bob Badoura99ac622021-10-25 16:21:00 -0700149
150// Len returns the count of the elmements in the list.
Colin Cross35f79c32022-01-27 15:18:52 -0800151func (l TargetEdgeList) Len() int { return len(l) }
Bob Badoura99ac622021-10-25 16:21:00 -0700152
153// Swap rearranges 2 elements so that each occupies the other's former position.
154func (l TargetEdgeList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
155
156// Less returns true when the `i`th element is lexicographically less than the `j`th.
157func (l TargetEdgeList) Less(i, j int) bool {
Bob Badour103eb0f2022-01-10 13:50:57 -0800158 namei := l[i].target.name
159 namej := l[j].target.name
160 if namei == namej {
161 namei = l[i].dependency.name
162 namej = l[j].dependency.name
Bob Badoura99ac622021-10-25 16:21:00 -0700163 }
Bob Badour103eb0f2022-01-10 13:50:57 -0800164 if namei == namej {
165 return l[i].annotations.Compare(l[j].annotations) < 0
166 }
167 return namei < namej
168}
169
170// TargetEdgePathSegment describes a single arc in a TargetPath associating the
171// edge with a context `ctx` defined by whatever process is creating the path.
172type TargetEdgePathSegment struct {
173 edge *TargetEdge
Colin Cross35f79c32022-01-27 15:18:52 -0800174 ctx interface{}
Bob Badour103eb0f2022-01-10 13:50:57 -0800175}
176
177// Target identifies the target that depends on the dependency.
178//
179// Target needs Dependency to build.
180func (s TargetEdgePathSegment) Target() *TargetNode {
181 return s.edge.target
182}
183
184// Dependency identifies the target depended on by the target.
185//
186// Dependency builds without Target, but Target needs Dependency to build.
187func (s TargetEdgePathSegment) Dependency() *TargetNode {
188 return s.edge.dependency
189}
190
191// Annotations describes the type of edge by the set of annotations attached to
192// it.
193//
194// Only annotations prescribed by policy have any meaning for licensing, and
195// the meaning for licensing is likewise prescribed by policy. Other annotations
196// are preserved and ignored by policy.
197func (s TargetEdgePathSegment) Annotations() TargetEdgeAnnotations {
198 return s.edge.annotations
199}
200
201// Context returns the context associated with the path segment. The type and
202// value of the context defined by the process creating the path.
203func (s TargetEdgePathSegment) Context() interface{} {
204 return s.ctx
205}
206
207// String returns a human-readable string representation of the edge.
208func (s TargetEdgePathSegment) String() string {
209 return fmt.Sprintf("%s -[%s]> %s", s.edge.target.name, strings.Join(s.edge.annotations.AsList(), ", "), s.edge.dependency.name)
Bob Badoura99ac622021-10-25 16:21:00 -0700210}
211
212// TargetEdgePath describes a sequence of edges starting at a root and ending
213// at some final dependency.
Bob Badour103eb0f2022-01-10 13:50:57 -0800214type TargetEdgePath []TargetEdgePathSegment
Bob Badoura99ac622021-10-25 16:21:00 -0700215
216// NewTargetEdgePath creates a new, empty path with capacity `cap`.
217func NewTargetEdgePath(cap int) *TargetEdgePath {
218 p := make(TargetEdgePath, 0, cap)
219 return &p
220}
221
222// Push appends a new edge to the list verifying that the target of the new
223// edge is the dependency of the prior.
Bob Badour103eb0f2022-01-10 13:50:57 -0800224func (p *TargetEdgePath) Push(edge *TargetEdge, ctx interface{}) {
Bob Badoura99ac622021-10-25 16:21:00 -0700225 if len(*p) == 0 {
Bob Badour103eb0f2022-01-10 13:50:57 -0800226 *p = append(*p, TargetEdgePathSegment{edge, ctx})
Bob Badoura99ac622021-10-25 16:21:00 -0700227 return
228 }
Bob Badour103eb0f2022-01-10 13:50:57 -0800229 if (*p)[len(*p)-1].edge.dependency != edge.target {
230 panic(fmt.Errorf("disjoint path %s does not end at %s", p.String(), edge.target.name))
Bob Badoura99ac622021-10-25 16:21:00 -0700231 }
Bob Badour103eb0f2022-01-10 13:50:57 -0800232 *p = append(*p, TargetEdgePathSegment{edge, ctx})
Bob Badoura99ac622021-10-25 16:21:00 -0700233}
234
235// Pop shortens the path by 1 edge.
236func (p *TargetEdgePath) Pop() {
237 if len(*p) == 0 {
238 panic(fmt.Errorf("attempt to remove edge from empty path"))
239 }
240 *p = (*p)[:len(*p)-1]
241}
242
243// Clear makes the path length 0.
244func (p *TargetEdgePath) Clear() {
245 *p = (*p)[:0]
246}
247
Bob Badoure6fdd142021-12-09 22:10:43 -0800248// Copy makes a new path with the same value.
249func (p *TargetEdgePath) Copy() *TargetEdgePath {
250 result := make(TargetEdgePath, 0, len(*p))
251 for _, e := range *p {
252 result = append(result, e)
253 }
254 return &result
255}
256
Bob Badoura99ac622021-10-25 16:21:00 -0700257// String returns a string representation of the path: [n1 -> n2 -> ... -> nn].
258func (p *TargetEdgePath) String() string {
259 if p == nil {
260 return "nil"
261 }
262 if len(*p) == 0 {
263 return "[]"
264 }
265 var sb strings.Builder
266 fmt.Fprintf(&sb, "[")
Bob Badour103eb0f2022-01-10 13:50:57 -0800267 for _, s := range *p {
268 fmt.Fprintf(&sb, "%s -> ", s.edge.target.name)
Bob Badoura99ac622021-10-25 16:21:00 -0700269 }
Bob Badour103eb0f2022-01-10 13:50:57 -0800270 lastSegment := (*p)[len(*p)-1]
271 fmt.Fprintf(&sb, "%s]", lastSegment.edge.dependency.name)
Bob Badoura99ac622021-10-25 16:21:00 -0700272 return sb.String()
273}
274
275// TargetNode describes a module or target identified by the name of a specific
276// metadata file. (immutable)
277//
278// Each metadata file corresponds to a Soong module or to a Make target.
279//
280// A target node can appear as the target or as the dependency in edges.
281// Most target nodes appear as both target in one edge and as dependency in
282// other edges.
283type TargetNode targetNode
284
285// Name returns the string that identifies the target node.
286// i.e. path to license metadata file
287func (tn *TargetNode) Name() string {
288 return tn.name
289}
290
Bob Badour103eb0f2022-01-10 13:50:57 -0800291// Dependencies returns the list of edges to dependencies of `tn`.
292func (tn *TargetNode) Dependencies() TargetEdgeList {
293 edges := make(TargetEdgeList, 0, len(tn.edges))
294 edges = append(edges, tn.edges...)
295 return edges
296}
297
Bob Badoura99ac622021-10-25 16:21:00 -0700298// PackageName returns the string that identifes the package for the target.
299func (tn *TargetNode) PackageName() string {
300 return tn.proto.GetPackageName()
301}
302
Bob Badoura99ac622021-10-25 16:21:00 -0700303// Projects returns the projects defining the target node. (unordered)
304//
305// In an ideal world, only 1 project defines a target, but the interaction
306// between Soong and Make for a variety of architectures and for host versus
307// product means a module is sometimes defined more than once.
308func (tn *TargetNode) Projects() []string {
309 return append([]string{}, tn.proto.Projects...)
310}
311
Bob Badoura99ac622021-10-25 16:21:00 -0700312// LicenseConditions returns a copy of the set of license conditions
313// originating at the target. The values that appear and how each is resolved
314// is a matter of policy. (unordered)
315//
316// e.g. notice or proprietary
Bob Badour103eb0f2022-01-10 13:50:57 -0800317func (tn *TargetNode) LicenseConditions() LicenseConditionSet {
318 return tn.licenseConditions
Bob Badoura99ac622021-10-25 16:21:00 -0700319}
320
321// LicenseTexts returns the paths to the files containing the license texts for
322// the target. (unordered)
323func (tn *TargetNode) LicenseTexts() []string {
324 return append([]string{}, tn.proto.LicenseTexts...)
325}
326
327// IsContainer returns true if the target represents a container that merely
328// aggregates other targets.
329func (tn *TargetNode) IsContainer() bool {
330 return tn.proto.GetIsContainer()
331}
332
333// Built returns the list of files built by the module or target. (unordered)
334func (tn *TargetNode) Built() []string {
335 return append([]string{}, tn.proto.Built...)
336}
337
338// Installed returns the list of files installed by the module or target.
339// (unordered)
340func (tn *TargetNode) Installed() []string {
341 return append([]string{}, tn.proto.Installed...)
342}
343
Bob Badoure6fdd142021-12-09 22:10:43 -0800344// TargetFiles returns the list of files built or installed by the module or
345// target. (unordered)
346func (tn *TargetNode) TargetFiles() []string {
347 return append(tn.proto.Built, tn.proto.Installed...)
348}
349
Bob Badoura99ac622021-10-25 16:21:00 -0700350// InstallMap returns the list of path name transformations to make to move
351// files from their original location in the file system to their destination
352// inside a container. (unordered)
353func (tn *TargetNode) InstallMap() []InstallMap {
354 result := make([]InstallMap, 0, len(tn.proto.InstallMap))
355 for _, im := range tn.proto.InstallMap {
356 result = append(result, InstallMap{im.GetFromPath(), im.GetContainerPath()})
357 }
358 return result
359}
360
361// Sources returns the list of file names depended on by the target, which may
362// be a proper subset of those made available by dependency modules.
363// (unordered)
364func (tn *TargetNode) Sources() []string {
365 return append([]string{}, tn.proto.Sources...)
366}
367
368// InstallMap describes the mapping from an input filesystem file to file in a
369// container.
370type InstallMap struct {
371 // FromPath is the input path on the filesystem.
372 FromPath string
373
374 // ContainerPath is the path to the same file inside the container or
375 // installed location.
376 ContainerPath string
377}
378
379// TargetEdgeAnnotations describes an immutable set of annotations attached to
380// an edge from a target to a dependency.
381//
382// Annotations typically distinguish between static linkage versus dynamic
383// versus tools that are used at build time but are not linked in any way.
384type TargetEdgeAnnotations struct {
Bob Badour5446a6f2022-01-10 18:44:59 -0800385 annotations map[string]struct{}
Bob Badoura99ac622021-10-25 16:21:00 -0700386}
387
388// newEdgeAnnotations creates a new instance of TargetEdgeAnnotations.
389func newEdgeAnnotations() TargetEdgeAnnotations {
Bob Badour5446a6f2022-01-10 18:44:59 -0800390 return TargetEdgeAnnotations{make(map[string]struct{})}
Bob Badoura99ac622021-10-25 16:21:00 -0700391}
392
393// HasAnnotation returns true if an annotation `ann` is in the set.
394func (ea TargetEdgeAnnotations) HasAnnotation(ann string) bool {
395 _, ok := ea.annotations[ann]
396 return ok
397}
398
399// Compare orders TargetAnnotations returning:
400// -1 when ea < other,
401// +1 when ea > other, and
402// 0 when ea == other.
403func (ea TargetEdgeAnnotations) Compare(other TargetEdgeAnnotations) int {
404 a1 := ea.AsList()
405 a2 := other.AsList()
406 sort.Strings(a1)
407 sort.Strings(a2)
408 for k := 0; k < len(a1) && k < len(a2); k++ {
409 if a1[k] < a2[k] {
410 return -1
411 }
412 if a1[k] > a2[k] {
413 return 1
414 }
415 }
416 if len(a1) < len(a2) {
417 return -1
418 }
419 if len(a1) > len(a2) {
420 return 1
421 }
422 return 0
423}
424
425// AsList returns the list of annotation names attached to the edge.
426// (unordered)
427func (ea TargetEdgeAnnotations) AsList() []string {
428 l := make([]string, 0, len(ea.annotations))
429 for ann := range ea.annotations {
430 l = append(l, ann)
431 }
432 return l
433}
434
435// TargetNodeSet describes a set of distinct nodes in a license graph.
436type TargetNodeSet struct {
Bob Badour5446a6f2022-01-10 18:44:59 -0800437 nodes map[*TargetNode]struct{}
Bob Badoura99ac622021-10-25 16:21:00 -0700438}
439
440// Contains returns true when `target` is an element of the set.
441func (ts *TargetNodeSet) Contains(target *TargetNode) bool {
442 _, isPresent := ts.nodes[target]
443 return isPresent
444}
445
446// AsList returns the list of target nodes in the set. (unordered)
447func (ts *TargetNodeSet) AsList() TargetNodeList {
448 result := make(TargetNodeList, 0, len(ts.nodes))
449 for tn := range ts.nodes {
450 result = append(result, tn)
451 }
452 return result
453}
454
455// Names returns the array of target node namess in the set. (unordered)
456func (ts *TargetNodeSet) Names() []string {
457 result := make([]string, 0, len(ts.nodes))
458 for tn := range ts.nodes {
459 result = append(result, tn.name)
460 }
461 return result
462}
463
Bob Badour103eb0f2022-01-10 13:50:57 -0800464// String returns a human-readable string representation of the set.
465func (ts *TargetNodeSet) String() string {
466 return fmt.Sprintf("{%s}", strings.Join(ts.Names(), ", "))
467}
468
Bob Badoura99ac622021-10-25 16:21:00 -0700469// TargetNodeList orders a list of targets by name.
470type TargetNodeList []*TargetNode
471
472// Len returns the count of elements in the list.
Colin Cross35f79c32022-01-27 15:18:52 -0800473func (l TargetNodeList) Len() int { return len(l) }
Bob Badoura99ac622021-10-25 16:21:00 -0700474
475// Swap rearranges 2 elements so that each occupies the other's former position.
476func (l TargetNodeList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
477
478// Less returns true when the `i`th element is lexicographicallt less than the `j`th.
479func (l TargetNodeList) Less(i, j int) bool {
480 return l[i].name < l[j].name
481}
482
483// String returns a string representation of the list.
484func (l TargetNodeList) String() string {
485 var sb strings.Builder
486 fmt.Fprintf(&sb, "[")
487 sep := ""
488 for _, tn := range l {
489 fmt.Fprintf(&sb, "%s%s", sep, tn.name)
490 sep = " "
491 }
492 fmt.Fprintf(&sb, "]")
493 return sb.String()
494}
495
496// Names returns an array the names of the nodes in the same order as the nodes in the list.
497func (l TargetNodeList) Names() []string {
498 result := make([]string, 0, len(l))
499 for _, tn := range l {
500 result = append(result, tn.name)
501 }
502 return result
503}