summaryrefslogtreecommitdiff
path: root/pkgtools/pkglint/files/shell.go
blob: 0ed87fc1598103dcb9e05e307a097e94edd0ebef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
package main

// Parsing and checking shell commands embedded in Makefiles

import (
	"path"
	"strings"
)

const (
	reShVarname      = `(?:[!#*\-\d?@]|\$\$|[A-Za-z_]\w*)`
	reShVarexpansion = `(?:(?:#|##|%|%%|:-|:=|:\?|:\+|\+)[^$\\{}]*)`
	reShVaruse       = `\$\$` + `(?:` + reShVarname + `|` + `\{` + reShVarname + `(?:` + reShVarexpansion + `)?` + `\})`
	reShDollar       = `\\\$\$|` + reShVaruse + `|\$\$[,\-/|]`
)

type ShellLine struct {
	line   *Line
	mkline *MkLine
}

func NewShellLine(mkline *MkLine) *ShellLine {
	return &ShellLine{mkline.Line, mkline}
}

var shellcommandsContextType = &Vartype{lkNone, BtShellCommands, []AclEntry{{"*", aclpAllRuntime}}, false}
var shellwordVuc = &VarUseContext{shellcommandsContextType, vucTimeUnknown, vucQuotPlain, false}

func (shline *ShellLine) CheckWord(token string, checkQuoting bool) {
	if G.opts.Debug {
		defer tracecall(token, checkQuoting)()
	}

	if token == "" || hasPrefix(token, "#") {
		return
	}

	line := shline.line

	p := NewMkParser(line, token, false)
	if varuse := p.VarUse(); varuse != nil && p.EOF() {
		shline.mkline.CheckVaruse(varuse, shellwordVuc)
		return
	}

	if matches(token, `\$\{PREFIX\}/man(?:$|/)`) {
		line.Warn0("Please use ${PKGMANDIR} instead of \"man\".")
	}
	if contains(token, "etc/rc.d") {
		line.Warn0("Please use the RCD_SCRIPTS mechanism to install rc.d scripts automatically to ${RCD_SCRIPTS_EXAMPLEDIR}.")
	}

	parser := NewMkParser(line, token, false)
	repl := parser.repl
	quoting := shqPlain
outer:
	for !parser.EOF() {
		if G.opts.Debug {
			traceStep("shell state %s: %q", quoting, parser.Rest())
		}

		switch {
		// When parsing inside backticks, it is more
		// reasonable to check the whole shell command
		// recursively, instead of splitting off the first
		// make(1) variable.
		case quoting == shqBackt || quoting == shqDquotBackt:
			var backtCommand string
			backtCommand, quoting = shline.unescapeBackticks(token, repl, quoting)
			setE := true
			shline.CheckShellCommand(backtCommand, &setE)

			// Make(1) variables have the same syntax, no matter in which state we are currently.
		case shline.checkVaruseToken(parser, quoting):
			break

		case quoting == shqPlain:
			switch {
			case repl.AdvanceRegexp(`^[!#\%&\(\)*+,\-.\/0-9:;<=>?@A-Z\[\]^_a-z{|}~]+`),
				repl.AdvanceRegexp(`^\\(?:[ !"#'\(\)*./;?\\^{|}]|\$\$)`):
			case repl.AdvanceStr("'"):
				quoting = shqSquot
			case repl.AdvanceStr("\""):
				quoting = shqDquot
			case repl.AdvanceStr("`"):
				quoting = shqBackt
			case repl.AdvanceRegexp(`^\$\$([0-9A-Z_a-z]+|#)`),
				repl.AdvanceRegexp(`^\$\$\{([0-9A-Z_a-z]+|#)\}`),
				repl.AdvanceRegexp(`^\$\$(\$)\$`):
				shvarname := repl.m[1]
				if G.opts.WarnQuoting && checkQuoting && shline.variableNeedsQuoting(shvarname) {
					line.Warn1("Unquoted shell variable %q.", shvarname)
					Explain(
						"When a shell variable contains white-space, it is expanded (split",
						"into multiple words) when it is written as $variable in a shell",
						"script.  If that is not intended, you should add quotation marks",
						"around it, like \"$variable\".  Then, the variable will always expand",
						"to a single word, preserving all white-space and other special",
						"characters.",
						"",
						"Example:",
						"\tfname=\"Curriculum vitae.doc\"",
						"\tcp $fname /tmp",
						"\t# tries to copy the two files \"Curriculum\" and \"Vitae.doc\"",
						"\tcp \"$fname\" /tmp",
						"\t# copies one file, as intended")
				}
			case repl.AdvanceStr("$@"):
				line.Warn2("Please use %q instead of %q.", "${.TARGET}", "$@")
				Explain2(
					"It is more readable and prevents confusion with the shell variable of",
					"the same name.")

			case repl.AdvanceStr("$$@"):
				line.Warn0("The $@ shell variable should only be used in double quotes.")

			case repl.AdvanceStr("$$?"):
				line.Warn0("The $? shell variable is often not available in \"set -e\" mode.")

			case repl.AdvanceStr("$$("):
				line.Warn0("Invoking subshells via $(...) is not portable enough.")
				Explain2(
					"The Solaris /bin/sh does not know this way to execute a command in a",
					"subshell.  Please use backticks (`...`) as a replacement.")

			case repl.AdvanceStr("$$"): // Not part of a variable.
				break

			default:
				break outer
			}

		case quoting == shqSquot:
			switch {
			case repl.AdvanceRegexp(`^'`):
				quoting = shqPlain
			case repl.AdvanceRegexp(`^[^\$\']+`):
				// just skip
			case repl.AdvanceRegexp(`^\$\$`):
				// just skip
			default:
				break outer
			}

		case quoting == shqDquot:
			switch {
			case repl.AdvanceStr("\""):
				quoting = shqPlain
			case repl.AdvanceStr("`"):
				quoting = shqDquotBackt
			case repl.AdvanceRegexp("^[^$\"\\\\`]+"):
				break
			case repl.AdvanceStr("\\$$"):
				break
			case repl.AdvanceRegexp(`^\\.`): // See http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_02_01
				break
			case repl.AdvanceRegexp(`^\$\$\{\w+[#%+\-:]*[^{}]*\}`),
				repl.AdvanceRegexp(`^\$\$(?:\w+|[!#?@]|\$\$)`):
				break
			case repl.AdvanceStr("$$"):
				line.Warn0("Unescaped $ or strange shell variable found.")
			default:
				break outer
			}
		}
	}

	if strings.TrimSpace(parser.Rest()) != "" {
		line.Warnf("Pkglint parse error in ShellLine.CheckWord at %q (quoting=%s, rest=%q)", token, quoting, parser.Rest())
	}
}

func (shline *ShellLine) checkVaruseToken(parser *MkParser, quoting ShQuoting) bool {
	if G.opts.Debug {
		defer tracecall(parser.Rest(), quoting)()
	}

	varuse := parser.VarUse()
	if varuse == nil {
		return false
	}
	varname := varuse.varname

	if varname == "@" {
		shline.line.Warn0("Please use \"${.TARGET}\" instead of \"$@\".")
		Explain2(
			"The variable $@ can easily be confused with the shell variable of",
			"the same name, which has a completely different meaning.")
		varname = ".TARGET"
		varuse = &MkVarUse{varname, varuse.modifiers}
	}

	switch {
	case quoting == shqPlain && varuse.IsQ():
		// Fine.
	case quoting == shqBackt:
		// Don't check anything here, to avoid false positives for tool names.
	case (quoting == shqSquot || quoting == shqDquot) && matches(varname, `^(?:.*DIR|.*FILE|.*PATH|.*_VAR|PREFIX|.*BASE|PKGNAME)$`):
		// This is ok if we don't allow these variables to have embedded [\$\\\"\'\`].
	case quoting == shqDquot && varuse.IsQ():
		shline.line.Warn0("Please don't use the :Q operator in double quotes.")
		Explain2(
			"Either remove the :Q or the double quotes.  In most cases, it is",
			"more appropriate to remove the double quotes.")
	}

	if varname != "@" {
		vucstate := quoting.ToVarUseContext()
		vuc := &VarUseContext{shellcommandsContextType, vucTimeUnknown, vucstate, true}
		shline.mkline.CheckVaruse(varuse, vuc)
	}
	return true
}

// Scan for the end of the backticks, checking for single backslashes
// and removing one level of backslashes. Backslashes are only removed
// before a dollar, a backslash or a backtick.
//
// See http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_03
func (shline *ShellLine) unescapeBackticks(shellword string, repl *PrefixReplacer, quoting ShQuoting) (unescaped string, newQuoting ShQuoting) {
	if G.opts.Debug {
		defer tracecall(shellword, quoting, "=>", ref(&unescaped))()
	}

	line := shline.line
	for repl.rest != "" {
		switch {
		case repl.AdvanceStr("`"):
			if quoting == shqBackt {
				quoting = shqPlain
			} else {
				quoting = shqDquot
			}
			return unescaped, quoting

		case repl.AdvanceRegexp("^\\\\([\"\\\\`$])"):
			unescaped += repl.m[1]

		case repl.AdvanceStr("\\"):
			line.Warn0("Backslashes should be doubled inside backticks.")
			unescaped += "\\"

		case quoting == shqDquotBackt && repl.AdvanceStr("\""):
			line.Warn0("Double quotes inside backticks inside double quotes are error prone.")
			Explain4(
				"According to the SUSv3, they produce undefined results.",
				"",
				"See the paragraph starting \"Within the backquoted ...\" in",
				"http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html")

		case repl.AdvanceRegexp("^([^\\\\`]+)"):
			unescaped += repl.m[1]

		default:
			line.Errorf("Internal pkglint error in ShellLine.unescapeBackticks at %q (rest=%q)", shellword, repl.rest)
		}
	}
	line.Error1("Unfinished backquotes: rest=%q", repl.rest)
	return unescaped, quoting
}

func (shline *ShellLine) variableNeedsQuoting(shvarname string) bool {
	switch shvarname {
	case "#", "?":
		return false // Definitely ok
	case "d", "f", "i", "dir", "file", "src", "dst":
		return false // Probably ok
	}
	return true
}

func (shline *ShellLine) CheckShellCommandLine(shelltext string) {
	if G.opts.Debug {
		defer tracecall1(shelltext)()
	}

	line := shline.line

	if contains(shelltext, "${SED}") && contains(shelltext, "${MV}") {
		line.Note0("Please use the SUBST framework instead of ${SED} and ${MV}.")
		Explain(
			"Using the SUBST framework instead of explicit commands is easier",
			"to understand, since all the complexity of using sed and mv is",
			"hidden behind the scenes.",
			"",
			"Run \"bmake help topic=subst\" for more information.")
		if contains(shelltext, "#") {
			Explain(
				"When migrating to the SUBST framework, pay attention to \"#\"",
				"characters.  In shell commands, make(1) does not interpret them as",
				"comment character, but in variable assignments it does.  Therefore,",
				"instead of the shell command",
				"",
				"\tsed -e 's,#define foo,,'",
				"",
				"you need to write",
				"",
				"\tSUBST_SED.foo+=\t's,\\#define foo,,'")
		}
	}

	if m, cmd := match1(shelltext, `^@*-(.*(?:MKDIR|INSTALL.*-d|INSTALL_.*_DIR).*)`); m {
		line.Note1("You don't need to use \"-\" before %q.", cmd)
	}

	repl := NewPrefixReplacer(shelltext)
	repl.AdvanceRegexp(`^\s+`)
	if repl.AdvanceRegexp(`^[-@]+`) {
		shline.checkHiddenAndSuppress(repl.m[0], repl.rest)
	}
	setE := false
	if repl.AdvanceStr("${RUN}") {
		setE = true
	} else {
		repl.AdvanceStr("${_PKG_SILENT}${_PKG_DEBUG}")
	}

	shline.CheckShellCommand(repl.rest, &setE)
}

func (shline *ShellLine) CheckShellCommand(shellcmd string, pSetE *bool) {
	if G.opts.Debug {
		defer tracecall()()
	}

	program, err := parseShellProgram(shline.line, shellcmd)
	if err != nil && contains(shellcmd, "$$(") { // Hack until the shell parser can handle subshells.
		shline.line.Warn0("Invoking subshells via $(...) is not portable enough.")
		return
	}
	if err != nil {
		shline.line.Warnf("Pkglint ShellLine.CheckShellCommand: %s", err)
		return
	}

	spc := &ShellProgramChecker{shline}
	spc.checkConditionalCd(program)

	(*MkShWalker).Walk(nil, program, func(node interface{}) {
		if cmd, ok := node.(*MkShSimpleCommand); ok {
			scc := NewSimpleCommandChecker(shline, cmd)
			scc.Check()
			if scc.strcmd.Name == "set" && scc.strcmd.AnyArgMatches(`^-.*e`) {
				*pSetE = true
			}
		}

		if cmd, ok := node.(*MkShList); ok {
			spc.checkSetE(cmd, pSetE)
		}

		if cmd, ok := node.(*MkShPipeline); ok {
			spc.checkPipeExitcode(shline.line, cmd)
		}

		if word, ok := node.(*ShToken); ok {
			spc.checkWord(word, false)
		}
	})
}

func (shline *ShellLine) CheckShellCommands(shellcmds string) {
	setE := true
	shline.CheckShellCommand(shellcmds, &setE)
	if !hasSuffix(shellcmds, ";") {
		shline.line.Warn0("This shell command list should end with a semicolon.")
	}
}

func (shline *ShellLine) checkHiddenAndSuppress(hiddenAndSuppress, rest string) {
	if G.opts.Debug {
		defer tracecall(hiddenAndSuppress, rest)()
	}

	switch {
	case !contains(hiddenAndSuppress, "@"):
		// Nothing is hidden at all.

	case hasPrefix(G.Mk.target, "show-") || hasSuffix(G.Mk.target, "-message"):
		// In these targets, all commands may be hidden.

	case hasPrefix(rest, "#"):
		// Shell comments may be hidden, since they cannot have side effects.

	default:
		tokens, _ := splitIntoShellTokens(shline.line, rest)
		if len(tokens) > 0 {
			cmd := tokens[0]
			switch cmd {
			case "${DELAYED_ERROR_MSG}", "${DELAYED_WARNING_MSG}",
				"${DO_NADA}",
				"${ECHO}", "${ECHO_MSG}", "${ECHO_N}", "${ERROR_CAT}", "${ERROR_MSG}",
				"${FAIL_MSG}",
				"${PHASE_MSG}", "${PRINTF}",
				"${SHCOMMENT}", "${STEP_MSG}",
				"${WARNING_CAT}", "${WARNING_MSG}":
				break
			default:
				shline.line.Warn1("The shell command %q should not be hidden.", cmd)
				Explain(
					"Hidden shell commands do not appear on the terminal or in the log",
					"file when they are executed.  When they fail, the error message",
					"cannot be assigned to the command, which is very difficult to debug.",
					"",
					"It is better to insert ${RUN} at the beginning of the whole command",
					"line.  This will hide the command by default, but shows it when",
					"PKG_DEBUG_LEVEL is set.")
			}
		}
	}

	if contains(hiddenAndSuppress, "-") {
		shline.line.Warn0("Using a leading \"-\" to suppress errors is deprecated.")
		Explain2(
			"If you really want to ignore any errors from this command, append",
			"\"|| ${TRUE}\" to the command.")
	}
}

type SimpleCommandChecker struct {
	shline *ShellLine
	cmd    *MkShSimpleCommand
	strcmd *StrCommand
}

func NewSimpleCommandChecker(shline *ShellLine, cmd *MkShSimpleCommand) *SimpleCommandChecker {
	strcmd := NewStrCommand(cmd)
	return &SimpleCommandChecker{shline, cmd, strcmd}

}

func (scc *SimpleCommandChecker) Check() {
	if G.opts.Debug {
		defer tracecall(scc.strcmd)()
	}

	scc.checkCommandStart()
	scc.checkAbsolutePathnames()
	scc.checkAutoMkdirs()
	scc.checkInstallMulti()
	scc.checkPaxPe()
	scc.checkEchoN()
}

func (scc *SimpleCommandChecker) checkCommandStart() {
	if G.opts.Debug {
		defer tracecall()()
	}

	shellword := scc.strcmd.Name
	switch {
	case shellword == "${RUN}" || shellword == "":
	case scc.handleForbiddenCommand():
	case scc.handleTool():
	case scc.handleCommandVariable():
	case matches(shellword, `^(?::|break|cd|continue|eval|exec|exit|export|read|set|shift|umask|unset)$`):
	case hasPrefix(shellword, "./"): // All commands from the current directory are fine.
	case hasPrefix(shellword, "${PKGSRCDIR"): // With or without the :Q modifier
	case scc.handleComment():
	default:
		if G.opts.WarnExtra && !(G.Mk != nil && G.Mk.indentation.DependsOn("OPSYS")) {
			scc.shline.line.Warn1("Unknown shell command %q.", shellword)
			Explain3(
				"If you want your package to be portable to all platforms that pkgsrc",
				"supports, you should only use shell commands that are covered by the",
				"tools framework.")
		}
	}
}

func (scc *SimpleCommandChecker) handleTool() bool {
	if G.opts.Debug {
		defer tracecall()()
	}

	shellword := scc.strcmd.Name
	tool := G.globalData.Tools.byName[shellword]
	if tool == nil {
		return false
	}

	if !G.Mk.tools[shellword] && !G.Mk.tools["g"+shellword] {
		scc.shline.line.Warn1("The %q tool is used but not added to USE_TOOLS.", shellword)
	}

	if tool.MustUseVarForm {
		scc.shline.line.Warn2("Please use \"${%s}\" instead of %q.", tool.Varname, shellword)
	}

	scc.shline.checkCommandUse(shellword)
	return true
}

func (scc *SimpleCommandChecker) handleForbiddenCommand() bool {
	if G.opts.Debug {
		defer tracecall()()
	}

	shellword := scc.strcmd.Name
	switch path.Base(shellword) {
	case "ktrace", "mktexlsr", "strace", "texconfig", "truss":
		scc.shline.line.Error1("%q must not be used in Makefiles.", shellword)
		Explain3(
			"This command must appear in INSTALL scripts, not in the package",
			"Makefile, so that the package also works if it is installed as a binary",
			"package via pkg_add.")
		return true
	}
	return false
}

func (scc *SimpleCommandChecker) handleCommandVariable() bool {
	if G.opts.Debug {
		defer tracecall()()
	}

	shellword := scc.strcmd.Name
	if m, varname := match1(shellword, `^\$\{([\w_]+)\}$`); m {

		if tool := G.globalData.Tools.byVarname[varname]; tool != nil {
			if !G.Mk.tools[tool.Name] {
				scc.shline.line.Warn1("The %q tool is used but not added to USE_TOOLS.", tool.Name)
			}
			scc.shline.checkCommandUse(shellword)
			return true
		}

		if vartype := scc.shline.mkline.getVariableType(varname); vartype != nil && vartype.basicType.name == "ShellCommand" {
			scc.shline.checkCommandUse(shellword)
			return true
		}

		// When the package author has explicitly defined a command
		// variable, assume it to be valid.
		if G.Pkg != nil && G.Pkg.vardef[varname] != nil {
			return true
		}
	}
	return false
}

func (scc *SimpleCommandChecker) handleComment() bool {
	if G.opts.Debug {
		defer tracecall()()
	}

	shellword := scc.strcmd.Name
	if G.opts.Debug {
		defer tracecall1(shellword)()
	}

	if !hasPrefix(shellword, "#") {
		return false
	}

	semicolon := contains(shellword, ";")
	multiline := scc.shline.line.IsMultiline()

	if semicolon {
		scc.shline.line.Warn0("A shell comment should not contain semicolons.")
	}
	if multiline {
		scc.shline.line.Warn0("A shell comment does not stop at the end of line.")
	}

	if semicolon || multiline {
		Explain(
			"When you split a shell command into multiple lines that are",
			"continued with a backslash, they will nevertheless be converted to",
			"a single line before the shell sees them.  That means that even if",
			"it _looks_ like that the comment only spans one line in the",
			"Makefile, in fact it spans until the end of the whole shell command.",
			"",
			"To insert a comment into shell code, you can write it like this:",
			"",
			"\t"+"${SHCOMMENT} \"The following command might fail; this is ok.\"",
			"",
			"Note that any special characters in the comment are still",
			"interpreted by the shell.")
	}
	return true
}

func (scc *SimpleCommandChecker) checkAbsolutePathnames() {
	if G.opts.Debug {
		defer tracecall()()
	}

	cmdname := scc.strcmd.Name
	isSubst := false
	for _, arg := range scc.strcmd.Args {
		if !isSubst {
			scc.shline.line.CheckAbsolutePathname(arg)
		}
		if false && isSubst && !matches(arg, `"^[\"\'].*[\"\']$`) {
			scc.shline.line.Warn1("Substitution commands like %q should always be quoted.", arg)
			Explain3(
				"Usually these substitution commands contain characters like '*' or",
				"other shell metacharacters that might lead to lookup of matching",
				"filenames and then expand to more than one word.")
		}
		isSubst = cmdname == "${PAX}" && arg == "-s" || cmdname == "${SED}" && arg == "-e"
	}
}

func (scc *SimpleCommandChecker) checkAutoMkdirs() {
	if G.opts.Debug {
		defer tracecall()()
	}

	cmdname := scc.strcmd.Name
	switch {
	case cmdname == "${MKDIR}":
		break
	case cmdname == "${INSTALL}" && scc.strcmd.HasOption("-d"):
		cmdname = "${INSTALL} -d"
	case matches(cmdname, `^\$\{INSTALL_.*_DIR\}$`):
		break
	default:
		return
	}

	for _, arg := range scc.strcmd.Args {
		if !contains(arg, "$$") && !matches(arg, `\$\{[_.]*[a-z]`) {
			if m, dirname := match1(arg, `^(?:\$\{DESTDIR\})?\$\{PREFIX(?:|:Q)\}/(.*)`); m {
				scc.shline.line.Note2("You can use AUTO_MKDIRS=yes or \"INSTALLATION_DIRS+= %s\" instead of %q.", dirname, cmdname)
				Explain(
					"Many packages include a list of all needed directories in their",
					"PLIST file.  In such a case, you can just set AUTO_MKDIRS=yes and",
					"be done.  The pkgsrc infrastructure will then create all directories",
					"in advance.",
					"",
					"To create directories that are not mentioned in the PLIST file, it",
					"is easier to just list them in INSTALLATION_DIRS than to execute the",
					"commands explicitly.  That way, you don't have to think about which",
					"of the many INSTALL_*_DIR variables is appropriate, since",
					"INSTALLATION_DIRS takes care of that.")
			}
		}
	}
}

func (scc *SimpleCommandChecker) checkInstallMulti() {
	if G.opts.Debug {
		defer tracecall()()
	}

	cmd := scc.strcmd

	if hasPrefix(cmd.Name, "${INSTALL_") && hasSuffix(cmd.Name, "_DIR}") {
		prevdir := ""
		for i, arg := range cmd.Args {
			switch {
			case hasPrefix(arg, "-"):
				break
			case i > 0 && (cmd.Args[i-1] == "-m" || cmd.Args[i-1] == "-o" || cmd.Args[i-1] == "-g"):
				break
			default:
				if prevdir != "" {
					scc.shline.line.Warn0("The INSTALL_*_DIR commands can only handle one directory at a time.")
					Explain2(
						"Many implementations of install(1) can handle more, but pkgsrc aims",
						"at maximum portability.")
					return
				}
				prevdir = arg
			}
		}
	}
}

func (scc *SimpleCommandChecker) checkPaxPe() {
	if G.opts.Debug {
		defer tracecall()()
	}

	if scc.strcmd.Name == "${PAX}" && scc.strcmd.HasOption("-pe") {
		scc.shline.line.Warn0("Please use the -pp option to pax(1) instead of -pe.")
		Explain3(
			"The -pe option tells pax to preserve the ownership of the files, which",
			"means that the installed files will belong to the user that has built",
			"the package.")
	}
}

func (scc *SimpleCommandChecker) checkEchoN() {
	if G.opts.Debug {
		defer tracecall()()
	}

	if scc.strcmd.Name == "${ECHO}" && scc.strcmd.HasOption("-n") {
		scc.shline.line.Warn0("Please use ${ECHO_N} instead of \"echo -n\".")
	}
}

type ShellProgramChecker struct {
	shline *ShellLine
}

func (spc *ShellProgramChecker) checkConditionalCd(list *MkShList) {
	if G.opts.Debug {
		defer tracecall()()
	}

	getSimple := func(list *MkShList) *MkShSimpleCommand {
		if len(list.AndOrs) == 1 {
			if len(list.AndOrs[0].Pipes) == 1 {
				if len(list.AndOrs[0].Pipes[0].Cmds) == 1 {
					return list.AndOrs[0].Pipes[0].Cmds[0].Simple
				}
			}
		}
		return nil
	}

	checkConditionalCd := func(cmd *MkShSimpleCommand) {
		if NewStrCommand(cmd).Name == "cd" {
			spc.shline.line.Error0("The Solaris /bin/sh cannot handle \"cd\" inside conditionals.")
			Explain3(
				"When the Solaris shell is in \"set -e\" mode and \"cd\" fails, the",
				"shell will exit, no matter if it is protected by an \"if\" or the",
				"\"||\" operator.")
		}
	}

	(*MkShWalker).Walk(nil, list, func(node interface{}) {
		if cmd, ok := node.(*MkShIfClause); ok {
			for _, cond := range cmd.Conds {
				if simple := getSimple(cond); simple != nil {
					checkConditionalCd(simple)
				}
			}
		}
		if cmd, ok := node.(*MkShLoopClause); ok {
			if simple := getSimple(cmd.Cond); simple != nil {
				checkConditionalCd(simple)
			}
		}
	})
}

func (spc *ShellProgramChecker) checkWords(words []*ShToken, checkQuoting bool) {
	if G.opts.Debug {
		defer tracecall()()
	}

	for _, word := range words {
		spc.checkWord(word, checkQuoting)
	}
}

func (spc *ShellProgramChecker) checkWord(word *ShToken, checkQuoting bool) {
	if G.opts.Debug {
		defer tracecall(word.MkText)()
	}

	spc.shline.CheckWord(word.MkText, checkQuoting)
}

func (scc *ShellProgramChecker) checkPipeExitcode(line *Line, pipeline *MkShPipeline) {
	if G.opts.Debug {
		defer tracecall()()
	}

	if G.opts.WarnExtra && len(pipeline.Cmds) > 1 {
		line.Warn0("The exitcode of the left-hand-side command of the pipe operator is ignored.")
		Explain(
			"In a shell command like \"cat *.txt | grep keyword\", if the command",
			"on the left side of the \"|\" fails, this failure is ignored.",
			"",
			"If you need to detect the failure of the left-hand-side command, use",
			"temporary files to save the output of the command.")
	}
}

func (scc *ShellProgramChecker) checkSetE(list *MkShList, eflag *bool) {
	if G.opts.Debug {
		defer tracecall()()
	}

	// Disabled until the shell parser can recognize "command || exit 1" reliably.
	if false && G.opts.WarnExtra && !*eflag && "the current token" == ";" {
		*eflag = true
		scc.shline.line.Warn1("Please switch to \"set -e\" mode before using a semicolon (the one after %q) to separate commands.", "previous token")
		Explain(
			"Normally, when a shell command fails (returns non-zero), the",
			"remaining commands are still executed.  For example, the following",
			"commands would remove all files from the HOME directory:",
			"",
			"\tcd \"$HOME\"; cd /nonexistent; rm -rf *",
			"",
			"To fix this warning, you can:",
			"",
			"* insert ${RUN} at the beginning of the line",
			"  (which among other things does \"set -e\")",
			"* insert \"set -e\" explicitly at the beginning of the line",
			"* use \"&&\" instead of \";\" to separate the commands")
	}
}

// Some shell commands should not be used in the install phase.
func (shline *ShellLine) checkCommandUse(shellcmd string) {
	if G.opts.Debug {
		defer tracecall()()
	}

	if G.Mk == nil || !matches(G.Mk.target, `^(?:pre|do|post)-install$`) {
		return
	}

	line := shline.line
	switch shellcmd {
	case "${INSTALL}",
		"${INSTALL_DATA}", "${INSTALL_DATA_DIR}",
		"${INSTALL_LIB}", "${INSTALL_LIB_DIR}",
		"${INSTALL_MAN}", "${INSTALL_MAN_DIR}",
		"${INSTALL_PROGRAM}", "${INSTALL_PROGRAM_DIR}",
		"${INSTALL_SCRIPT}",
		"${LIBTOOL}",
		"${LN}",
		"${PAX}":
		return

	case "sed", "${SED}",
		"tr", "${TR}":
		line.Warn1("The shell command %q should not be used in the install phase.", shellcmd)
		Explain3(
			"In the install phase, the only thing that should be done is to",
			"install the prepared files to their final location.  The file's",
			"contents should not be changed anymore.")

	case "cp", "${CP}":
		line.Warn0("${CP} should not be used to install files.")
		Explain(
			"The ${CP} command is highly platform dependent and cannot overwrite",
			"read-only files.  Please use ${PAX} instead.",
			"",
			"For example, instead of",
			"\t${CP} -R ${WRKSRC}/* ${PREFIX}/foodir",
			"you should use",
			"\tcd ${WRKSRC} && ${PAX} -wr * ${PREFIX}/foodir")
	}
}

// Example: "word1 word2;;;" => "word1", "word2", ";;", ";"
func splitIntoShellTokens(line *Line, text string) (tokens []string, rest string) {
	if G.opts.Debug {
		defer tracecall(line, text)()
	}

	word := ""
	emit := func() {
		if word != "" {
			tokens = append(tokens, word)
			word = ""
		}
	}
	p := NewShTokenizer(line, text, false)
	atoms := p.ShAtoms()
	q := shqPlain
	for _, atom := range atoms {
		q = atom.Quoting
		if atom.Type == shtSpace && q == shqPlain {
			emit()
		} else if atom.Type == shtWord || atom.Type == shtVaruse || atom.Quoting != shqPlain {
			word += atom.MkText
		} else {
			emit()
			tokens = append(tokens, atom.MkText)
		}
	}
	emit()
	return tokens, word + p.mkp.Rest()
}

// Example: "word1 word2;;;" => "word1", "word2;;;"
// Compare devel/bmake/files/str.c, function brk_string.
func splitIntoMkWords(line *Line, text string) (words []string, rest string) {
	if G.opts.Debug {
		defer tracecall(line, text)()
	}

	p := NewShTokenizer(line, text, false)
	atoms := p.ShAtoms()
	word := ""
	for _, atom := range atoms {
		if atom.Type == shtSpace && atom.Quoting == shqPlain {
			words = append(words, word)
			word = ""
		} else {
			word += atom.MkText
		}
	}
	if word != "" && atoms[len(atoms)-1].Quoting == shqPlain {
		words = append(words, word)
		word = ""
	}
	return words, word + p.mkp.Rest()
}