Debian Codegraph @

interp/vars.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package interp
5
6 import (
7 cryptorand "crypto/rand"
8 "encoding/binary"
9 "errors"
10 "fmt"
11 "maps"
12 mathrand "math/rand/v2"
13 "os"
14 "runtime"
15 "slices"
16 "strconv"
17 "strings"
18
19 "mvdan.cc/sh/v3/expand"
20 "mvdan.cc/sh/v3/internal"
21 "mvdan.cc/sh/v3/syntax"
22 )
23
24 func newOverlayEnviron(parent expand.Environ, background bool) *overlayEnviron {
25 oenv := &overlayEnviron{}
26 if !background {
27 oenv.parent = parent
28 } else {
29 // We could do better here if the parent is also an overlayEnviron;
30 // measure with profiles or benchmarks before we choose to do so.
31 for name, vr := range parent.Each {
32 oenv.Set(name, vr)
33 }
34 }
35 return oenv
36 }
37
38 // overlayEnviron is our main implementation of [expand.WriteEnviron].
39 type overlayEnviron struct {
40 // parent is non-nil if [values] is an overlay over a parent environment
41 // which we can safely reuse without data races, such as non-background subshells
42 // or function calls.
43 parent expand.Environ
44
45 // values maps normalized variable names, per [overlayEnviron.normalize].
46 values map[string]namedVariable
47
48 // We need to know if the current scope is a function's scope, because
49 // functions can modify global variables. When true, [parent] must not be nil.
50 funcScope bool
51 }
52
53 // namedVariable records the original name of a variable for platforms
54 // where variable names are matched in a case-insensitive way.
55 type namedVariable struct {
56 // TODO(v4): consider adding this field to [expand.Variable],
57 // as a general way for a variable to report its original name.
58 // This can be useful for GOOS=windows with case insensitive env vars,
59 // as otherwise it's not possible to Environ.Get a var
60 // and know what was its original name without looping over Environ.Each.
61 Name string
62 expand.Variable
63 }
64
65 func (o *overlayEnviron) normalize(name string) string {
66 if runtime.GOOS == "windows" {
67 return strings.ToUpper(name)
68 }
69 return name
70 }
71
72 func (o *overlayEnviron) Get(name string) expand.Variable {
73 normalized := o.normalize(name)
74 if vr, ok := o.values[normalized]; ok {
75 return vr.Variable
76 }
77 if o.parent != nil {
78 return o.parent.Get(name)
79 }
80 return expand.Variable{}
81 }
82
83 func (o *overlayEnviron) Set(name string, vr expand.Variable) error {
84 normalized := o.normalize(name)
85 prev, inOverlay := o.values[normalized]
86 // Manipulation of a global var inside a function.
87 if o.funcScope && !vr.Local && !prev.Local {
88 // In a function, the parent environment is ours, so it's always read-write.
89 return o.parent.(expand.WriteEnviron).Set(name, vr)
90 }
91 if !inOverlay && o.parent != nil {
92 prev.Variable = o.parent.Get(name)
93 }
94
95 if o.values == nil {
96 o.values = make(map[string]namedVariable)
97 }
98 if vr.Kind == expand.KeepValue {
99 vr.Kind = prev.Kind
100 vr.Str = prev.Str
101 vr.List = prev.List
102 vr.Indexes = prev.Indexes
103 vr.Map = prev.Map
104 } else if prev.ReadOnly {
105 return errReadOnly
106 }
107 if !vr.IsSet() { // unsetting
108 if prev.Local {
109 vr.Local = true
110 o.values[normalized] = namedVariable{name, vr}
111 return nil
112 }
113 delete(o.values, normalized)
114 }
115 // modifying the entire variable
116 vr.Local = prev.Local || vr.Local
117 o.values[normalized] = namedVariable{name, vr}
118 return nil
119 }
120
121 func (o *overlayEnviron) Each(f func(name string, vr expand.Variable) bool) {
122 if o.parent != nil {
123 o.parent.Each(f)
124 }
125 for _, vr := range o.values {
126 if !f(vr.Name, vr.Variable) {
127 return
128 }
129 }
130 }
131
132 func execEnv(env expand.Environ) []string {
133 list := make([]string, 0, 64)
134 for name, vr := range env.Each {
135 if !vr.IsSet() {
136 // If a variable is set globally but unset in the
137 // runner, we need to ensure it's not part of the final
138 // list. Seems like zeroing the element is enough.
139 // This is a linear search, but this scenario should be
140 // rare, and the number of variables shouldn't be large.
141 for i, kv := range list {
142 if strings.HasPrefix(kv, name+"=") {
143 list[i] = ""
144 }
145 }
146 }
147 if vr.Exported && vr.Kind == expand.String {
148 list = append(list, name+"="+vr.String())
149 }
150 }
151 return list
152 }
153
154 func (r *Runner) lookupVar(name string) expand.Variable {
155 if name == "" {
156 panic("variable name must not be empty")
157 }
158 var vr expand.Variable
159 switch name {
160 case "#":
161 vr.Kind, vr.Str = expand.String, strconv.Itoa(len(r.Params))
162 case "@", "*":
163 vr.Kind = expand.Indexed
164 if r.Params == nil {
165 // r.Params may be nil but positional parameters always exist
166 vr.List = []string{}
167 } else {
168 vr.List = r.Params
169 }
170 case "!":
171 if n := len(r.bgProcs); n > 0 {
172 vr.Kind, vr.Str = expand.String, "g"+strconv.Itoa(n)
173 }
174 case "?":
175 vr.Kind, vr.Str = expand.String, strconv.Itoa(int(r.lastExit.code))
176 case "-":
177 // Note that we don't support some of Bash's flags, such as h or B.
178 vr.Kind, vr.Str = expand.String, r.posixOptFlags()
179 case "$":
180 vr.Kind, vr.Str = expand.String, strconv.Itoa(os.Getpid())
181 case "PPID":
182 vr.Kind, vr.Str = expand.String, strconv.Itoa(os.Getppid())
183 case "RANDOM": // not for cryptographic use
184 // Without a seed we use the global generator, which is seeded randomly
185 // and also uses ChaCha8. Note that [Runner.subshell] does not copy the
186 // seeded generator, so subshells start afresh like in bash.
187 var n int
188 if r.rand != nil {
189 n = r.rand.IntN(randomMax)
190 } else {
191 n = mathrand.IntN(randomMax)
192 }
193 vr.Kind, vr.Str = expand.String, strconv.Itoa(n)
194 case "SRANDOM": // pseudo-random generator from the system
195 var p [4]byte
196 cryptorand.Read(p[:])
197 n := binary.NativeEndian.Uint32(p[:])
198 vr.Kind, vr.Str = expand.String, strconv.FormatUint(uint64(n), 10)
199 case "DIRSTACK":
200 vr.Kind, vr.List = expand.Indexed, r.dirStack
201 case "0":
202 vr.Kind = expand.String
203 if r.filename != "" {
204 vr.Str = r.filename
205 } else {
206 vr.Str = "gosh"
207 }
208 case "1", "2", "3", "4", "5", "6", "7", "8", "9":
209 if i := int(name[0] - '1'); i < len(r.Params) {
210 vr.Kind = expand.String
211 vr.Str = r.Params[i]
212 }
213 }
214 if vr.Kind != expand.Unknown {
215 vr.Set = true
216 return vr
217 }
218 if vr := r.writeEnv.Get(name); vr.Declared() {
219 return vr
220 }
221 return expand.Variable{}
222 }
223
224 func (r *Runner) envGet(name string) string {
225 return r.lookupVar(name).String()
226 }
227
228 func (r *Runner) delVar(name string) {
229 if err := r.writeEnv.Set(name, expand.Variable{}); err != nil {
230 r.errf("%s: %v\n", name, err)
231 r.exit.code = 1
232 return
233 }
234 }
235
236 func (r *Runner) setVarString(name, value string) {
237 r.setVar(name, expand.Variable{Set: true, Kind: expand.String, Str: value})
238 }
239
240 func (r *Runner) setVar(name string, vr expand.Variable) {
241 if err := r.setVarErr(name, vr); err != nil {
242 r.errf("%v\n", err)
243 r.exit.code = 1
244 }
245 }
246
247 // errReadOnly is returned when trying to modify a read-only variable.
248 var errReadOnly = errors.New("readonly variable")
249
250 // randomMax is one past the highest value that RANDOM expands to, like in Bash.
251 const randomMax = 32768
252
253 // setVarErr is like [Runner.setVar], but it returns any error rather than
254 // reporting it, for the sake of the expand package.
255 func (r *Runner) setVarErr(name string, vr expand.Variable) error {
256 if r.opts[optAllExport] {
257 vr.Exported = true
258 }
259 if err := r.writeEnv.Set(name, vr); err != nil {
260 return fmt.Errorf("%s: %w", name, err)
261 }
262 if name == "RANDOM" && vr.Kind == expand.String {
263 // Assigning to RANDOM seeds its generator; the stored value is never
264 // read, as [Runner.lookupVar] always computes a new number. We only
265 // seed once the assignment succeeds so that attributes such as
266 // read-only still apply. We use ChaCha8 rather than PCG, whose only
267 // edge is speed, which is irrelevant next to expanding a variable.
268 var seed [32]byte
269 binary.LittleEndian.PutUint64(seed[:], uint64(atoi(vr.Str)))
270 r.rand = mathrand.New(mathrand.NewChaCha8(seed))
271 }
272 return nil
273 }
274
275 func (r *Runner) setVarWithIndex(prev expand.Variable, name string, index syntax.ArithmExpr, vr expand.Variable) {
276 if vr.Kind == expand.String && index == nil {
277 // When assigning a string to an array, fall back to the
278 // zero value for the index.
279 switch prev.Kind {
280 case expand.Indexed:
281 index = &syntax.Word{Parts: []syntax.WordPart{
282 &syntax.Lit{Value: "0"},
283 }}
284 case expand.Associative:
285 index = &syntax.Word{Parts: []syntax.WordPart{
286 &syntax.DblQuoted{},
287 }}
288 }
289 }
290 if index == nil {
291 r.setVar(name, vr)
292 return
293 }
294
295 // from the syntax package, we know that value must be a string if index
296 // is non-nil; nested arrays are forbidden.
297 valStr := vr.Str
298
299 var list []string
300 var indexes []int
301 switch prev.Kind {
302 case expand.String:
303 list = append(list, prev.Str)
304 case expand.Indexed:
305 // TODO: only clone when inside a subshell and getting a var from outside for the first time
306 list = slices.Clone(prev.List)
307 indexes = slices.Clone(prev.Indexes)
308 case expand.Associative:
309 // if the existing variable is already an AssocArray, try our
310 // best to convert the key to a string
311 w, ok := index.(*syntax.Word)
312 if !ok {
313 return
314 }
315 k := r.literal(w)
316
317 // TODO: only clone when inside a subshell and getting a var from outside for the first time
318 prev.Map = maps.Clone(prev.Map)
319 if prev.Map == nil {
320 prev.Map = make(map[string]string)
321 }
322 prev.Map[k] = valStr
323 r.setVar(name, prev)
324 return
325 }
326 k := r.arithm(index)
327 if k < 0 {
328 // Negative indices count from one past the maximum index.
329 if k += internal.IndexedMax(list, indexes) + 1; k < 0 {
330 r.errf("%s: bad array subscript\n", name)
331 r.exit.code = 1
332 return
333 }
334 }
335 list, indexes = internal.SetIndexedElem(list, indexes, k, valStr)
336 prev.Kind = expand.Indexed
337 prev.List = list
338 prev.Indexes = indexes
339 r.setVar(name, prev)
340 }
341
342 // cutElemSubscript splits an array element argument like `a[3]`, as used by
343 // the unset builtin, into the array name and the subscript between brackets.
344 func cutElemSubscript(arg string) (name, sub string, ok bool) {
345 i := strings.IndexByte(arg, '[')
346 if i > 0 && strings.HasSuffix(arg, "]") && syntax.ValidName(arg[:i]) {
347 return arg[:i], arg[i+1 : len(arg)-1], true
348 }
349 return "", "", false
350 }
351
352 // unsetElem unsets a single element of an indexed or associative array, like
353 // `unset 'a[3]'`. Unsetting an indexed array element may leave a hole.
354 func (r *Runner) unsetElem(name, sub string) {
355 vr := r.lookupVar(name)
356 if n, v := vr.Resolve(r.writeEnv); n != "" {
357 name, vr = n, v
358 }
359 switch vr.Kind {
360 case expand.Indexed:
361 if sub == "@" || sub == "*" {
362 r.delVar(name)
363 return
364 }
365 expr, err := syntax.NewParser().Arithmetic(strings.NewReader(sub))
366 if err != nil {
367 r.errf("unset: %s[%s]: bad array subscript\n", name, sub)
368 r.exit.code = 1
369 return
370 }
371 if expr == nil {
372 return // an empty subscript like `unset 'a[]'` is a no-op
373 }
374 k := r.arithm(expr)
375 if k < 0 {
376 // Negative indices count from one past the maximum index.
377 if k += internal.IndexedMax(vr.List, vr.Indexes) + 1; k < 0 {
378 r.errf("unset: %s[%s]: bad array subscript\n", name, sub)
379 r.exit.code = 1
380 return
381 }
382 }
383 // TODO: only clone when inside a subshell and getting a var from outside for the first time
384 vr.List = slices.Clone(vr.List)
385 vr.Indexes = slices.Clone(vr.Indexes)
386 vr.List, vr.Indexes = internal.DeleteIndexedElem(vr.List, vr.Indexes, k)
387 r.setVar(name, vr)
388 case expand.Associative:
389 if sub == "@" || sub == "*" {
390 r.delVar(name)
391 return
392 }
393 // TODO: only clone when inside a subshell and getting a var from outside for the first time
394 vr.Map = maps.Clone(vr.Map)
395 delete(vr.Map, sub)
396 r.setVar(name, vr)
397 case expand.String:
398 // A scalar can be unset via subscript zero.
399 if sub == "0" {
400 r.delVar(name)
401 } else {
402 r.errf("unset: %s: not an array variable\n", name)
403 r.exit.code = 1
404 }
405 }
406 }
407
408 func (r *Runner) setFunc(name string, body *syntax.Stmt) {
409 if r.Funcs == nil {
410 r.Funcs = make(map[string]*syntax.Stmt, 4)
411 }
412 r.Funcs[name] = body
413 }
414
415 func stringIndex(index syntax.ArithmExpr) bool {
416 w, ok := index.(*syntax.Word)
417 if !ok || len(w.Parts) != 1 {
418 return false
419 }
420 switch w.Parts[0].(type) {
421 case *syntax.DblQuoted, *syntax.SglQuoted:
422 return true
423 }
424 return false
425 }
426
427 // TODO: make assignVal and [setVar] consistent with the [expand.WriteEnviron] interface
428
429 func (r *Runner) assignVal(name string, prev expand.Variable, as *syntax.Assign, valType string) (string, expand.Variable) {
430 if n, v := prev.Resolve(r.writeEnv); n != "" {
431 name, prev = n, v
432 }
433 prev.Set = true
434 if as.Value != nil {
435 s := r.literal(as.Value)
436 if !as.Append {
437 prev.Kind = expand.String
438 if valType == "-n" {
439 prev.Kind = expand.NameRef
440 }
441 prev.Str = s
442 return name, prev
443 }
444 switch prev.Kind {
445 case expand.String, expand.Unknown:
446 prev.Kind = expand.String
447 prev.Str += s
448 case expand.Indexed:
449 // Appends to the element at index 0, creating it if unset.
450 if len(prev.List) > 0 && (prev.Indexes == nil || prev.Indexes[0] == 0) {
451 prev.List[0] += s
452 } else {
453 prev.List, prev.Indexes = internal.SetIndexedElem(prev.List, prev.Indexes, 0, s)
454 }
455 case expand.Associative:
456 // TODO
457 }
458 return name, prev
459 }
460 if as.Array == nil {
461 // don't return the zero value, as that's an unset variable
462 prev.Kind = expand.String
463 if valType == "-n" {
464 prev.Kind = expand.NameRef
465 }
466 prev.Str = ""
467 return name, prev
468 }
469 // Array assignment.
470 elems := as.Array.Elems
471 if valType == "" {
472 valType = "-a" // indexed
473 if len(elems) > 0 && stringIndex(elems[0].Index) {
474 valType = "-A" // associative
475 }
476 }
477 if valType == "-A" {
478 amap := make(map[string]string, len(elems))
479 for _, elem := range elems {
480 k := r.literal(elem.Index.(*syntax.Word))
481 amap[k] = r.literal(elem.Value)
482 }
483 if !as.Append {
484 prev.Kind = expand.Associative
485 prev.Map = amap
486 return name, prev
487 }
488 // TODO
489 return name, prev
490 }
491 // The base array which the new elements are set on; empty unless
492 // we are appending to an existing value.
493 var list []string
494 var indexes []int
495 if as.Append {
496 switch prev.Kind {
497 case expand.Unknown:
498 case expand.String:
499 list = []string{prev.Str}
500 case expand.Indexed:
501 // TODO: only clone when inside a subshell and getting a var from outside for the first time
502 list = slices.Clone(prev.List)
503 indexes = slices.Clone(prev.Indexes)
504 case expand.Associative:
505 // TODO
506 return name, prev
507 default:
508 // Should only happen if we forgot a case above.
509 panic(fmt.Sprintf("unexpected conversion of kind %d", prev.Kind))
510 }
511 }
512 // Evaluate values for each array element. An explicit index like
513 // [5]=x resets our index counter, which otherwise advances for every
514 // value, starting after the maximum index of the base array.
515 index := internal.IndexedMax(list, indexes) + 1
516 for _, elem := range elems {
517 if elem.Index != nil {
518 // Index resets our index with a literal value.
519 index = r.arithm(elem.Index)
520 if index < 0 {
521 // Negative indices count from one past the maximum index.
522 if index += internal.IndexedMax(list, indexes) + 1; index < 0 {
523 r.errf("%s: bad array subscript\n", name)
524 r.exit.code = 1
525 break
526 }
527 }
528 list, indexes = internal.SetIndexedElem(list, indexes, index, r.literal(elem.Value))
529 index++
530 } else {
531 // Implicit index, advancing for every word.
532 for _, val := range r.fields(elem.Value) {
533 list, indexes = internal.SetIndexedElem(list, indexes, index, val)
534 index++
535 }
536 }
537 }
538 if list == nil {
539 // An empty array like a=() must still expand to zero fields.
540 list = []string{}
541 }
542 prev.Kind = expand.Indexed
543 prev.List = list
544 prev.Indexes = indexes
545 return name, prev
546 }