sym.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // Derived from Inferno utils/6l/obj.c and utils/6l/span.c
  2. // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/obj.c
  3. // https://bitbucket.org/inferno-os/inferno-os/src/master/utils/6l/span.c
  4. //
  5. // Copyright © 1994-1999 Lucent Technologies Inc. All rights reserved.
  6. // Portions Copyright © 1995-1997 C H Forsyth (forsyth@terzarima.net)
  7. // Portions Copyright © 1997-1999 Vita Nuova Limited
  8. // Portions Copyright © 2000-2007 Vita Nuova Holdings Limited (www.vitanuova.com)
  9. // Portions Copyright © 2004,2006 Bruce Ellis
  10. // Portions Copyright © 2005-2007 C H Forsyth (forsyth@terzarima.net)
  11. // Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
  12. // Portions Copyright © 2009 The Go Authors. All rights reserved.
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining a copy
  15. // of this software and associated documentation files (the "Software"), to deal
  16. // in the Software without restriction, including without limitation the rights
  17. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18. // copies of the Software, and to permit persons to whom the Software is
  19. // furnished to do so, subject to the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be included in
  22. // all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  27. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  30. // THE SOFTWARE.
  31. package obj
  32. import (
  33. "github.com/twitchyliquid64/golang-asm/goobj"
  34. "github.com/twitchyliquid64/golang-asm/objabi"
  35. "fmt"
  36. "log"
  37. "math"
  38. "sort"
  39. )
  40. func Linknew(arch *LinkArch) *Link {
  41. ctxt := new(Link)
  42. ctxt.hash = make(map[string]*LSym)
  43. ctxt.funchash = make(map[string]*LSym)
  44. ctxt.statichash = make(map[string]*LSym)
  45. ctxt.Arch = arch
  46. ctxt.Pathname = objabi.WorkingDir()
  47. if err := ctxt.Headtype.Set(objabi.GOOS); err != nil {
  48. log.Fatalf("unknown goos %s", objabi.GOOS)
  49. }
  50. ctxt.Flag_optimize = true
  51. return ctxt
  52. }
  53. // LookupDerived looks up or creates the symbol with name name derived from symbol s.
  54. // The resulting symbol will be static iff s is.
  55. func (ctxt *Link) LookupDerived(s *LSym, name string) *LSym {
  56. if s.Static() {
  57. return ctxt.LookupStatic(name)
  58. }
  59. return ctxt.Lookup(name)
  60. }
  61. // LookupStatic looks up the static symbol with name name.
  62. // If it does not exist, it creates it.
  63. func (ctxt *Link) LookupStatic(name string) *LSym {
  64. s := ctxt.statichash[name]
  65. if s == nil {
  66. s = &LSym{Name: name, Attribute: AttrStatic}
  67. ctxt.statichash[name] = s
  68. }
  69. return s
  70. }
  71. // LookupABI looks up a symbol with the given ABI.
  72. // If it does not exist, it creates it.
  73. func (ctxt *Link) LookupABI(name string, abi ABI) *LSym {
  74. return ctxt.LookupABIInit(name, abi, nil)
  75. }
  76. // LookupABI looks up a symbol with the given ABI.
  77. // If it does not exist, it creates it and
  78. // passes it to init for one-time initialization.
  79. func (ctxt *Link) LookupABIInit(name string, abi ABI, init func(s *LSym)) *LSym {
  80. var hash map[string]*LSym
  81. switch abi {
  82. case ABI0:
  83. hash = ctxt.hash
  84. case ABIInternal:
  85. hash = ctxt.funchash
  86. default:
  87. panic("unknown ABI")
  88. }
  89. ctxt.hashmu.Lock()
  90. s := hash[name]
  91. if s == nil {
  92. s = &LSym{Name: name}
  93. s.SetABI(abi)
  94. hash[name] = s
  95. if init != nil {
  96. init(s)
  97. }
  98. }
  99. ctxt.hashmu.Unlock()
  100. return s
  101. }
  102. // Lookup looks up the symbol with name name.
  103. // If it does not exist, it creates it.
  104. func (ctxt *Link) Lookup(name string) *LSym {
  105. return ctxt.LookupInit(name, nil)
  106. }
  107. // LookupInit looks up the symbol with name name.
  108. // If it does not exist, it creates it and
  109. // passes it to init for one-time initialization.
  110. func (ctxt *Link) LookupInit(name string, init func(s *LSym)) *LSym {
  111. ctxt.hashmu.Lock()
  112. s := ctxt.hash[name]
  113. if s == nil {
  114. s = &LSym{Name: name}
  115. ctxt.hash[name] = s
  116. if init != nil {
  117. init(s)
  118. }
  119. }
  120. ctxt.hashmu.Unlock()
  121. return s
  122. }
  123. func (ctxt *Link) Float32Sym(f float32) *LSym {
  124. i := math.Float32bits(f)
  125. name := fmt.Sprintf("$f32.%08x", i)
  126. return ctxt.LookupInit(name, func(s *LSym) {
  127. s.Size = 4
  128. s.WriteFloat32(ctxt, 0, f)
  129. s.Type = objabi.SRODATA
  130. s.Set(AttrLocal, true)
  131. s.Set(AttrContentAddressable, true)
  132. ctxt.constSyms = append(ctxt.constSyms, s)
  133. })
  134. }
  135. func (ctxt *Link) Float64Sym(f float64) *LSym {
  136. i := math.Float64bits(f)
  137. name := fmt.Sprintf("$f64.%016x", i)
  138. return ctxt.LookupInit(name, func(s *LSym) {
  139. s.Size = 8
  140. s.WriteFloat64(ctxt, 0, f)
  141. s.Type = objabi.SRODATA
  142. s.Set(AttrLocal, true)
  143. s.Set(AttrContentAddressable, true)
  144. ctxt.constSyms = append(ctxt.constSyms, s)
  145. })
  146. }
  147. func (ctxt *Link) Int64Sym(i int64) *LSym {
  148. name := fmt.Sprintf("$i64.%016x", uint64(i))
  149. return ctxt.LookupInit(name, func(s *LSym) {
  150. s.Size = 8
  151. s.WriteInt(ctxt, 0, 8, i)
  152. s.Type = objabi.SRODATA
  153. s.Set(AttrLocal, true)
  154. s.Set(AttrContentAddressable, true)
  155. ctxt.constSyms = append(ctxt.constSyms, s)
  156. })
  157. }
  158. // Assign index to symbols.
  159. // asm is set to true if this is called by the assembler (i.e. not the compiler),
  160. // in which case all the symbols are non-package (for now).
  161. func (ctxt *Link) NumberSyms() {
  162. if ctxt.Headtype == objabi.Haix {
  163. // Data must be sorted to keep a constant order in TOC symbols.
  164. // As they are created during Progedit, two symbols can be switched between
  165. // two different compilations. Therefore, BuildID will be different.
  166. // TODO: find a better place and optimize to only sort TOC symbols
  167. sort.Slice(ctxt.Data, func(i, j int) bool {
  168. return ctxt.Data[i].Name < ctxt.Data[j].Name
  169. })
  170. }
  171. // Constant symbols are created late in the concurrent phase. Sort them
  172. // to ensure a deterministic order.
  173. sort.Slice(ctxt.constSyms, func(i, j int) bool {
  174. return ctxt.constSyms[i].Name < ctxt.constSyms[j].Name
  175. })
  176. ctxt.Data = append(ctxt.Data, ctxt.constSyms...)
  177. ctxt.constSyms = nil
  178. ctxt.pkgIdx = make(map[string]int32)
  179. ctxt.defs = []*LSym{}
  180. ctxt.hashed64defs = []*LSym{}
  181. ctxt.hasheddefs = []*LSym{}
  182. ctxt.nonpkgdefs = []*LSym{}
  183. var idx, hashedidx, hashed64idx, nonpkgidx int32
  184. ctxt.traverseSyms(traverseDefs, func(s *LSym) {
  185. // if Pkgpath is unknown, cannot hash symbols with relocations, as it
  186. // may reference named symbols whose names are not fully expanded.
  187. if s.ContentAddressable() && (ctxt.Pkgpath != "" || len(s.R) == 0) {
  188. if len(s.P) <= 8 && len(s.R) == 0 { // we can use short hash only for symbols without relocations
  189. s.PkgIdx = goobj.PkgIdxHashed64
  190. s.SymIdx = hashed64idx
  191. if hashed64idx != int32(len(ctxt.hashed64defs)) {
  192. panic("bad index")
  193. }
  194. ctxt.hashed64defs = append(ctxt.hashed64defs, s)
  195. hashed64idx++
  196. } else {
  197. s.PkgIdx = goobj.PkgIdxHashed
  198. s.SymIdx = hashedidx
  199. if hashedidx != int32(len(ctxt.hasheddefs)) {
  200. panic("bad index")
  201. }
  202. ctxt.hasheddefs = append(ctxt.hasheddefs, s)
  203. hashedidx++
  204. }
  205. } else if isNonPkgSym(ctxt, s) {
  206. s.PkgIdx = goobj.PkgIdxNone
  207. s.SymIdx = nonpkgidx
  208. if nonpkgidx != int32(len(ctxt.nonpkgdefs)) {
  209. panic("bad index")
  210. }
  211. ctxt.nonpkgdefs = append(ctxt.nonpkgdefs, s)
  212. nonpkgidx++
  213. } else {
  214. s.PkgIdx = goobj.PkgIdxSelf
  215. s.SymIdx = idx
  216. if idx != int32(len(ctxt.defs)) {
  217. panic("bad index")
  218. }
  219. ctxt.defs = append(ctxt.defs, s)
  220. idx++
  221. }
  222. s.Set(AttrIndexed, true)
  223. })
  224. ipkg := int32(1) // 0 is invalid index
  225. nonpkgdef := nonpkgidx
  226. ctxt.traverseSyms(traverseRefs|traverseAux, func(rs *LSym) {
  227. if rs.PkgIdx != goobj.PkgIdxInvalid {
  228. return
  229. }
  230. if !ctxt.Flag_linkshared {
  231. // Assign special index for builtin symbols.
  232. // Don't do it when linking against shared libraries, as the runtime
  233. // may be in a different library.
  234. if i := goobj.BuiltinIdx(rs.Name, int(rs.ABI())); i != -1 {
  235. rs.PkgIdx = goobj.PkgIdxBuiltin
  236. rs.SymIdx = int32(i)
  237. rs.Set(AttrIndexed, true)
  238. return
  239. }
  240. }
  241. pkg := rs.Pkg
  242. if rs.ContentAddressable() {
  243. // for now, only support content-addressable symbols that are always locally defined.
  244. panic("hashed refs unsupported for now")
  245. }
  246. if pkg == "" || pkg == "\"\"" || pkg == "_" || !rs.Indexed() {
  247. rs.PkgIdx = goobj.PkgIdxNone
  248. rs.SymIdx = nonpkgidx
  249. rs.Set(AttrIndexed, true)
  250. if nonpkgidx != nonpkgdef+int32(len(ctxt.nonpkgrefs)) {
  251. panic("bad index")
  252. }
  253. ctxt.nonpkgrefs = append(ctxt.nonpkgrefs, rs)
  254. nonpkgidx++
  255. return
  256. }
  257. if k, ok := ctxt.pkgIdx[pkg]; ok {
  258. rs.PkgIdx = k
  259. return
  260. }
  261. rs.PkgIdx = ipkg
  262. ctxt.pkgIdx[pkg] = ipkg
  263. ipkg++
  264. })
  265. }
  266. // Returns whether s is a non-package symbol, which needs to be referenced
  267. // by name instead of by index.
  268. func isNonPkgSym(ctxt *Link, s *LSym) bool {
  269. if ctxt.IsAsm && !s.Static() {
  270. // asm symbols are referenced by name only, except static symbols
  271. // which are file-local and can be referenced by index.
  272. return true
  273. }
  274. if ctxt.Flag_linkshared {
  275. // The referenced symbol may be in a different shared library so
  276. // the linker cannot see its index.
  277. return true
  278. }
  279. if s.Pkg == "_" {
  280. // The frontend uses package "_" to mark symbols that should not
  281. // be referenced by index, e.g. linkname'd symbols.
  282. return true
  283. }
  284. if s.DuplicateOK() {
  285. // Dupok symbol needs to be dedup'd by name.
  286. return true
  287. }
  288. return false
  289. }
  290. // StaticNamePref is the prefix the front end applies to static temporary
  291. // variables. When turned into LSyms, these can be tagged as static so
  292. // as to avoid inserting them into the linker's name lookup tables.
  293. const StaticNamePref = ".stmp_"
  294. type traverseFlag uint32
  295. const (
  296. traverseDefs traverseFlag = 1 << iota
  297. traverseRefs
  298. traverseAux
  299. traverseAll = traverseDefs | traverseRefs | traverseAux
  300. )
  301. // Traverse symbols based on flag, call fn for each symbol.
  302. func (ctxt *Link) traverseSyms(flag traverseFlag, fn func(*LSym)) {
  303. lists := [][]*LSym{ctxt.Text, ctxt.Data, ctxt.ABIAliases}
  304. for _, list := range lists {
  305. for _, s := range list {
  306. if flag&traverseDefs != 0 {
  307. fn(s)
  308. }
  309. if flag&traverseRefs != 0 {
  310. for _, r := range s.R {
  311. if r.Sym != nil {
  312. fn(r.Sym)
  313. }
  314. }
  315. }
  316. if flag&traverseAux != 0 {
  317. if s.Gotype != nil {
  318. fn(s.Gotype)
  319. }
  320. if s.Type == objabi.STEXT {
  321. f := func(parent *LSym, aux *LSym) {
  322. fn(aux)
  323. }
  324. ctxt.traverseFuncAux(flag, s, f)
  325. }
  326. }
  327. }
  328. }
  329. }
  330. func (ctxt *Link) traverseFuncAux(flag traverseFlag, fsym *LSym, fn func(parent *LSym, aux *LSym)) {
  331. pc := &fsym.Func.Pcln
  332. if flag&traverseAux == 0 {
  333. // NB: should it become necessary to walk aux sym reloc references
  334. // without walking the aux syms themselves, this can be changed.
  335. panic("should not be here")
  336. }
  337. for _, d := range pc.Funcdata {
  338. if d != nil {
  339. fn(fsym, d)
  340. }
  341. }
  342. files := ctxt.PosTable.FileTable()
  343. usedFiles := make([]goobj.CUFileIndex, 0, len(pc.UsedFiles))
  344. for f := range pc.UsedFiles {
  345. usedFiles = append(usedFiles, f)
  346. }
  347. sort.Slice(usedFiles, func(i, j int) bool { return usedFiles[i] < usedFiles[j] })
  348. for _, f := range usedFiles {
  349. if filesym := ctxt.Lookup(files[f]); filesym != nil {
  350. fn(fsym, filesym)
  351. }
  352. }
  353. for _, call := range pc.InlTree.nodes {
  354. if call.Func != nil {
  355. fn(fsym, call.Func)
  356. }
  357. f, _ := linkgetlineFromPos(ctxt, call.Pos)
  358. if filesym := ctxt.Lookup(f); filesym != nil {
  359. fn(fsym, filesym)
  360. }
  361. }
  362. dwsyms := []*LSym{fsym.Func.dwarfRangesSym, fsym.Func.dwarfLocSym, fsym.Func.dwarfDebugLinesSym, fsym.Func.dwarfInfoSym}
  363. for _, dws := range dwsyms {
  364. if dws == nil || dws.Size == 0 {
  365. continue
  366. }
  367. fn(fsym, dws)
  368. if flag&traverseRefs != 0 {
  369. for _, r := range dws.R {
  370. if r.Sym != nil {
  371. fn(dws, r.Sym)
  372. }
  373. }
  374. }
  375. }
  376. }
  377. // Traverse aux symbols, calling fn for each sym/aux pair.
  378. func (ctxt *Link) traverseAuxSyms(flag traverseFlag, fn func(parent *LSym, aux *LSym)) {
  379. lists := [][]*LSym{ctxt.Text, ctxt.Data, ctxt.ABIAliases}
  380. for _, list := range lists {
  381. for _, s := range list {
  382. if s.Gotype != nil {
  383. if flag&traverseDefs != 0 {
  384. fn(s, s.Gotype)
  385. }
  386. }
  387. if s.Type != objabi.STEXT {
  388. continue
  389. }
  390. ctxt.traverseFuncAux(flag, s, fn)
  391. }
  392. }
  393. }