From fd7666881beb9bb598e8e4e0c2ba9cd3a9ee4466 Mon Sep 17 00:00:00 2001 From: Cherry Zhang Date: Wed, 8 Apr 2020 19:45:12 -0400 Subject: [PATCH] [dev.link] cmd/link: add methods for adding relocations in Reloc2 format This is in prepration of removing the old loader.Reloc. This also introduces a way of adding a slice of relocations more efficiently (will be used in the next CL). Change-Id: I3eaee7fb3a3e102a8670990f4a31c40d0b17b8c2 Reviewed-on: https://go-review.googlesource.com/c/go/+/227761 Run-TryBot: Cherry Zhang TryBot-Result: Gobot Gobot Reviewed-by: Than McIntosh --- src/cmd/link/internal/loader/symbolbuilder.go | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/cmd/link/internal/loader/symbolbuilder.go b/src/cmd/link/internal/loader/symbolbuilder.go index 3d5dc87616..8f14298543 100644 --- a/src/cmd/link/internal/loader/symbolbuilder.go +++ b/src/cmd/link/internal/loader/symbolbuilder.go @@ -10,6 +10,7 @@ import ( "cmd/internal/sys" "cmd/link/internal/sym" "fmt" + "sort" ) // SymbolBuilder is a helper designed to help with the construction @@ -141,6 +142,38 @@ func (sb *SymbolBuilder) SetRelocs(rslice []Reloc) { } } +// Add n relocations, return a handle to the relocations. +func (sb *SymbolBuilder) AddRelocs(n int) Relocs { + sb.relocs = append(sb.relocs, make([]goobj2.Reloc2, n)...) + sb.reltypes = append(sb.reltypes, make([]objabi.RelocType, n)...) + return sb.l.Relocs(sb.symIdx) +} + +// Add a relocation with given type, return its handle and index +// (to set other fields). +func (sb *SymbolBuilder) AddRel(typ objabi.RelocType) (Reloc2, int) { + j := len(sb.relocs) + sb.relocs = append(sb.relocs, goobj2.Reloc2{}) + sb.reltypes = append(sb.reltypes, typ) + relocs := sb.Relocs() + return relocs.At2(j), j +} + +// Sort relocations by offset. +func (sb *SymbolBuilder) SortRelocs() { + sort.Sort((*relocsByOff)(sb.extSymPayload)) +} + +// Implement sort.Interface +type relocsByOff extSymPayload + +func (p *relocsByOff) Len() int { return len(p.relocs) } +func (p *relocsByOff) Less(i, j int) bool { return p.relocs[i].Off() < p.relocs[j].Off() } +func (p *relocsByOff) Swap(i, j int) { + p.relocs[i], p.relocs[j] = p.relocs[j], p.relocs[i] + p.reltypes[i], p.reltypes[j] = p.reltypes[j], p.reltypes[i] +} + // AddReloc appends the specified reloc to the symbols list of // relocations. Return value is the index of the newly created // reloc.