cmd/link/internal/ld: don't leave files open in a loop

Noticed by Ingo Oeser in his review of CL 168321.

Change-Id: I2f39db675a7c22b395062a11903657a9d0d1956d
Reviewed-on: https://go-review.googlesource.com/c/go/+/168560
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Cherry Zhang <cherryyz@google.com>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
This commit is contained in:
Elias Naur 2019-03-21 16:41:48 +01:00
parent 4a52267574
commit 804a4024ec

View file

@ -694,14 +694,20 @@ func Asmbmacho(ctxt *Link) {
}
}
}
load, err := hostobjMachoPlatform(hostobj)
if err != nil {
Exitf("%v", err)
foundLoad := false
for _, h := range hostobj {
load, err := hostobjMachoPlatform(&h)
if err != nil {
Exitf("%v", err)
}
if load != nil {
ml := newMachoLoad(ctxt.Arch, load.cmd.type_, uint32(len(load.cmd.data)))
copy(ml.data, load.cmd.data)
foundLoad = true
break
}
}
if load != nil {
ml := newMachoLoad(ctxt.Arch, load.cmd.type_, uint32(len(load.cmd.data)))
copy(ml.data, load.cmd.data)
} else if ctxt.LinkMode == LinkInternal {
if !foundLoad && ctxt.LinkMode == LinkInternal {
// For lldb, must say LC_VERSION_MIN_MACOSX or else
// it won't know that this Mach-O binary is from OS X
// (could be iOS or WatchOS instead).
@ -1027,29 +1033,20 @@ func Machoemitreloc(ctxt *Link) {
}
// hostobjMachoPlatform returns the first platform load command found
// in the host objects, if any.
func hostobjMachoPlatform(hostobj []Hostobj) (*MachoPlatformLoad, error) {
for _, h := range hostobj {
f, err := os.Open(h.file)
if err != nil {
return nil, fmt.Errorf("%s: failed to open host object: %v\n", h.file, err)
}
defer f.Close()
sr := io.NewSectionReader(f, h.off, h.length)
m, err := macho.NewFile(sr)
if err != nil {
// Not a valid Mach-O file.
return nil, nil
}
load, err := peekMachoPlatform(m)
if err != nil {
return nil, err
}
if load != nil {
return load, nil
}
// in the host object, if any.
func hostobjMachoPlatform(h *Hostobj) (*MachoPlatformLoad, error) {
f, err := os.Open(h.file)
if err != nil {
return nil, fmt.Errorf("%s: failed to open host object: %v\n", h.file, err)
}
return nil, nil
defer f.Close()
sr := io.NewSectionReader(f, h.off, h.length)
m, err := macho.NewFile(sr)
if err != nil {
// Not a valid Mach-O file.
return nil, nil
}
return peekMachoPlatform(m)
}
// peekMachoPlatform returns the first LC_VERSION_MIN_* or LC_BUILD_VERSION