1// 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 rbcrun 16 17import ( 18 "fmt" 19 "io/fs" 20 "os" 21 "os/exec" 22 "path/filepath" 23 "sort" 24 "strings" 25 26 "go.starlark.net/starlark" 27 "go.starlark.net/starlarkstruct" 28) 29 30type ExecutionMode int 31const ( 32 ExecutionModeRbc ExecutionMode = iota 33 ExecutionModeScl ExecutionMode = iota 34) 35 36const allowExternalEntrypointKey = "allowExternalEntrypoint" 37const callingFileKey = "callingFile" 38const executionModeKey = "executionMode" 39const shellKey = "shell" 40 41type modentry struct { 42 globals starlark.StringDict 43 err error 44} 45 46var moduleCache = make(map[string]*modentry) 47 48var rbcBuiltins starlark.StringDict = starlark.StringDict{ 49 "struct": starlark.NewBuiltin("struct", starlarkstruct.Make), 50 // To convert find-copy-subdir and product-copy-files-by pattern 51 "rblf_find_files": starlark.NewBuiltin("rblf_find_files", find), 52 // To convert makefile's $(shell cmd) 53 "rblf_shell": starlark.NewBuiltin("rblf_shell", shell), 54 // Output to stderr 55 "rblf_log": starlark.NewBuiltin("rblf_log", log), 56 // To convert makefile's $(wildcard foo*) 57 "rblf_wildcard": starlark.NewBuiltin("rblf_wildcard", wildcard), 58} 59 60var sclBuiltins starlark.StringDict = starlark.StringDict{ 61 "struct": starlark.NewBuiltin("struct", starlarkstruct.Make), 62} 63 64func isSymlink(filepath string) (bool, error) { 65 if info, err := os.Lstat(filepath); err == nil { 66 return info.Mode() & os.ModeSymlink != 0, nil 67 } else { 68 return false, err 69 } 70} 71 72// Takes a module name (the first argument to the load() function) and returns the path 73// it's trying to load, stripping out leading //, and handling leading :s. 74func cleanModuleName(moduleName string, callerDir string, allowExternalPaths bool) (string, error) { 75 if strings.Count(moduleName, ":") > 1 { 76 return "", fmt.Errorf("at most 1 colon must be present in starlark path: %s", moduleName) 77 } 78 79 // We don't have full support for external repositories, but at least support skylib's dicts. 80 if moduleName == "@bazel_skylib//lib:dicts.bzl" { 81 return "external/bazel-skylib/lib/dicts.bzl", nil 82 } 83 84 localLoad := false 85 if strings.HasPrefix(moduleName, "@//") { 86 moduleName = moduleName[3:] 87 } else if strings.HasPrefix(moduleName, "//") { 88 moduleName = moduleName[2:] 89 } else if strings.HasPrefix(moduleName, ":") { 90 moduleName = moduleName[1:] 91 localLoad = true 92 } else if !allowExternalPaths { 93 return "", fmt.Errorf("load path must start with // or :") 94 } 95 96 if ix := strings.LastIndex(moduleName, ":"); ix >= 0 { 97 moduleName = moduleName[:ix] + string(os.PathSeparator) + moduleName[ix+1:] 98 } 99 100 if filepath.Clean(moduleName) != moduleName { 101 return "", fmt.Errorf("load path must be clean, found: %s, expected: %s", moduleName, filepath.Clean(moduleName)) 102 } 103 if !allowExternalPaths { 104 if strings.HasPrefix(moduleName, "../") { 105 return "", fmt.Errorf("load path must not start with ../: %s", moduleName) 106 } 107 if strings.HasPrefix(moduleName, "/") { 108 return "", fmt.Errorf("load path starts with /, use // for a absolute path: %s", moduleName) 109 } 110 } 111 112 if localLoad { 113 return filepath.Join(callerDir, moduleName), nil 114 } 115 116 return moduleName, nil 117} 118 119// loader implements load statement. The format of the loaded module URI is 120// [//path]:base[|symbol] 121// The file path is $ROOT/path/base if path is present, <caller_dir>/base otherwise. 122// The presence of `|symbol` indicates that the loader should return a single 'symbol' 123// bound to None if file is missing. 124func loader(thread *starlark.Thread, module string) (starlark.StringDict, error) { 125 mode := thread.Local(executionModeKey).(ExecutionMode) 126 allowExternalEntrypoint := thread.Local(allowExternalEntrypointKey).(bool) 127 var defaultSymbol string 128 mustLoad := true 129 if mode == ExecutionModeRbc { 130 pipePos := strings.LastIndex(module, "|") 131 if pipePos >= 0 { 132 mustLoad = false 133 defaultSymbol = module[pipePos+1:] 134 module = module[:pipePos] 135 } 136 } 137 callingFile := thread.Local(callingFileKey).(string) 138 modulePath, err := cleanModuleName(module, filepath.Dir(callingFile), allowExternalEntrypoint) 139 if err != nil { 140 return nil, err 141 } 142 e, ok := moduleCache[modulePath] 143 if e == nil { 144 if ok { 145 return nil, fmt.Errorf("cycle in load graph") 146 } 147 148 // Add a placeholder to indicate "load in progress". 149 moduleCache[modulePath] = nil 150 151 // Decide if we should load. 152 if !mustLoad { 153 if _, err := os.Stat(modulePath); err == nil { 154 mustLoad = true 155 } 156 } 157 158 // Load or return default 159 if mustLoad { 160 if strings.HasSuffix(callingFile, ".scl") && !strings.HasSuffix(modulePath, ".scl") { 161 return nil, fmt.Errorf(".scl files can only load other .scl files: %q loads %q", callingFile, modulePath) 162 } 163 // Switch into scl mode from here on 164 if strings.HasSuffix(modulePath, ".scl") { 165 mode = ExecutionModeScl 166 } 167 168 if sym, err := isSymlink(modulePath); sym && err == nil { 169 return nil, fmt.Errorf("symlinks to starlark files are not allowed. Instead, load the target file and re-export its symbols: %s", modulePath) 170 } else if err != nil { 171 return nil, err 172 } 173 174 childThread := &starlark.Thread{Name: "exec " + module, Load: thread.Load} 175 // Cheating for the sake of testing: 176 // propagate starlarktest's Reporter key, otherwise testing 177 // the load function may cause panic in starlarktest code. 178 const testReporterKey = "Reporter" 179 if v := thread.Local(testReporterKey); v != nil { 180 childThread.SetLocal(testReporterKey, v) 181 } 182 183 // Only the entrypoint starlark file allows external loads. 184 childThread.SetLocal(allowExternalEntrypointKey, false) 185 childThread.SetLocal(callingFileKey, modulePath) 186 childThread.SetLocal(executionModeKey, mode) 187 childThread.SetLocal(shellKey, thread.Local(shellKey)) 188 if mode == ExecutionModeRbc { 189 globals, err := starlark.ExecFile(childThread, modulePath, nil, rbcBuiltins) 190 e = &modentry{globals, err} 191 } else if mode == ExecutionModeScl { 192 globals, err := starlark.ExecFile(childThread, modulePath, nil, sclBuiltins) 193 e = &modentry{globals, err} 194 } else { 195 return nil, fmt.Errorf("unknown executionMode %d", mode) 196 } 197 } else { 198 e = &modentry{starlark.StringDict{defaultSymbol: starlark.None}, nil} 199 } 200 201 // Update the cache. 202 moduleCache[modulePath] = e 203 } 204 return e.globals, e.err 205} 206 207// wildcard(pattern, top=None) expands shell's glob pattern. If 'top' is present, 208// the 'top/pattern' is globbed and then 'top/' prefix is removed. 209func wildcard(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, 210 kwargs []starlark.Tuple) (starlark.Value, error) { 211 var pattern string 212 var top string 213 214 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &pattern, &top); err != nil { 215 return starlark.None, err 216 } 217 218 var files []string 219 var err error 220 if top == "" { 221 if files, err = filepath.Glob(pattern); err != nil { 222 return starlark.None, err 223 } 224 } else { 225 prefix := top + string(filepath.Separator) 226 if files, err = filepath.Glob(prefix + pattern); err != nil { 227 return starlark.None, err 228 } 229 for i := range files { 230 files[i] = strings.TrimPrefix(files[i], prefix) 231 } 232 } 233 // Kati uses glob(3) with no flags, which means it's sorted 234 // because GLOB_NOSORT is not passed. Go's glob is not 235 // guaranteed to sort the results. 236 sort.Strings(files) 237 return makeStringList(files), nil 238} 239 240// find(top, pattern, only_files = 0) returns all the paths under 'top' 241// whose basename matches 'pattern' (which is a shell's glob pattern). 242// If 'only_files' is non-zero, only the paths to the regular files are 243// returned. The returned paths are relative to 'top'. 244func find(_ *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, 245 kwargs []starlark.Tuple) (starlark.Value, error) { 246 var top, pattern string 247 var onlyFiles int 248 if err := starlark.UnpackArgs(b.Name(), args, kwargs, 249 "top", &top, "pattern", &pattern, "only_files?", &onlyFiles); err != nil { 250 return starlark.None, err 251 } 252 top = filepath.Clean(top) 253 pattern = filepath.Clean(pattern) 254 // Go's filepath.Walk is slow, consider using OS's find 255 var res []string 256 err := filepath.WalkDir(top, func(path string, d fs.DirEntry, err error) error { 257 if err != nil { 258 if d != nil && d.IsDir() { 259 return fs.SkipDir 260 } else { 261 return nil 262 } 263 } 264 relPath := strings.TrimPrefix(path, top) 265 if len(relPath) > 0 && relPath[0] == os.PathSeparator { 266 relPath = relPath[1:] 267 } 268 // Do not return top-level dir 269 if len(relPath) == 0 { 270 return nil 271 } 272 if matched, err := filepath.Match(pattern, d.Name()); err == nil && matched && (onlyFiles == 0 || d.Type().IsRegular()) { 273 res = append(res, relPath) 274 } 275 return nil 276 }) 277 return makeStringList(res), err 278} 279 280// shell(command) runs OS shell with given command and returns back 281// its output the same way as Make's $(shell ) function. The end-of-lines 282// ("\n" or "\r\n") are replaced with " " in the result, and the trailing 283// end-of-line is removed. 284func shell(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, 285 kwargs []starlark.Tuple) (starlark.Value, error) { 286 var command string 287 if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &command); err != nil { 288 return starlark.None, err 289 } 290 shellPath := thread.Local(shellKey).(string) 291 if shellPath == "" { 292 return starlark.None, 293 fmt.Errorf("cannot run shell, /bin/sh is missing (running on Windows?)") 294 } 295 cmd := exec.Command(shellPath, "-c", command) 296 // We ignore command's status 297 bytes, _ := cmd.Output() 298 output := string(bytes) 299 if strings.HasSuffix(output, "\n") { 300 output = strings.TrimSuffix(output, "\n") 301 } else { 302 output = strings.TrimSuffix(output, "\r\n") 303 } 304 305 return starlark.String( 306 strings.ReplaceAll( 307 strings.ReplaceAll(output, "\r\n", " "), 308 "\n", " ")), nil 309} 310 311func makeStringList(items []string) *starlark.List { 312 elems := make([]starlark.Value, len(items)) 313 for i, item := range items { 314 elems[i] = starlark.String(item) 315 } 316 return starlark.NewList(elems) 317} 318 319func log(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { 320 sep := " " 321 if err := starlark.UnpackArgs("print", nil, kwargs, "sep?", &sep); err != nil { 322 return nil, err 323 } 324 for i, v := range args { 325 if i > 0 { 326 fmt.Fprint(os.Stderr, sep) 327 } 328 if s, ok := starlark.AsString(v); ok { 329 fmt.Fprint(os.Stderr, s) 330 } else if b, ok := v.(starlark.Bytes); ok { 331 fmt.Fprint(os.Stderr, string(b)) 332 } else { 333 fmt.Fprintf(os.Stderr, "%s", v) 334 } 335 } 336 337 fmt.Fprintln(os.Stderr) 338 return starlark.None, nil 339} 340 341// Parses, resolves, and executes a Starlark file. 342// filename and src parameters are as for starlark.ExecFile: 343// * filename is the name of the file to execute, 344// and the name that appears in error messages; 345// * src is an optional source of bytes to use instead of filename 346// (it can be a string, or a byte array, or an io.Reader instance) 347// Returns the top-level starlark variables, the list of starlark files loaded, and an error 348func Run(filename string, src interface{}, mode ExecutionMode, allowExternalEntrypoint bool) (starlark.StringDict, []string, error) { 349 // NOTE(asmundak): OS-specific. Behave similar to Linux `system` call, 350 // which always uses /bin/sh to run the command 351 shellPath := "/bin/sh" 352 if _, err := os.Stat(shellPath); err != nil { 353 shellPath = "" 354 } 355 356 mainThread := &starlark.Thread{ 357 Name: "main", 358 Print: func(_ *starlark.Thread, msg string) { 359 if mode == ExecutionModeRbc { 360 // In rbc mode, rblf_log is used to print to stderr 361 fmt.Println(msg) 362 } else if mode == ExecutionModeScl { 363 fmt.Fprintln(os.Stderr, msg) 364 } 365 }, 366 Load: loader, 367 } 368 filename, err := filepath.Abs(filename) 369 if err != nil { 370 return nil, nil, err 371 } 372 if wd, err := os.Getwd(); err == nil { 373 filename, err = filepath.Rel(wd, filename) 374 if err != nil { 375 return nil, nil, err 376 } 377 if !allowExternalEntrypoint && strings.HasPrefix(filename, "../") { 378 return nil, nil, fmt.Errorf("path could not be made relative to workspace root: %s", filename) 379 } 380 } else { 381 return nil, nil, err 382 } 383 384 if sym, err := isSymlink(filename); sym && err == nil { 385 return nil, nil, fmt.Errorf("symlinks to starlark files are not allowed. Instead, load the target file and re-export its symbols: %s", filename) 386 } else if err != nil { 387 return nil, nil, err 388 } 389 390 if mode == ExecutionModeScl && !strings.HasSuffix(filename, ".scl") { 391 return nil, nil, fmt.Errorf("filename must end in .scl: %s", filename) 392 } 393 394 // Add top-level file to cache for cycle detection purposes 395 moduleCache[filename] = nil 396 397 var results starlark.StringDict 398 mainThread.SetLocal(allowExternalEntrypointKey, allowExternalEntrypoint) 399 mainThread.SetLocal(callingFileKey, filename) 400 mainThread.SetLocal(executionModeKey, mode) 401 mainThread.SetLocal(shellKey, shellPath) 402 if mode == ExecutionModeRbc { 403 results, err = starlark.ExecFile(mainThread, filename, src, rbcBuiltins) 404 } else if mode == ExecutionModeScl { 405 results, err = starlark.ExecFile(mainThread, filename, src, sclBuiltins) 406 } else { 407 return results, nil, fmt.Errorf("unknown executionMode %d", mode) 408 } 409 loadedStarlarkFiles := make([]string, 0, len(moduleCache)) 410 for file := range moduleCache { 411 loadedStarlarkFiles = append(loadedStarlarkFiles, file) 412 } 413 sort.Strings(loadedStarlarkFiles) 414 415 return results, loadedStarlarkFiles, err 416} 417