decoder.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. // Copyright 2021 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package pkgbits
  5. import (
  6. "encoding/binary"
  7. "errors"
  8. "fmt"
  9. "go/constant"
  10. "go/token"
  11. "io"
  12. "math/big"
  13. "os"
  14. "runtime"
  15. "strings"
  16. )
  17. // A PkgDecoder provides methods for decoding a package's Unified IR
  18. // export data.
  19. type PkgDecoder struct {
  20. // version is the file format version.
  21. version uint32
  22. // sync indicates whether the file uses sync markers.
  23. sync bool
  24. // pkgPath is the package path for the package to be decoded.
  25. //
  26. // TODO(mdempsky): Remove; unneeded since CL 391014.
  27. pkgPath string
  28. // elemData is the full data payload of the encoded package.
  29. // Elements are densely and contiguously packed together.
  30. //
  31. // The last 8 bytes of elemData are the package fingerprint.
  32. elemData string
  33. // elemEnds stores the byte-offset end positions of element
  34. // bitstreams within elemData.
  35. //
  36. // For example, element I's bitstream data starts at elemEnds[I-1]
  37. // (or 0, if I==0) and ends at elemEnds[I].
  38. //
  39. // Note: elemEnds is indexed by absolute indices, not
  40. // section-relative indices.
  41. elemEnds []uint32
  42. // elemEndsEnds stores the index-offset end positions of relocation
  43. // sections within elemEnds.
  44. //
  45. // For example, section K's end positions start at elemEndsEnds[K-1]
  46. // (or 0, if K==0) and end at elemEndsEnds[K].
  47. elemEndsEnds [numRelocs]uint32
  48. scratchRelocEnt []RelocEnt
  49. }
  50. // PkgPath returns the package path for the package
  51. //
  52. // TODO(mdempsky): Remove; unneeded since CL 391014.
  53. func (pr *PkgDecoder) PkgPath() string { return pr.pkgPath }
  54. // SyncMarkers reports whether pr uses sync markers.
  55. func (pr *PkgDecoder) SyncMarkers() bool { return pr.sync }
  56. // NewPkgDecoder returns a PkgDecoder initialized to read the Unified
  57. // IR export data from input. pkgPath is the package path for the
  58. // compilation unit that produced the export data.
  59. //
  60. // TODO(mdempsky): Remove pkgPath parameter; unneeded since CL 391014.
  61. func NewPkgDecoder(pkgPath, input string) PkgDecoder {
  62. pr := PkgDecoder{
  63. pkgPath: pkgPath,
  64. }
  65. // TODO(mdempsky): Implement direct indexing of input string to
  66. // avoid copying the position information.
  67. r := strings.NewReader(input)
  68. assert(binary.Read(r, binary.LittleEndian, &pr.version) == nil)
  69. switch pr.version {
  70. default:
  71. panic(fmt.Errorf("unsupported version: %v", pr.version))
  72. case 0:
  73. // no flags
  74. case 1:
  75. var flags uint32
  76. assert(binary.Read(r, binary.LittleEndian, &flags) == nil)
  77. pr.sync = flags&flagSyncMarkers != 0
  78. }
  79. assert(binary.Read(r, binary.LittleEndian, pr.elemEndsEnds[:]) == nil)
  80. pr.elemEnds = make([]uint32, pr.elemEndsEnds[len(pr.elemEndsEnds)-1])
  81. assert(binary.Read(r, binary.LittleEndian, pr.elemEnds[:]) == nil)
  82. pos, err := r.Seek(0, io.SeekCurrent)
  83. assert(err == nil)
  84. pr.elemData = input[pos:]
  85. assert(len(pr.elemData)-8 == int(pr.elemEnds[len(pr.elemEnds)-1]))
  86. return pr
  87. }
  88. // NumElems returns the number of elements in section k.
  89. func (pr *PkgDecoder) NumElems(k RelocKind) int {
  90. count := int(pr.elemEndsEnds[k])
  91. if k > 0 {
  92. count -= int(pr.elemEndsEnds[k-1])
  93. }
  94. return count
  95. }
  96. // TotalElems returns the total number of elements across all sections.
  97. func (pr *PkgDecoder) TotalElems() int {
  98. return len(pr.elemEnds)
  99. }
  100. // Fingerprint returns the package fingerprint.
  101. func (pr *PkgDecoder) Fingerprint() [8]byte {
  102. var fp [8]byte
  103. copy(fp[:], pr.elemData[len(pr.elemData)-8:])
  104. return fp
  105. }
  106. // AbsIdx returns the absolute index for the given (section, index)
  107. // pair.
  108. func (pr *PkgDecoder) AbsIdx(k RelocKind, idx Index) int {
  109. absIdx := int(idx)
  110. if k > 0 {
  111. absIdx += int(pr.elemEndsEnds[k-1])
  112. }
  113. if absIdx >= int(pr.elemEndsEnds[k]) {
  114. errorf("%v:%v is out of bounds; %v", k, idx, pr.elemEndsEnds)
  115. }
  116. return absIdx
  117. }
  118. // DataIdx returns the raw element bitstream for the given (section,
  119. // index) pair.
  120. func (pr *PkgDecoder) DataIdx(k RelocKind, idx Index) string {
  121. absIdx := pr.AbsIdx(k, idx)
  122. var start uint32
  123. if absIdx > 0 {
  124. start = pr.elemEnds[absIdx-1]
  125. }
  126. end := pr.elemEnds[absIdx]
  127. return pr.elemData[start:end]
  128. }
  129. // StringIdx returns the string value for the given string index.
  130. func (pr *PkgDecoder) StringIdx(idx Index) string {
  131. return pr.DataIdx(RelocString, idx)
  132. }
  133. // NewDecoder returns a Decoder for the given (section, index) pair,
  134. // and decodes the given SyncMarker from the element bitstream.
  135. func (pr *PkgDecoder) NewDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
  136. r := pr.NewDecoderRaw(k, idx)
  137. r.Sync(marker)
  138. return r
  139. }
  140. // TempDecoder returns a Decoder for the given (section, index) pair,
  141. // and decodes the given SyncMarker from the element bitstream.
  142. // If possible the Decoder should be RetireDecoder'd when it is no longer
  143. // needed, this will avoid heap allocations.
  144. func (pr *PkgDecoder) TempDecoder(k RelocKind, idx Index, marker SyncMarker) Decoder {
  145. r := pr.TempDecoderRaw(k, idx)
  146. r.Sync(marker)
  147. return r
  148. }
  149. func (pr *PkgDecoder) RetireDecoder(d *Decoder) {
  150. pr.scratchRelocEnt = d.Relocs
  151. d.Relocs = nil
  152. }
  153. // NewDecoderRaw returns a Decoder for the given (section, index) pair.
  154. //
  155. // Most callers should use NewDecoder instead.
  156. func (pr *PkgDecoder) NewDecoderRaw(k RelocKind, idx Index) Decoder {
  157. r := Decoder{
  158. common: pr,
  159. k: k,
  160. Idx: idx,
  161. }
  162. // TODO(mdempsky) r.data.Reset(...) after #44505 is resolved.
  163. r.Data = *strings.NewReader(pr.DataIdx(k, idx))
  164. r.Sync(SyncRelocs)
  165. r.Relocs = make([]RelocEnt, r.Len())
  166. for i := range r.Relocs {
  167. r.Sync(SyncReloc)
  168. r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
  169. }
  170. return r
  171. }
  172. func (pr *PkgDecoder) TempDecoderRaw(k RelocKind, idx Index) Decoder {
  173. r := Decoder{
  174. common: pr,
  175. k: k,
  176. Idx: idx,
  177. }
  178. r.Data.Reset(pr.DataIdx(k, idx))
  179. r.Sync(SyncRelocs)
  180. l := r.Len()
  181. if cap(pr.scratchRelocEnt) >= l {
  182. r.Relocs = pr.scratchRelocEnt[:l]
  183. pr.scratchRelocEnt = nil
  184. } else {
  185. r.Relocs = make([]RelocEnt, l)
  186. }
  187. for i := range r.Relocs {
  188. r.Sync(SyncReloc)
  189. r.Relocs[i] = RelocEnt{RelocKind(r.Len()), Index(r.Len())}
  190. }
  191. return r
  192. }
  193. // A Decoder provides methods for decoding an individual element's
  194. // bitstream data.
  195. type Decoder struct {
  196. common *PkgDecoder
  197. Relocs []RelocEnt
  198. Data strings.Reader
  199. k RelocKind
  200. Idx Index
  201. }
  202. func (r *Decoder) checkErr(err error) {
  203. if err != nil {
  204. errorf("unexpected decoding error: %w", err)
  205. }
  206. }
  207. func (r *Decoder) rawUvarint() uint64 {
  208. x, err := readUvarint(&r.Data)
  209. r.checkErr(err)
  210. return x
  211. }
  212. // readUvarint is a type-specialized copy of encoding/binary.ReadUvarint.
  213. // This avoids the interface conversion and thus has better escape properties,
  214. // which flows up the stack.
  215. func readUvarint(r *strings.Reader) (uint64, error) {
  216. var x uint64
  217. var s uint
  218. for i := 0; i < binary.MaxVarintLen64; i++ {
  219. b, err := r.ReadByte()
  220. if err != nil {
  221. if i > 0 && err == io.EOF {
  222. err = io.ErrUnexpectedEOF
  223. }
  224. return x, err
  225. }
  226. if b < 0x80 {
  227. if i == binary.MaxVarintLen64-1 && b > 1 {
  228. return x, overflow
  229. }
  230. return x | uint64(b)<<s, nil
  231. }
  232. x |= uint64(b&0x7f) << s
  233. s += 7
  234. }
  235. return x, overflow
  236. }
  237. var overflow = errors.New("pkgbits: readUvarint overflows a 64-bit integer")
  238. func (r *Decoder) rawVarint() int64 {
  239. ux := r.rawUvarint()
  240. // Zig-zag decode.
  241. x := int64(ux >> 1)
  242. if ux&1 != 0 {
  243. x = ^x
  244. }
  245. return x
  246. }
  247. func (r *Decoder) rawReloc(k RelocKind, idx int) Index {
  248. e := r.Relocs[idx]
  249. assert(e.Kind == k)
  250. return e.Idx
  251. }
  252. // Sync decodes a sync marker from the element bitstream and asserts
  253. // that it matches the expected marker.
  254. //
  255. // If r.common.sync is false, then Sync is a no-op.
  256. func (r *Decoder) Sync(mWant SyncMarker) {
  257. if !r.common.sync {
  258. return
  259. }
  260. pos, _ := r.Data.Seek(0, io.SeekCurrent)
  261. mHave := SyncMarker(r.rawUvarint())
  262. writerPCs := make([]int, r.rawUvarint())
  263. for i := range writerPCs {
  264. writerPCs[i] = int(r.rawUvarint())
  265. }
  266. if mHave == mWant {
  267. return
  268. }
  269. // There's some tension here between printing:
  270. //
  271. // (1) full file paths that tools can recognize (e.g., so emacs
  272. // hyperlinks the "file:line" text for easy navigation), or
  273. //
  274. // (2) short file paths that are easier for humans to read (e.g., by
  275. // omitting redundant or irrelevant details, so it's easier to
  276. // focus on the useful bits that remain).
  277. //
  278. // The current formatting favors the former, as it seems more
  279. // helpful in practice. But perhaps the formatting could be improved
  280. // to better address both concerns. For example, use relative file
  281. // paths if they would be shorter, or rewrite file paths to contain
  282. // "$GOROOT" (like objabi.AbsFile does) if tools can be taught how
  283. // to reliably expand that again.
  284. fmt.Printf("export data desync: package %q, section %v, index %v, offset %v\n", r.common.pkgPath, r.k, r.Idx, pos)
  285. fmt.Printf("\nfound %v, written at:\n", mHave)
  286. if len(writerPCs) == 0 {
  287. fmt.Printf("\t[stack trace unavailable; recompile package %q with -d=syncframes]\n", r.common.pkgPath)
  288. }
  289. for _, pc := range writerPCs {
  290. fmt.Printf("\t%s\n", r.common.StringIdx(r.rawReloc(RelocString, pc)))
  291. }
  292. fmt.Printf("\nexpected %v, reading at:\n", mWant)
  293. var readerPCs [32]uintptr // TODO(mdempsky): Dynamically size?
  294. n := runtime.Callers(2, readerPCs[:])
  295. for _, pc := range fmtFrames(readerPCs[:n]...) {
  296. fmt.Printf("\t%s\n", pc)
  297. }
  298. // We already printed a stack trace for the reader, so now we can
  299. // simply exit. Printing a second one with panic or base.Fatalf
  300. // would just be noise.
  301. os.Exit(1)
  302. }
  303. // Bool decodes and returns a bool value from the element bitstream.
  304. func (r *Decoder) Bool() bool {
  305. r.Sync(SyncBool)
  306. x, err := r.Data.ReadByte()
  307. r.checkErr(err)
  308. assert(x < 2)
  309. return x != 0
  310. }
  311. // Int64 decodes and returns an int64 value from the element bitstream.
  312. func (r *Decoder) Int64() int64 {
  313. r.Sync(SyncInt64)
  314. return r.rawVarint()
  315. }
  316. // Uint64 decodes and returns a uint64 value from the element bitstream.
  317. func (r *Decoder) Uint64() uint64 {
  318. r.Sync(SyncUint64)
  319. return r.rawUvarint()
  320. }
  321. // Len decodes and returns a non-negative int value from the element bitstream.
  322. func (r *Decoder) Len() int { x := r.Uint64(); v := int(x); assert(uint64(v) == x); return v }
  323. // Int decodes and returns an int value from the element bitstream.
  324. func (r *Decoder) Int() int { x := r.Int64(); v := int(x); assert(int64(v) == x); return v }
  325. // Uint decodes and returns a uint value from the element bitstream.
  326. func (r *Decoder) Uint() uint { x := r.Uint64(); v := uint(x); assert(uint64(v) == x); return v }
  327. // Code decodes a Code value from the element bitstream and returns
  328. // its ordinal value. It's the caller's responsibility to convert the
  329. // result to an appropriate Code type.
  330. //
  331. // TODO(mdempsky): Ideally this method would have signature "Code[T
  332. // Code] T" instead, but we don't allow generic methods and the
  333. // compiler can't depend on generics yet anyway.
  334. func (r *Decoder) Code(mark SyncMarker) int {
  335. r.Sync(mark)
  336. return r.Len()
  337. }
  338. // Reloc decodes a relocation of expected section k from the element
  339. // bitstream and returns an index to the referenced element.
  340. func (r *Decoder) Reloc(k RelocKind) Index {
  341. r.Sync(SyncUseReloc)
  342. return r.rawReloc(k, r.Len())
  343. }
  344. // String decodes and returns a string value from the element
  345. // bitstream.
  346. func (r *Decoder) String() string {
  347. r.Sync(SyncString)
  348. return r.common.StringIdx(r.Reloc(RelocString))
  349. }
  350. // Strings decodes and returns a variable-length slice of strings from
  351. // the element bitstream.
  352. func (r *Decoder) Strings() []string {
  353. res := make([]string, r.Len())
  354. for i := range res {
  355. res[i] = r.String()
  356. }
  357. return res
  358. }
  359. // Value decodes and returns a constant.Value from the element
  360. // bitstream.
  361. func (r *Decoder) Value() constant.Value {
  362. r.Sync(SyncValue)
  363. isComplex := r.Bool()
  364. val := r.scalar()
  365. if isComplex {
  366. val = constant.BinaryOp(val, token.ADD, constant.MakeImag(r.scalar()))
  367. }
  368. return val
  369. }
  370. func (r *Decoder) scalar() constant.Value {
  371. switch tag := CodeVal(r.Code(SyncVal)); tag {
  372. default:
  373. panic(fmt.Errorf("unexpected scalar tag: %v", tag))
  374. case ValBool:
  375. return constant.MakeBool(r.Bool())
  376. case ValString:
  377. return constant.MakeString(r.String())
  378. case ValInt64:
  379. return constant.MakeInt64(r.Int64())
  380. case ValBigInt:
  381. return constant.Make(r.bigInt())
  382. case ValBigRat:
  383. num := r.bigInt()
  384. denom := r.bigInt()
  385. return constant.Make(new(big.Rat).SetFrac(num, denom))
  386. case ValBigFloat:
  387. return constant.Make(r.bigFloat())
  388. }
  389. }
  390. func (r *Decoder) bigInt() *big.Int {
  391. v := new(big.Int).SetBytes([]byte(r.String()))
  392. if r.Bool() {
  393. v.Neg(v)
  394. }
  395. return v
  396. }
  397. func (r *Decoder) bigFloat() *big.Float {
  398. v := new(big.Float).SetPrec(512)
  399. assert(v.UnmarshalText([]byte(r.String())) == nil)
  400. return v
  401. }
  402. // @@@ Helpers
  403. // TODO(mdempsky): These should probably be removed. I think they're a
  404. // smell that the export data format is not yet quite right.
  405. // PeekPkgPath returns the package path for the specified package
  406. // index.
  407. func (pr *PkgDecoder) PeekPkgPath(idx Index) string {
  408. var path string
  409. {
  410. r := pr.TempDecoder(RelocPkg, idx, SyncPkgDef)
  411. path = r.String()
  412. pr.RetireDecoder(&r)
  413. }
  414. if path == "" {
  415. path = pr.pkgPath
  416. }
  417. return path
  418. }
  419. // PeekObj returns the package path, object name, and CodeObj for the
  420. // specified object index.
  421. func (pr *PkgDecoder) PeekObj(idx Index) (string, string, CodeObj) {
  422. var ridx Index
  423. var name string
  424. var rcode int
  425. {
  426. r := pr.TempDecoder(RelocName, idx, SyncObject1)
  427. r.Sync(SyncSym)
  428. r.Sync(SyncPkg)
  429. ridx = r.Reloc(RelocPkg)
  430. name = r.String()
  431. rcode = r.Code(SyncCodeObj)
  432. pr.RetireDecoder(&r)
  433. }
  434. path := pr.PeekPkgPath(ridx)
  435. assert(name != "")
  436. tag := CodeObj(rcode)
  437. return path, name, tag
  438. }