internal/codescan/shell.go

272 lines · 6729 bytes

12 symbols in this file
  1package codescan
  2
  3import "strings"
  4
  5// unquotedExpansionRule flags a parameter expansion in a command. It
  6// reports $1 in printf "%$(($1 - 1))s", where the shell splits nothing:
  7// arithmetic is never word-split, and here it is inside double quotes as
  8// well.
  9// splitLines reads the script to tell those apart from the real thing.
 10const unquotedExpansionRule = "bash.lang.correctness.unquoted-variable-expansion-in-command"
 11
 12// Shell contexts. In a command, a backtick or a $( ) an expansion is
 13// word-split; in double quotes and arithmetic it is not.
 14const (
 15	shCommand = iota
 16	shSubst
 17	shBacktick
 18	shDouble
 19	shArith
 20)
 21
 22type shFrame struct {
 23	kind  int
 24	depth int // ( open within the frame
 25}
 26
 27type heredoc struct {
 28	delim         string
 29	strip, quoted bool
 30}
 31
 32// splitLines returns the lines of a shell script that hold an expansion
 33// the shell word-splits: $name, ${…}, $1, $* or $@ outside double quotes
 34// and arithmetic. A command that runs over several lines marks all of
 35// them. ok is false when the script does not read to the end with every
 36// quote, bracket and heredoc closed, and then nothing is known.
 37func splitLines(src []byte) (lines map[int]bool, ok bool) {
 38	s := string(src)
 39	lines = map[int]bool{}
 40	stack := []shFrame{{kind: shCommand}}
 41	line, first := 1, 1
 42	split := false
 43	var pending []heredoc
 44	push := func(kind int) { stack = append(stack, shFrame{kind: kind}) }
 45	pop := func() { stack = stack[:len(stack)-1] }
 46	for i := 0; i < len(s); i++ {
 47		c := s[i]
 48		top := &stack[len(stack)-1]
 49		if c == '\n' {
 50			line++
 51			if top.kind == shDouble || top.kind == shArith {
 52				continue
 53			}
 54			end, l, sp, ok := heredocs(s, i+1, pending)
 55			if !ok {
 56				return nil, false
 57			}
 58			i, line, split, pending = end-1, line+l, split || sp, nil
 59			if len(stack) == 1 {
 60				if split {
 61					for l := first; l < line; l++ {
 62						lines[l] = true
 63					}
 64				}
 65				first, split = line, false
 66			}
 67			continue
 68		}
 69		if c == '\\' {
 70			if i+1 < len(s) && s[i+1] == '\n' {
 71				line++
 72			}
 73			i++
 74			continue
 75		}
 76		if c == '$' {
 77			n, kind, splits := dollar(s, i, top.kind)
 78			if n < 0 {
 79				return nil, false
 80			}
 81			line += strings.Count(s[i:i+n], "\n")
 82			split = split || splits
 83			if kind >= 0 {
 84				push(kind)
 85			}
 86			i += n - 1
 87			continue
 88		}
 89		switch top.kind {
 90		case shDouble:
 91			switch c {
 92			case '"':
 93				pop()
 94			case '`':
 95				push(shBacktick)
 96			}
 97		case shArith:
 98			switch {
 99			case c == '"':
100				push(shDouble)
101			case c == '(':
102				top.depth++
103			case c == ')' && top.depth > 0:
104				top.depth--
105			case c == ')':
106				if i+1 >= len(s) || s[i+1] != ')' {
107					return nil, false
108				}
109				pop()
110				i++
111			}
112		default: // shCommand, shSubst, shBacktick
113			switch {
114			case c == '\'':
115				end := strings.IndexByte(s[i+1:], '\'')
116				if end < 0 {
117					return nil, false
118				}
119				line += strings.Count(s[i+1:i+1+end], "\n")
120				i += 1 + end
121			case c == '"':
122				push(shDouble)
123			case c == '`' && top.kind == shBacktick:
124				pop()
125			case c == '`':
126				push(shBacktick)
127			case c == '#' && (i == 0 || strings.IndexByte(" \t\n;|&(", s[i-1]) >= 0):
128				if end := strings.IndexByte(s[i:], '\n'); end >= 0 {
129					i += end - 1
130				} else {
131					i = len(s)
132				}
133			case c == '(':
134				top.depth++
135			case c == ')' && top.depth > 0:
136				top.depth--
137			case c == ')' && top.kind == shSubst:
138				pop()
139			case strings.HasPrefix(s[i:], "<<") && !strings.HasPrefix(s[i:], "<<<"):
140				h, n := heredocOp(s, i)
141				if n < 0 {
142					return nil, false
143				}
144				pending = append(pending, h)
145				i += n - 1
146			}
147		}
148	}
149	if len(stack) != 1 || len(pending) > 0 {
150		return nil, false
151	}
152	if split {
153		for l := first; l <= line; l++ {
154			lines[l] = true
155		}
156	}
157	return lines, true
158}
159
160// dollar reads the expansion starting with the $ at i, in a context of
161// kind ctx. n is how many bytes it takes, or -1 when it is not closed;
162// kind is the frame it opens, or -1; splits is whether the shell
163// word-splits it there.
164func dollar(s string, i, ctx int) (n, kind int, splits bool) {
165	splitting := ctx != shDouble && ctx != shArith
166	rest := s[i+1:]
167	switch {
168	case strings.HasPrefix(rest, "(("):
169		return 3, shArith, false
170	case strings.HasPrefix(rest, "("):
171		return 2, shSubst, false
172	case strings.HasPrefix(rest, "{"):
173		depth := 0
174		for j := 1; j < len(s)-i; j++ {
175			switch s[i+j] {
176			case '\\':
177				j++
178			case '{':
179				depth++
180			case '}':
181				if depth--; depth == 0 {
182					return j + 1, -1, splitting
183				}
184			}
185		}
186		return -1, -1, false
187	case strings.HasPrefix(rest, "'") && ctx != shDouble:
188		for j := 2; j < len(s)-i; j++ {
189			switch s[i+j] {
190			case '\\':
191				j++
192			case '\'':
193				return j + 1, -1, false
194			}
195		}
196		return -1, -1, false
197	case strings.HasPrefix(rest, `"`) && ctx != shDouble:
198		return 2, shDouble, false
199	case rest != "" && (rest[0] == '_' || isLetter(rest[0])):
200		j := 1
201		for j < len(rest) && (rest[j] == '_' || isLetter(rest[j]) || rest[j] >= '0' && rest[j] <= '9') {
202			j++
203		}
204		return j + 1, -1, splitting
205	case rest != "" && (rest[0] >= '0' && rest[0] <= '9' || rest[0] == '*' || rest[0] == '@'):
206		return 2, -1, splitting
207	}
208	// $# $? $$ $! $- expand to text with no separators in it; a bare $ is
209	// literal.
210	if rest != "" && strings.IndexByte("#?$!-", rest[0]) >= 0 {
211		return 2, -1, false
212	}
213	return 1, -1, false
214}
215
216// heredocOp reads a << or <<- operator and its delimiter word at i. n is
217// how many bytes it takes, or -1 when there is no word.
218func heredocOp(s string, i int) (heredoc, int) {
219	j := i + 2
220	var h heredoc
221	if j < len(s) && s[j] == '-' {
222		h.strip = true
223		j++
224	}
225	for j < len(s) && (s[j] == ' ' || s[j] == '\t') {
226		j++
227	}
228	start := j
229	for j < len(s) && strings.IndexByte(" \t\n;|&<>()", s[j]) < 0 {
230		j++
231	}
232	word := s[start:j]
233	h.quoted = strings.ContainsAny(word, `'"\`)
234	h.delim = strings.NewReplacer(`'`, "", `"`, "", `\`, "").Replace(word)
235	if h.delim == "" {
236		return h, -1
237	}
238	return h, j - i
239}
240
241// heredocs reads the bodies of the pending heredocs from i, the start of
242// the line after their operators. end is just past the last delimiter
243// line, n the lines read. A body that is not quoted and runs a command
244// substitution counts as splitting, since the command inside is not
245// read here.
246func heredocs(s string, i int, pending []heredoc) (end, n int, splits, ok bool) {
247	for _, h := range pending {
248		for {
249			if i >= len(s) {
250				return 0, 0, false, false
251			}
252			nl := strings.IndexByte(s[i:], '\n')
253			text := s[i:]
254			next := len(s)
255			if nl >= 0 {
256				text, next = s[i:i+nl], i+nl+1
257				n++
258			}
259			if !h.quoted && (strings.Contains(text, "$(") || strings.Contains(text, "`")) {
260				splits = true
261			}
262			i = next
263			if h.strip {
264				text = strings.TrimLeft(text, "\t")
265			}
266			if text == h.delim {
267				break
268			}
269		}
270	}
271	return i, n, splits, true
272}