-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
1446 lines (1284 loc) · 39.3 KB
/
main.go
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
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"crypto/sha256"
"debug/buildinfo"
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime/debug"
"slices"
"strconv"
"strings"
"sync"
"github.com/blang/semver/v4"
"github.com/fatih/color"
"github.com/goretk/gore"
flag "github.com/spf13/pflag"
)
const (
cmdLinePkg = "command-line-arguments"
goVersionPrefix = "go version go"
dockerGoRoot = "/usr/local/go"
dockerGoModCache = "/go-mod-cache"
dockerBuildDir = "/build-dir"
dockerGoBuildCache = "/go-build-cache"
dockerfileFrom = "FROM golang:%s-alpine"
gitDockerfileTmpl = `
RUN apk add --update-cache git \
&& rm -rf /var/cache/apk/* \
&& git config --global --add safe.directory '*'`
goRootDockerfileTmpl = `
ARG GOROOT=%s/
ENV PATH=${GOROOT}bin:${PATH}
RUN mkdir -p "${GOROOT}" \
&& mv /usr/local/go/* "${GOROOT}" \
&& rmdir /usr/local/go
ENV GOROOT=`
reproSuffix = ".repro"
)
const (
successCode int = iota
errCode
sizeDifferentCode
hashesDifferentCode
buildIDSameCode
)
var (
infoColor = color.New(color.FgBlue)
warnColor = color.New(color.FgYellow)
errColor = color.New(color.FgRed)
almostColor = color.New(color.FgMagenta)
successColor = color.New(color.FgGreen)
extraFlags []string
dryRun bool
goDebug bool
noGoGC bool
verbose bool
goEnvVars = []string{
"HOME",
"PATH",
}
failReasons []failReason
)
func usage() {
fmt.Fprintf(os.Stderr, `
gorepro creates reproducible Go binaries.
gorepro [flags] binary
It does this by creating a "go build" command from the embedded build
metadata in the specified Go binary that should produce an identical
binary. gorepro will notify you if the specified binary was built in
such a way that makes reproducing it unlikely, or your build environment
is not suitable for reproducing.
If gorepro detects that a different version of Go was used to create
the specified binary than what is currently installed, gorepro will
build in a docker container with the correct Go version needed to
reproduce the specified binary. Note that gorepro requires that
binaries to reproduce be built with Go 1.18 or later as earlier
versions do not embed build metadata.
gorepro requires that it be run in the directory where the source code
for the specified binary exists. Depending on how the specified binary
was built, gorepro may require that it be run inside a cloned Git
repository that the specified binary was built from. The binary to
reproduce is not required to be in any specific directory however.
For example, to reproduce a Go binary:
gorepro ./gobin
To specify required build arguments that are not detected:
gorepro -b=-buildmode=pie ./gobin
To handle multiple undetected build arguments, -b can be passed multiple
times, and can accept multiple comma-separated flags as well:
gorepro -b=-buildmode=exe,-cover -b="-ldflags=-s -w" ./gobin
gorepro accepts the following flags:
`[1:])
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, `
For more information, see https://github.com/capnspacehook/gorepro.
`[1:])
}
type failReason struct {
reason string
retCodes []int
}
func addFailReason(retCodes []int, format string, a ...any) {
failReasons = append(failReasons,
failReason{
reason: fmt.Sprintf(format, a...),
retCodes: retCodes,
},
)
}
func verbosef(format string, a ...any) {
if !verbose {
return
}
infoColor.Fprintf(os.Stderr, format, a...)
infoColor.Fprintln(os.Stderr)
}
func infof(format string, a ...any) {
if dryRun {
return
}
infoColor.Printf(format, a...)
infoColor.Println()
}
func warnf(format string, a ...any) {
warnColor.Printf(format, a...)
warnColor.Println()
}
func errf(format string, a ...any) {
errColor.Printf(format, a...)
errColor.Println()
}
func almostf(format string, a ...any) {
almostColor.Printf(format, a...)
almostColor.Println()
}
func successf(format string, a ...any) {
successColor.Printf(format, a...)
successColor.Println()
}
func parseVersion(version string) (semver.Version, error) {
if i := strings.Index(version, "beta"); i != -1 {
version = version[i-1:] + "-" + version[:i]
} else if i := strings.Index(version, "rc"); i != -1 {
version = version[i-1:] + "-" + version[:i]
} else if strings.Count(version, ".") == 1 {
version += ".0"
}
ver, err := semver.Parse(version)
if err != nil {
return semver.Version{}, err
}
return ver, err
}
func getBuildID(ctx context.Context, file string) ([]byte, error) {
return runCommand(ctx, "go", "tool", "buildid", file)
}
func runCommand(ctx context.Context, name string, arg ...string) ([]byte, error) {
var buf bytes.Buffer
var w io.Writer = &buf
if verbose {
w = io.MultiWriter(w, os.Stderr)
}
cmd := exec.CommandContext(ctx, name, arg...)
verbosef("running command: %s", cmd)
cmd.Stdout = w
cmd.Stderr = w
err := cmd.Run()
if err != nil {
return buf.Bytes(), err
}
return buf.Bytes(), nil
}
func main() {
os.Exit(mainRetCode())
}
type errJustExit int
func (e errJustExit) Error() string { return fmt.Sprintf("exit: %d", e) }
type errWithRetCode struct {
error
code int
}
// unparam complains that hashesDifferentCode is only ever passed to the code parameter
//
//nolint:unparam
func errWithCode(code int, err error) error {
return errWithRetCode{
error: err,
code: code,
}
}
func mainRetCode() int {
err := mainErr()
if err == nil {
if dryRun {
fmt.Println()
}
return successCode
}
var errRetCode errJustExit
var errAndRetCode errWithRetCode
var retCode int
if errors.As(err, &errRetCode) {
retCode = int(errRetCode)
} else if errors.As(err, &errAndRetCode) {
retCode = errAndRetCode.code
if retCode == errCode {
errf("error %v", errAndRetCode)
}
} else {
retCode = errCode
errf("error %v", err)
return retCode
}
if retCode > errCode && len(failReasons) != 0 {
var sb strings.Builder
var reasonsListed int
sb.WriteString(warnColor.Sprint("reasons reproducing may have failed:\n"))
for _, reason := range failReasons {
// Skip warnings that don't apply to the returned error code.
// Warnings that
if reason.retCodes != nil && !slices.Contains(reason.retCodes, retCode) {
continue
}
sb.WriteString(warnColor.Sprintf(" - %s\n", reason.reason))
reasonsListed++
}
if reasonsListed != 0 {
fmt.Print(sb.String())
}
}
return retCode
}
func mainErr() error {
flag.Usage = usage
flag.StringSliceVarP(&extraFlags, "build-flags", "b", nil, "extra build flags that are needed to reproduce but aren't detected, comma separated")
flag.BoolVarP(&dryRun, "dry-run", "d", false, "print build commands instead of running them")
flag.BoolVarP(&goDebug, "godebug", "g", false, "print very verbose debug information from the Go compiler")
flag.BoolVarP(&noGoGC, "no-go-gc", "s", false, "trade memory usage for speed by disabling the garbage collector when compiling")
flag.BoolVarP(&verbose, "verbose", "v", false, "print commands being run and verbose information")
flag.Parse()
if dryRun && verbose {
return fmt.Errorf("-d and -v are mutually exclusive")
}
// ensure the go command is present
if _, err := exec.LookPath("go"); err != nil {
return fmt.Errorf(`finding "go": %w`, err)
}
if flag.NArg() == 0 {
usage()
return errJustExit(errCode)
} else if flag.NArg() > 1 {
fmt.Fprintf(os.Stderr, "only one binary can be reproduced at a time\n\nusage:\n\n")
usage()
return errJustExit(errCode)
}
binary := flag.Arg(0)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
// read the binary's build info
info, err := buildinfo.ReadFile(binary)
if err != nil {
return fmt.Errorf("parsing build metadata: %w", err)
}
binVersionStr := info.GoVersion
if len(binVersionStr) > 2 {
binVersionStr = binVersionStr[2:]
}
binVer, err := parseVersion(binVersionStr)
if err != nil {
return fmt.Errorf("parsing go version of %q: %w", binary, err)
}
// check if binary can be reproduced
if binVer.Minor < 18 {
return fmt.Errorf("%q was built with Go %s, only Go 1.18 or newer embeds build metadata that is required by gorepro",
binary,
binVersionStr,
)
}
if len(info.Settings) == 0 {
return fmt.Errorf("no build metadata present in %q, reproducing is possible but not supported by gorepro", binary)
}
if binVer.Minor < 20 {
addFailReason(
nil,
`%q was built with Go %s which doesn't include what "-buildmode" was set to, a non default build mode may have been used`,
binary,
binVersionStr,
)
}
file, err := gore.Open(binary)
if err != nil {
return err
}
defer file.Close()
// check if source files for the main module need to be explicitly
// passed
var mainSrcFiles []string
if info.Path == cmdLinePkg {
p, err := file.GetPackages()
if err != nil {
return err
}
for _, pkg := range p {
if pkg.Name == "main" {
srcFiles := file.GetSourceFiles(pkg)
for _, srcFile := range srcFiles {
mainSrcFiles = append(mainSrcFiles, srcFile.Name)
}
break
}
}
} else if info.Main.Version != "" && info.Main.Version != "(devel)" {
return fmt.Errorf(`%q was built using "go install", reproducing is possible but not supported by gorepro`, binary)
}
// ensure main module source files exist
if len(mainSrcFiles) != 0 {
for _, file := range mainSrcFiles {
if _, err := os.Stat(file); err != nil {
if errors.Is(err, os.ErrNotExist) {
return fmt.Errorf(`%q was built by passing %q to "go build", but that file couldn't be found; rerun gorepro in the directory with %q`,
binary,
file,
file,
)
}
return fmt.Errorf("reading build file: %w", err)
}
}
}
// get the version of the go command, we may have to download
// a different version if it's not available
out, err := runCommand(ctx, "go", "version")
if err != nil {
return fmt.Errorf(`running "go version": %w`, err)
}
if len(out) < len(goVersionPrefix) {
return fmt.Errorf(`malformed "go version" output`)
}
out = out[len(goVersionPrefix):]
i := bytes.IndexByte(out, ' ')
if i == -1 {
return fmt.Errorf(`malformed "go version" output`)
}
goVersionStr := string(out[:i])
goVer, err := parseVersion(goVersionStr)
if err != nil {
return fmt.Errorf("parsing version of local Go toolchain: %w", err)
}
// build command that will hopefully reproduce the binary from its
// embedded build information
var buildArgs []string
var env []string
var buildModeSet bool
var buildIDExplicitlySet bool
var trimpathFound bool
var vcsUsed string
var vcsRev string
var vcsModified bool
for _, setting := range info.Settings {
switch setting.Key {
case "-asmflags", "-buildmode", "-gcflags", "-ldflags", "-tags":
if setting.Key == "-ldflags" {
if strings.Contains(setting.Value, "-buildid") {
buildIDExplicitlySet = true
}
}
value := setting.Value
if setting.Key == "-buildmode" {
buildModeSet = true
if setting.Value == "exe" {
infof(`passing "-buildmode=default" instead of "-buildmode=exe"`)
value = "default"
addFailReason(
nil,
`"-buildmode=exe" is in the embedded build metadata of %q but it's impossible to tell if "-buildmode=default" was passed at build time instead.
As explicitly passing "-buildmode=exe" is uncommon, "-buildmode=default" was used for this build instead. Trying again with "gorepro -b=-buildmode=exe ..." may reproduce the binary.`,
binary,
)
}
}
if dryRun {
buildArgs = append(buildArgs, fmt.Sprintf(`%s=%q`, setting.Key, value))
} else {
buildArgs = append(buildArgs, fmt.Sprintf("%s=%s", setting.Key, value))
}
case "-compiler":
if setting.Value != "gc" {
//lint:ignore ST1005 'Go' should be capitalized consistently
return fmt.Errorf("Go compiler %s was used to build %s, only the building with the official Go compiler gc is supported",
setting.Value,
binary,
)
}
case "-trimpath":
trimpathFound = true
if binVer.Minor <= 21 {
addFailReason(
nil,
`Go <= 1.21 was used to build %q and "-trimpath" was set, if "-ldflags" was set at build time it won't be in the embedded build data`,
binary,
)
}
buildArgs = append(buildArgs, setting.Key)
case "vcs":
vcsUsed = setting.Value
case "vcs.modified":
if setting.Value == "true" {
vcsModified = true
addFailReason(
nil,
"the Git repo %q was built in had uncommitted file(s) when it was built, you may be trying to build with different source code",
binary,
)
}
case "vcs.revision":
vcsRev = setting.Value
buildArgs = append(buildArgs, "-buildvcs=true")
case "CGO_ENABLED":
if setting.Value != "0" {
return fmt.Errorf("%q was built with CGO enabled, reproducing is possible but not supported by gorepro", binary)
}
env = append(env, "CGO_ENABLED=0")
case "GOAMD64", "GOARCH", "GOARM", "GOEXPERIMENT", "GOMIPS", "GOMIPS64", "GOOS", "GOPPC64", "GOWASM":
env = append(env, fmt.Sprintf("%s=%s", setting.Key, setting.Value))
}
}
if binVer.Minor < 20 && !buildModeSet {
addFailReason(
[]int{buildIDSameCode},
`"-buildmode" wasn't in the embedded build metadata of %q but it may have been set to "-buildmode=exe";
trying again with "gorepro -b=-buildmode=exe ..." may reproduce the binary`,
binary,
)
}
// try and determine if -trimpath was set and gather necessary information
// needed to reproduce if it wasn't
var dockerInfo *dockerBuildInfo
if !trimpathFound {
setTrimpath, di, err := checkTrimpath(binVer, file, binary)
if err != nil {
return err
}
if setTrimpath {
buildArgs = append(buildArgs, "-trimpath")
}
dockerInfo = di
}
// if the binary was built with VCS info embedded, check that our
// build env is compatible and if not make it so
if vcsUsed != "" {
tempFile, checkedOut, err := checkVCS(ctx, vcsUsed, vcsRev, vcsModified, binary)
if err != nil {
return err
}
if tempFile != "" {
defer func() {
if err := os.Remove(tempFile); err != nil {
warnf("error removing temporary file: %v", err)
}
}()
}
if checkedOut {
if dryRun {
defer fmt.Print("; git checkout -q -")
} else {
defer func() {
_, _ = runCommand(ctx, "git", "checkout", "-q", "-")
}()
}
}
} else {
buildArgs = append(buildArgs, "-buildvcs=false")
}
if err := findGoRoot(ctx, binary, file, dockerInfo); err != nil {
return err
}
// if the local version of Go isn't the same as the version that
// built the binary, building in Docker isn't needed and the local
// version of Go is >= 1.21.0, use GOTOOLCHAIN to ensure the correct
// Go version will be used instead.
if binVersionStr != goVersionStr && dockerInfo == nil && goVer.Minor >= 21 {
env = append(env, fmt.Sprintf("GOTOOLCHAIN=go%s", binVersionStr))
}
if dockerInfo != nil {
if err := fillDockerBuildInfo(dockerInfo); err != nil {
return err
}
}
// if the same build flags are passed twice, the last flag will
// overwrite the flags before
if len(extraFlags) != 0 {
// if we are printing this command quote all extra flags that
// contain spaces
if dryRun {
for i, extraFlag := range extraFlags {
if strings.ContainsRune(extraFlag, ' ') {
extraFlags[i] = strconv.Quote(extraFlags[i])
}
}
}
buildArgs = append(buildArgs, extraFlags...)
}
// try to reproduce the binary
ourBinary := binary + reproSuffix
err = attemptRepro(ctx, binary, ourBinary, vcsUsed != "", binVer, env, buildArgs, mainSrcFiles, info, dockerInfo)
if err != nil {
return err
}
if dryRun {
return nil
}
// check that file sizes match
binfi, err := os.Stat(binary)
if err != nil {
return fmt.Errorf("reading file: %w", err)
}
ourBinfi, err := os.Stat(ourBinary)
if err != nil {
return fmt.Errorf("reading file: %w", err)
}
if binfi.Size() != ourBinfi.Size() {
errf("failed to reproduce: file sizes don't match")
return errJustExit(sizeDifferentCode)
}
// check that file hashes match
binf, err := os.Open(binary)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer binf.Close()
ourBinf, err := os.Open(ourBinary)
if err != nil {
return fmt.Errorf("opening file: %w", err)
}
defer ourBinf.Close()
binHash := sha256.New()
if _, err := io.Copy(binHash, binf); err != nil {
return fmt.Errorf("hashing %q: %w", binary, err)
}
ourBinHash := sha256.New()
if _, err := io.Copy(ourBinHash, ourBinf); err != nil {
return fmt.Errorf("hashing %q: %w", ourBinary, err)
}
binSum, ourBinSum := binHash.Sum(nil), ourBinHash.Sum(nil)
infof("%x %q", binSum, binary)
infof("%x %q", ourBinSum, ourBinary)
if !bytes.Equal(binSum, ourBinSum) {
errf("failed to reproduce: file hashes don't match")
// if the build ID was explicitly set via a linker flag, don't
// check the differences between build IDs, they will be the same
if buildIDExplicitlySet {
return errJustExit(hashesDifferentCode)
}
binBuildID, err := getBuildID(ctx, binary)
if err != nil {
return errWithCode(hashesDifferentCode, fmt.Errorf("getting build ID of %q: %w", binary, err))
}
if _, err := binf.Seek(0, io.SeekStart); err != nil {
return errWithCode(hashesDifferentCode, fmt.Errorf("seeking to beginning of %q: %w", binary, err))
}
ourBinBuildID, err := getBuildID(ctx, ourBinary)
if err != nil {
return errWithCode(hashesDifferentCode, fmt.Errorf("getting build ID of %q: %w", ourBinary, err))
}
if _, err := ourBinf.Seek(0, io.SeekStart); err != nil {
return errWithCode(hashesDifferentCode, fmt.Errorf("seeking to beginning of %q: %w", ourBinary, err))
}
// if the build IDs are different but the rest of the binaries'
// contents match tell the user
restSame, err := onlyBuildIDDifferent(binf, ourBinf, binBuildID, ourBinBuildID)
if err != nil {
return errWithCode(hashesDifferentCode, fmt.Errorf("comparing binaries: %w", err))
}
if restSame {
almostf("however, only the build ID differs between binaries, binaries are almost the same")
return errJustExit(buildIDSameCode)
} else {
binBuildIDParts := bytes.Split(binBuildID, []byte("/"))
ourBinBuildIDParts := bytes.Split(ourBinBuildID, []byte("/"))
if bytes.Equal(binBuildIDParts[2], ourBinBuildIDParts[2]) {
almostf("the main module's compiled code is the same between binaries")
}
}
return errJustExit(hashesDifferentCode)
}
successf("reproduced successfully! new binary is at %q", ourBinary)
return nil
}
type dockerBuildInfo struct {
goRoot string
goModCache string
buildDir string
localCodeDir string
containerCodeDir string
}
func checkTrimpath(binVer semver.Version, file *gore.GoFile, binary string) (bool, *dockerBuildInfo, error) {
// Go 1.19+ adds -trimpath to the build metadata, on earlier Go
// versions we can't always know for sure if it was passed
trimpathUnknown := true
if binVer.Minor >= 19 {
trimpathUnknown = false
}
// detect if -trimpath was passed by inspecting the binary's GOROOT
goRoot, err := file.GetGoRoot()
if err != nil {
if errors.Is(err, gore.ErrNoGoRootFound) {
// if we don't know if -trimpath was set
if trimpathUnknown {
addFailReason(
nil,
`"-trimpath" may not have been set when building %q, it could not be detected from embedded build metadata`,
binary,
)
return true, nil, nil
}
} else {
return false, nil, fmt.Errorf("finding GOROOT of %q: %w", binary, err)
}
}
// GOROOT will be 'go' if -trimpath was set
if goRoot == "go" {
return true, nil, nil
}
if goRoot != "" {
trimpathUnknown = false
}
// find GOMODCACHE
findGoModCache := func(pkgs []*gore.Package) string {
for _, pkg := range pkgs {
name := pkg.Name
// get first part of package name
if strings.Contains(name, "/") {
s, _, ok := strings.Cut(pkg.Name, "/")
if !ok {
continue
}
name = s
}
// get dir before package name
path, _, ok := strings.Cut(pkg.Filepath, name)
if !ok {
continue
}
// package is stdlib, continue
if strings.HasPrefix(path, goRoot) {
continue
}
return path
}
return ""
}
thirdPartyPkgs, err := file.GetVendors()
if err != nil {
return false, nil, fmt.Errorf("getting packages of %q: %w", binary, err)
}
goModCache := findGoModCache(thirdPartyPkgs)
if goModCache == "" {
unknownPkgs, err := file.GetUnknown()
if err != nil {
return false, nil, fmt.Errorf("getting packages of %q: %w", binary, err)
}
goModCache = findGoModCache(unknownPkgs)
}
// get the build dir the binary was built in
mainPkgs, err := file.GetPackages()
if err != nil {
return false, nil, fmt.Errorf("getting packages of %q: %w", binary, err)
}
var buildDir string
for _, pkg := range mainPkgs {
if pkg.Name == "main" {
buildDir = pkg.Filepath
break
}
}
cwd, err := os.Getwd()
if err != nil {
return false, nil, err
}
if cwd != buildDir && trimpathUnknown {
addFailReason(
nil,
`"-trimpath" may not have been set when building %q, and %q was used as the build directory while you are using %q`,
binary,
buildDir,
cwd,
)
}
return false, &dockerBuildInfo{
goModCache: goModCache,
buildDir: buildDir,
}, nil
}
func trimNewline(b []byte) []byte {
if len(b) != 0 && b[len(b)-1] == '\n' {
return b[:len(b)-1]
}
return b
}
func min(i, j int) int {
if i < j {
return i
}
return j
}
func checkVCS(ctx context.Context, vcsUsed, vcsRev string, vcsModified bool, binary string) (string, bool, error) {
var ok bool
var tempFileName string
// if we didn't return successfully and a temp file was created, delete
// it so the caller doesn't have to worry about it
defer func() {
if tempFileName != "" && !ok {
if err := os.Remove(tempFileName); err != nil {
warnf("error removing temporary file: %v", err)
}
}
}()
if vcsUsed != "git" {
addFailReason(nil, "version control system %s isn't supported by gorepro", vcsUsed)
return "", false, nil
}
if _, err := exec.LookPath("git"); err != nil {
return "", false, fmt.Errorf(`could not find "git": %w`, err)
}
gitStatus, err := runCommand(ctx, "git", "status", "--porcelain=v1")
if err != nil {
if strings.HasPrefix(string(gitStatus), "fatal: not a git repository") {
return "", false, fmt.Errorf("%q was built in a Git repo, but gorepro wasn't run in one; reproducing will fail", binary)
}
return "", false, fmt.Errorf("getting Git status: %s %w", gitStatus, err)
}
// if there are new/modified Go source files present, chances are
// the source code won't match what the original binary was compiled
// with
if len(gitStatus) != 0 {
scanner := bufio.NewScanner(bytes.NewReader(gitStatus))
for scanner.Scan() {
// separate status symbol from file path
// lines look like this:
// M main.go
// ?? new.go
txt := scanner.Text()
if len(txt) < 4 {
return "", false, fmt.Errorf(`error parsing "git status --porcelain: line too short: %s`, txt)
}
_, file, ok := strings.Cut(txt[1:], " ")
if !ok {
return "", false, fmt.Errorf(`error parsing "git status --porcelain: line malformed: %s`, txt)
}
_, file = filepath.Split(file)
if strings.HasSuffix(file, ".go") || file == "go.mod" || file == "go.sum" {
addFailReason(
nil,
"there is at least one new or modified Go file in the local Git repo, source code may differ from what %q was built with",
binary,
)
break
}
}
if err := scanner.Err(); err != nil {
return "", false, fmt.Errorf(`error parsing "git status" output: %w`, err)
}
}
if !dryRun && vcsModified && len(gitStatus) == 0 {
infof("%q was built in a dirty Git repo but the local Git repo is clean; creating a temporary file to make local Git repo dirty",
binary,
)
tempFile, err := os.CreateTemp(".", "*")
if err != nil {
return "", false, fmt.Errorf("creating temporary file: %w", err)
}
tempFileName = tempFile.Name()
tempFile.Close()
} else if !vcsModified && len(gitStatus) != 0 {
return "", false, fmt.Errorf("%q was built in a clean Git repo, and the local Git repo isn't clean; reproducing will fail", binary)
}
gitShow, err := runCommand(ctx, "git", "-c", "log.showsignature=false", "show", "-s", "--format=%H")
if err != nil {
return "", false, fmt.Errorf("getting latest git commit: %s %w", gitShow, err)
}
latestCommit := string(trimNewline(gitShow))
var checkedOut bool
if vcsRev != latestCommit {
checkedOut = true
if dryRun {
fmt.Printf("git checkout -q %s; ", vcsRev)
} else {
infof("%q was built on commit %s but we're on %s, checking out correct commit", binary, vcsRev, latestCommit)
out, err := runCommand(ctx, "git", "checkout", "-q", vcsRev)
if err != nil {
return "", false, fmt.Errorf("checking out git commit: %s %w", out, err)
}
}
}
ok = true
return tempFileName, checkedOut, nil
}
func findGoRoot(ctx context.Context, binary string, file *gore.GoFile, dockerInfo *dockerBuildInfo) error {
// if we already need to build in a Docker container ensure the
// GOROOT used will be the same was what was used to build the
// binary
binGoRoot, err := file.GetGoRoot()
if err != nil {
if errors.Is(err, gore.ErrNoGoRootFound) {
addFailReason(
[]int{sizeDifferentCode, hashesDifferentCode},
"the GOROOT of %q couldn't be found, a incorrect GOROOT may have been used",
binary,
)
return nil
}
return fmt.Errorf("finding GOROOT of %q: %w", binary, err)
}
if dockerInfo != nil && binGoRoot != dockerGoRoot {
dockerInfo.goRoot = binGoRoot
return nil
}
// if the binary's GOROOT doesn't match our local GOROOT we need
// to build in a Docker container to ensure the correct GOROOT
// is used
goRoot, err := runCommand(ctx, "go", "env", "GOROOT")
if err != nil {
return fmt.Errorf("getting GOROOT: %w", err)
}
goRoot = trimNewline(goRoot)
if string(goRoot) != binGoRoot {
dockerInfo = &dockerBuildInfo{
goRoot: binGoRoot,
}
}
return nil
}
func fillDockerBuildInfo(dockerInfo *dockerBuildInfo) error {
if dockerInfo.goRoot == "" {
dockerInfo.goRoot = dockerGoRoot
}
if dockerInfo.goModCache == "" {
dockerInfo.goModCache = dockerGoModCache
}
if dockerInfo.buildDir == "" {
dockerInfo.buildDir = dockerBuildDir
}
cwd, err := os.Getwd()
if err != nil {
return err
}
dockerInfo.localCodeDir = cwd
// figure out where module starts (where go.mod is) and mount accordingly
goModDir, err := getGoModDir()
if err != nil {
return err
}
if goModDir != "" {
dockerInfo.localCodeDir = goModDir
}
// ensure the container code dir is set correctly so the source code
// is mounted at the appropriate local dir
dockerInfo.containerCodeDir = dockerInfo.buildDir
// if we aren't in the root dir of the module, adjust the
// container code dir accordingly
if dockerInfo.localCodeDir != cwd {
sep := string(filepath.Separator)
buildDirParts := strings.Split(dockerInfo.buildDir, sep)
cwdParts := strings.Split(cwd, sep)
for i := 1; i < min(len(buildDirParts), len(cwdParts)); i++ {
if buildDirParts[len(buildDirParts)-i] != cwdParts[len(cwdParts)-i] {
// TODO: if buildDir doesn't change, probably should report error to user
// they probably aren't in correct dir
dockerInfo.containerCodeDir = sep + filepath.Join(buildDirParts[:i-1]...)
return nil
}