您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

1722 行
43 KiB

  1. // Copyright 2018 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. //m4_changequote(`@',`@')
  15. // Evaluates Go expressions, using the current values of variables in a program
  16. // being debugged.
  17. //
  18. // TODOs:
  19. // More overflow checking.
  20. // Stricter type checking.
  21. // More expression types.
  22. package server
  23. import (
  24. "errors"
  25. "fmt"
  26. "go/ast"
  27. "go/parser"
  28. "go/token"
  29. "math"
  30. "math/big"
  31. "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug"
  32. "cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/dwarf"
  33. )
  34. const prec = 256 // precision for untyped float and complex constants.
  35. var (
  36. // Some big.Ints to use in overflow checks.
  37. bigIntMaxInt32 = big.NewInt(math.MaxInt32)
  38. bigIntMinInt32 = big.NewInt(math.MinInt32)
  39. bigIntMaxInt64 = big.NewInt(math.MaxInt64)
  40. bigIntMinInt64 = big.NewInt(math.MinInt64)
  41. bigIntMaxUint64 = new(big.Int).SetUint64(math.MaxUint64)
  42. )
  43. // result stores an intermediate value produced during evaluation of an expression.
  44. //
  45. // d contains the DWARF type of the value. For untyped values, d will be nil.
  46. //
  47. // v contains the value itself. For numeric and bool types, v will have the
  48. // corresponding predeclared Go type.
  49. // For untyped integer, rune, float, complex, string, and bool constants, v will
  50. // have type untInt, untRune, untFloat, untComplex, untString, or bool,
  51. // respectively.
  52. // For values of type int, uint and uintptr, v will be an int32, int64, uint32
  53. // or uint64 as appropriate.
  54. // For address operations, v will have type pointerToValue.
  55. // For the operands of address operations, v will have type addressableValue.
  56. // Other types are represented using the corresponding implementation of
  57. // debug.Value in program.go.
  58. //
  59. // If an evaluation results in an error, the zero value of result is used.
  60. type result struct {
  61. d dwarf.Type
  62. v interface{}
  63. }
  64. // untInt is an untyped integer constant
  65. type untInt struct {
  66. *big.Int
  67. }
  68. // untRune is an untyped rune constant
  69. type untRune struct {
  70. *big.Int
  71. }
  72. // untFloat is an untyped floating-point constant
  73. type untFloat struct {
  74. *big.Float
  75. }
  76. // untComplex is an untyped complex constant
  77. type untComplex struct {
  78. r *big.Float
  79. i *big.Float
  80. }
  81. // untString is an untyped string constant
  82. type untString string
  83. // pointerToValue is a pointer to a value in memory.
  84. // The evaluator constructs these as the result of address operations like "&x".
  85. // Unlike debug.Pointer, the DWARF type stored alongside values of this type
  86. // is the type of the variable, not the type of the pointer.
  87. type pointerToValue struct {
  88. a uint64
  89. }
  90. // addressableValue is the memory location of a value.
  91. // The evaluator constructs these while evaluating the operands of address
  92. // operations like "&x", instead of computing the value of x itself.
  93. type addressableValue struct {
  94. a uint64
  95. }
  96. // A sliceOf is a slice created by slicing an array.
  97. // Unlike debug.Slice, the DWARF type stored alongside a value of this type is
  98. // the type of the slice's elements, not the type of the slice.
  99. type sliceOf debug.Slice
  100. // ident is a value for representing a special identifier.
  101. type ident string
  102. // identLookup is a built-in function of the expression evaluator which gets the
  103. // value of a global symbol.
  104. var identLookup ident = "lookup"
  105. // evalExpression evaluates a Go expression.
  106. // If the program counter and stack pointer are nonzero, they are used to determine
  107. // what local variables are available and where in memory they are.
  108. func (s *Server) evalExpression(expression string, pc, sp uint64) (debug.Value, error) {
  109. e := evaluator{server: s, expression: expression, pc: pc, sp: sp}
  110. node, err := parser.ParseExpr(expression)
  111. if err != nil {
  112. return nil, err
  113. }
  114. val := e.evalNode(node, false)
  115. if e.evalError != nil {
  116. return nil, e.evalError
  117. }
  118. // Convert untyped constants to their default types.
  119. switch v := val.v.(type) {
  120. case untInt:
  121. return e.intFromInteger(v)
  122. case untRune:
  123. if v.Cmp(bigIntMaxInt32) == +1 {
  124. return nil, errors.New("constant overflows rune")
  125. }
  126. if v.Cmp(bigIntMinInt32) == -1 {
  127. return nil, errors.New("constant overflows rune")
  128. }
  129. return int32(v.Int64()), nil
  130. case untFloat:
  131. f, _ := v.Float64()
  132. if math.IsInf(f, 0) {
  133. return nil, errors.New("constant overflows float64")
  134. }
  135. if math.IsNaN(f) {
  136. return nil, errors.New("constant is NaN")
  137. }
  138. return f, nil
  139. case untComplex:
  140. r, _ := v.r.Float64()
  141. i, _ := v.i.Float64()
  142. if math.IsInf(r, 0) || math.IsInf(i, 0) {
  143. return nil, errors.New("constant overflows complex128")
  144. }
  145. if math.IsNaN(r) || math.IsNaN(i) {
  146. return nil, errors.New("constant is NaN")
  147. }
  148. return complex(r, i), nil
  149. case untString:
  150. return debug.String{Length: uint64(len(v)), String: string(v)}, nil
  151. case pointerToValue:
  152. return debug.Pointer{TypeID: uint64(val.d.Common().Offset), Address: v.a}, nil
  153. case sliceOf:
  154. return debug.Slice(v), nil
  155. case nil, addressableValue:
  156. // This case should not be reachable.
  157. return nil, errors.New("unknown error")
  158. }
  159. return val.v, nil
  160. }
  161. type evaluator struct {
  162. // expression is the expression being evaluated.
  163. expression string
  164. // server interacts with the program being debugged.
  165. server *Server
  166. // curNode is the current parse tree node. This is set so that error messages
  167. // can quote the part of the expression that caused an error.
  168. curNode ast.Node
  169. // evalError is the first error that occurred while evaluating the expression,
  170. // or nil if no error has occurred.
  171. evalError error
  172. // pc and sp are the current program counter and stack pointer, used for
  173. // finding local variables. If either are zero, the expression is evaluated
  174. // without using local variables.
  175. pc uint64
  176. sp uint64
  177. }
  178. // setNode sets curNode, and returns curNode's previous value.
  179. func (e *evaluator) setNode(node ast.Node) (old ast.Node) {
  180. old, e.curNode = e.curNode, node
  181. return old
  182. }
  183. // err saves an error that occurred during evaluation.
  184. // It returns a zero result, so that functions can exit and set an error with
  185. // return e.err(...)
  186. func (e *evaluator) err(s string) result {
  187. if e.evalError != nil {
  188. return result{}
  189. }
  190. // Append the substring of the expression that corresponds to the current AST node.
  191. start := int(e.curNode.Pos() - 1)
  192. end := int(e.curNode.End() - 1)
  193. if start < 0 {
  194. start = 0
  195. }
  196. if end > len(e.expression) {
  197. end = len(e.expression)
  198. }
  199. if start > end {
  200. start, end = 0, 0
  201. }
  202. e.evalError = errors.New(s + `: "` + e.expression[start:end] + `"`)
  203. return result{}
  204. }
  205. // evalNode computes the value of a node in the expression tree.
  206. // If getAddress is true, the node is the argument of an & operator, so evalNode
  207. // will return a result with a value of type addressableValue if possible.
  208. func (e *evaluator) evalNode(node ast.Node, getAddress bool) result {
  209. // Set the current node in the evaluator, so that error messages can refer to
  210. // it. Defer a function call that changes it back.
  211. defer e.setNode(e.setNode(node))
  212. switch n := node.(type) {
  213. case *ast.Ident:
  214. if e.pc != 0 && e.sp != 0 {
  215. a, t := e.server.findLocalVar(n.Name, e.pc, e.sp)
  216. if t != nil {
  217. return e.resultFrom(a, t, getAddress)
  218. }
  219. }
  220. a, t := e.server.findGlobalVar(n.Name)
  221. if t != nil {
  222. return e.resultFrom(a, t, getAddress)
  223. }
  224. switch n.Name {
  225. // Note: these could have been redefined as constants in the code, but we
  226. // don't have a way to detect that.
  227. case "true":
  228. return result{nil, true}
  229. case "false":
  230. return result{nil, false}
  231. case "lookup":
  232. return result{nil, identLookup}
  233. }
  234. return e.err("unknown identifier")
  235. case *ast.BasicLit:
  236. switch n.Kind {
  237. case token.INT:
  238. i := new(big.Int)
  239. if _, ok := i.SetString(n.Value, 0); !ok {
  240. return e.err("invalid integer constant")
  241. }
  242. return result{nil, untInt{i}}
  243. case token.FLOAT:
  244. r, _, err := big.ParseFloat(n.Value, 10, prec, big.ToNearestEven)
  245. if err != nil {
  246. return e.err(err.Error())
  247. }
  248. return result{nil, untFloat{r}}
  249. case token.IMAG:
  250. if len(n.Value) <= 1 || n.Value[len(n.Value)-1] != 'i' {
  251. return e.err("invalid imaginary constant")
  252. }
  253. r, _, err := big.ParseFloat(n.Value[:len(n.Value)-1], 10, prec, big.ToNearestEven)
  254. if err != nil {
  255. return e.err(err.Error())
  256. }
  257. return result{nil, untComplex{new(big.Float), r}}
  258. case token.CHAR:
  259. // TODO: unescaping
  260. return result{nil, untRune{new(big.Int).SetInt64(int64(n.Value[1]))}}
  261. case token.STRING:
  262. // TODO: unescaping
  263. if len(n.Value) <= 1 {
  264. return e.err("invalid string constant")
  265. }
  266. return result{nil, untString(n.Value[1 : len(n.Value)-1])}
  267. }
  268. case *ast.ParenExpr:
  269. return e.evalNode(n.X, getAddress)
  270. case *ast.StarExpr:
  271. x := e.evalNode(n.X, false)
  272. switch v := x.v.(type) {
  273. case debug.Pointer:
  274. // x.d may be a typedef pointing to a pointer type (or a typedef pointing
  275. // to a typedef pointing to a pointer type, etc.), so remove typedefs
  276. // until we get the underlying pointer type.
  277. t := followTypedefs(x.d)
  278. if pt, ok := t.(*dwarf.PtrType); ok {
  279. return e.resultFrom(v.Address, pt.Type, getAddress)
  280. } else {
  281. return e.err("invalid DWARF type for pointer")
  282. }
  283. case pointerToValue:
  284. return e.resultFrom(v.a, x.d, getAddress)
  285. case nil:
  286. return x
  287. }
  288. return e.err("invalid indirect")
  289. case *ast.SelectorExpr:
  290. x := e.evalNode(n.X, false)
  291. sel := n.Sel.Name
  292. switch v := x.v.(type) {
  293. case debug.Struct:
  294. for _, f := range v.Fields {
  295. if f.Name == sel {
  296. t, err := e.server.dwarfData.Type(dwarf.Offset(f.Var.TypeID))
  297. if err != nil {
  298. return e.err(err.Error())
  299. }
  300. return e.resultFrom(f.Var.Address, t, getAddress)
  301. }
  302. }
  303. return e.err("struct field not found")
  304. case debug.Pointer:
  305. pt, ok := followTypedefs(x.d).(*dwarf.PtrType) // x.d should be a pointer to struct.
  306. if !ok {
  307. return e.err("invalid DWARF information for pointer")
  308. }
  309. st, ok := followTypedefs(pt.Type).(*dwarf.StructType)
  310. if !ok {
  311. break
  312. }
  313. for _, f := range st.Field {
  314. if f.Name == sel {
  315. return e.resultFrom(v.Address+uint64(f.ByteOffset), f.Type, getAddress)
  316. }
  317. }
  318. return e.err("struct field not found")
  319. case pointerToValue:
  320. st, ok := followTypedefs(x.d).(*dwarf.StructType) // x.d should be a struct.
  321. if !ok {
  322. break
  323. }
  324. for _, f := range st.Field {
  325. if f.Name == sel {
  326. return e.resultFrom(v.a+uint64(f.ByteOffset), f.Type, getAddress)
  327. }
  328. }
  329. return e.err("struct field not found")
  330. }
  331. return e.err("invalid selector expression")
  332. case *ast.IndexExpr:
  333. x, index := e.evalNode(n.X, false), e.evalNode(n.Index, false)
  334. if x.v == nil || index.v == nil {
  335. return result{}
  336. }
  337. // The expression is x[index]
  338. if m, ok := x.v.(debug.Map); ok {
  339. if getAddress {
  340. return e.err("can't take address of map value")
  341. }
  342. mt, ok := followTypedefs(x.d).(*dwarf.MapType)
  343. if !ok {
  344. return e.err("invalid DWARF type for map")
  345. }
  346. var (
  347. found bool // true if the key was found
  348. value result // the map value for the key
  349. abort bool // true if an error occurred while searching
  350. // fn is a function that checks if one (key, value) pair corresponds
  351. // to the index in the expression.
  352. fn = func(keyAddr, valAddr uint64, keyType, valType dwarf.Type) bool {
  353. key := e.resultFrom(keyAddr, keyType, false)
  354. if key.v == nil {
  355. abort = true
  356. return false // stop searching map
  357. }
  358. equal, ok := e.evalBinaryOp(token.EQL, index, key).v.(bool)
  359. if !ok {
  360. abort = true
  361. return false // stop searching map
  362. }
  363. if equal {
  364. found = true
  365. value = e.resultFrom(valAddr, valType, false)
  366. return false // stop searching map
  367. }
  368. return true // continue searching map
  369. }
  370. )
  371. if err := e.server.peekMapValues(mt, m.Address, fn); err != nil {
  372. return e.err(err.Error())
  373. }
  374. if abort {
  375. // Some operation on individual map keys failed.
  376. return result{}
  377. }
  378. if found {
  379. return value
  380. }
  381. // The key wasn't in the map; return the zero value.
  382. return e.zero(mt.ElemType)
  383. }
  384. // The index should be a non-negative integer for the remaining cases.
  385. u, err := uint64FromResult(index)
  386. if err != nil {
  387. return e.err("invalid index: " + err.Error())
  388. }
  389. switch v := x.v.(type) {
  390. case debug.Array:
  391. if u >= v.Length {
  392. return e.err("array index out of bounds")
  393. }
  394. elemType, err := e.server.dwarfData.Type(dwarf.Offset(v.ElementTypeID))
  395. if err != nil {
  396. return e.err(err.Error())
  397. }
  398. return e.resultFrom(v.Element(u).Address, elemType, getAddress)
  399. case debug.Slice:
  400. if u >= v.Length {
  401. return e.err("slice index out of bounds")
  402. }
  403. elemType, err := e.server.dwarfData.Type(dwarf.Offset(v.ElementTypeID))
  404. if err != nil {
  405. return e.err(err.Error())
  406. }
  407. return e.resultFrom(v.Element(u).Address, elemType, getAddress)
  408. case sliceOf:
  409. if u >= v.Length {
  410. return e.err("slice index out of bounds")
  411. }
  412. return e.resultFrom(v.Element(u).Address, x.d, getAddress)
  413. case debug.String:
  414. if getAddress {
  415. return e.err("can't take address of string element")
  416. }
  417. if u >= v.Length {
  418. return e.err("string index out of bounds")
  419. }
  420. if u >= uint64(len(v.String)) {
  421. return e.err("string element unavailable")
  422. }
  423. return e.uint8Result(v.String[u])
  424. case untString:
  425. if getAddress {
  426. return e.err("can't take address of string element")
  427. }
  428. if u >= uint64(len(v)) {
  429. return e.err("string index out of bounds")
  430. }
  431. return e.uint8Result(v[u])
  432. }
  433. return e.err("invalid index expression")
  434. case *ast.SliceExpr:
  435. if n.Slice3 && n.High == nil {
  436. return e.err("middle index required in full slice")
  437. }
  438. if n.Slice3 && n.Max == nil {
  439. return e.err("final index required in full slice")
  440. }
  441. var (
  442. low, high, max uint64
  443. err error
  444. )
  445. if n.Low != nil {
  446. low, err = uint64FromResult(e.evalNode(n.Low, false))
  447. if err != nil {
  448. return e.err("invalid slice lower bound: " + err.Error())
  449. }
  450. }
  451. if n.High != nil {
  452. high, err = uint64FromResult(e.evalNode(n.High, false))
  453. if err != nil {
  454. return e.err("invalid slice upper bound: " + err.Error())
  455. }
  456. }
  457. if n.Max != nil {
  458. max, err = uint64FromResult(e.evalNode(n.Max, false))
  459. if err != nil {
  460. return e.err("invalid slice capacity: " + err.Error())
  461. }
  462. }
  463. x := e.evalNode(n.X, false)
  464. switch v := x.v.(type) {
  465. case debug.Array, debug.Pointer, pointerToValue:
  466. // This case handles the slicing of arrays and pointers to arrays.
  467. var arr debug.Array
  468. switch v := x.v.(type) {
  469. case debug.Array:
  470. arr = v
  471. case debug.Pointer:
  472. pt, ok := followTypedefs(x.d).(*dwarf.PtrType)
  473. if !ok {
  474. return e.err("invalid DWARF type for pointer")
  475. }
  476. a := e.resultFrom(v.Address, pt.Type, false)
  477. arr, ok = a.v.(debug.Array)
  478. if !ok {
  479. // v is a pointer to something other than an array.
  480. return e.err("cannot slice pointer")
  481. }
  482. case pointerToValue:
  483. a := e.resultFrom(v.a, x.d, false)
  484. var ok bool
  485. arr, ok = a.v.(debug.Array)
  486. if !ok {
  487. // v is a pointer to something other than an array.
  488. return e.err("cannot slice pointer")
  489. }
  490. }
  491. elemType, err := e.server.dwarfData.Type(dwarf.Offset(arr.ElementTypeID))
  492. if err != nil {
  493. return e.err(err.Error())
  494. }
  495. if n.High == nil {
  496. high = arr.Length
  497. } else if high > arr.Length {
  498. return e.err("slice upper bound is too large")
  499. }
  500. if n.Max == nil {
  501. max = arr.Length
  502. } else if max > arr.Length {
  503. return e.err("slice capacity is too large")
  504. }
  505. if low > high || high > max {
  506. return e.err("invalid slice index")
  507. }
  508. return result{
  509. d: elemType,
  510. v: sliceOf{
  511. Array: debug.Array{
  512. ElementTypeID: arr.ElementTypeID,
  513. Address: arr.Element(low).Address,
  514. Length: high - low,
  515. StrideBits: uint64(elemType.Common().ByteSize) * 8,
  516. },
  517. Capacity: max - low,
  518. },
  519. }
  520. case debug.Slice:
  521. if n.High == nil {
  522. high = v.Length
  523. } else if high > v.Capacity {
  524. return e.err("slice upper bound is too large")
  525. }
  526. if n.Max == nil {
  527. max = v.Capacity
  528. } else if max > v.Capacity {
  529. return e.err("slice capacity is too large")
  530. }
  531. if low > high || high > max {
  532. return e.err("invalid slice index")
  533. }
  534. v.Address += low * (v.StrideBits / 8)
  535. v.Length = high - low
  536. v.Capacity = max - low
  537. return result{x.d, v}
  538. case sliceOf:
  539. if n.High == nil {
  540. high = v.Length
  541. } else if high > v.Capacity {
  542. return e.err("slice upper bound is too large")
  543. }
  544. if n.Max == nil {
  545. max = v.Capacity
  546. } else if max > v.Capacity {
  547. return e.err("slice capacity is too large")
  548. }
  549. if low > high || high > max {
  550. return e.err("invalid slice index")
  551. }
  552. v.Address += low * (v.StrideBits / 8)
  553. v.Length = high - low
  554. v.Capacity = max - low
  555. return result{x.d, v}
  556. case debug.String:
  557. if n.Max != nil {
  558. return e.err("full slice of string")
  559. }
  560. if n.High == nil {
  561. high = v.Length
  562. }
  563. if low > high || high > v.Length {
  564. return e.err("invalid slice index")
  565. }
  566. v.Length = high - low
  567. if low > uint64(len(v.String)) {
  568. // v.String was truncated before the point where this slice starts.
  569. v.String = ""
  570. } else {
  571. if high > uint64(len(v.String)) {
  572. // v.String was truncated before the point where this slice ends.
  573. high = uint64(len(v.String))
  574. }
  575. v.String = v.String[low:high]
  576. }
  577. return result{x.d, v}
  578. case untString:
  579. if n.Max != nil {
  580. return e.err("full slice of string")
  581. }
  582. if n.High == nil {
  583. high = uint64(len(v))
  584. }
  585. if low > high {
  586. return e.err("invalid slice expression")
  587. }
  588. if high > uint64(len(v)) {
  589. return e.err("slice upper bound is too large")
  590. }
  591. return e.stringResult(string(v[low:high]))
  592. default:
  593. return e.err("invalid slice expression")
  594. }
  595. case *ast.CallExpr:
  596. // Only supports lookup("x"), which gets the value of a global symbol x.
  597. fun := e.evalNode(n.Fun, false)
  598. var args []result
  599. for _, a := range n.Args {
  600. args = append(args, e.evalNode(a, false))
  601. }
  602. if fun.v == identLookup {
  603. if len(args) != 1 {
  604. return e.err("lookup should have one argument")
  605. }
  606. ident, ok := args[0].v.(untString)
  607. if !ok {
  608. return e.err("argument for lookup should be a string constant")
  609. }
  610. if a, t := e.server.findGlobalVar(string(ident)); t == nil {
  611. return e.err("symbol not found")
  612. } else {
  613. return e.resultFrom(a, t, getAddress)
  614. }
  615. }
  616. return e.err("function calls not implemented")
  617. case *ast.UnaryExpr:
  618. if n.Op == token.AND {
  619. x := e.evalNode(n.X, true)
  620. switch v := x.v.(type) {
  621. case addressableValue:
  622. return result{x.d, pointerToValue{v.a}}
  623. case nil:
  624. return x
  625. }
  626. return e.err("can't take address")
  627. }
  628. x := e.evalNode(n.X, false)
  629. if x.v == nil {
  630. return x
  631. }
  632. switch v := x.v.(type) {
  633. m4_define(UNARY_INT_OPS, @case $1:
  634. switch n.Op {
  635. case token.ADD:
  636. case token.SUB:
  637. v = -v
  638. case token.XOR:
  639. v = ^v
  640. default:
  641. return e.err("invalid operation")
  642. }
  643. return result{x.d, v}
  644. @)
  645. m4_define(UNARY_FLOAT_OPS, @case $1:
  646. switch n.Op {
  647. case token.ADD:
  648. case token.SUB:
  649. v = -v
  650. default:
  651. return e.err("invalid operation")
  652. }
  653. return result{x.d, v}
  654. @)
  655. UNARY_INT_OPS(int8)
  656. UNARY_INT_OPS(int16)
  657. UNARY_INT_OPS(int32)
  658. UNARY_INT_OPS(int64)
  659. UNARY_INT_OPS(uint8)
  660. UNARY_INT_OPS(uint16)
  661. UNARY_INT_OPS(uint32)
  662. UNARY_INT_OPS(uint64)
  663. UNARY_FLOAT_OPS(float32)
  664. UNARY_FLOAT_OPS(float64)
  665. UNARY_FLOAT_OPS(complex64)
  666. UNARY_FLOAT_OPS(complex128)
  667. case untInt:
  668. switch n.Op {
  669. case token.ADD:
  670. case token.SUB:
  671. v.Int.Neg(v.Int)
  672. case token.XOR:
  673. v.Int.Not(v.Int)
  674. default:
  675. return e.err("invalid operation")
  676. }
  677. return result{x.d, v}
  678. case untRune:
  679. switch n.Op {
  680. case token.ADD:
  681. case token.SUB:
  682. v.Int.Neg(v.Int)
  683. case token.XOR:
  684. v.Int.Not(v.Int)
  685. default:
  686. return e.err("invalid operation")
  687. }
  688. return result{x.d, v}
  689. case untFloat:
  690. switch n.Op {
  691. case token.ADD:
  692. case token.SUB:
  693. v.Float.Neg(v.Float)
  694. default:
  695. return e.err("invalid operation")
  696. }
  697. return result{x.d, v}
  698. case untComplex:
  699. switch n.Op {
  700. case token.ADD:
  701. case token.SUB:
  702. v.r.Neg(v.r)
  703. v.i.Neg(v.i)
  704. default:
  705. return e.err("invalid operation")
  706. }
  707. return result{x.d, v}
  708. case bool:
  709. switch n.Op {
  710. case token.NOT:
  711. v = !v
  712. default:
  713. return e.err("invalid operation")
  714. }
  715. return result{x.d, v}
  716. }
  717. case *ast.BinaryExpr:
  718. x := e.evalNode(n.X, false)
  719. if x.v == nil {
  720. return x
  721. }
  722. y := e.evalNode(n.Y, false)
  723. if y.v == nil {
  724. return y
  725. }
  726. return e.evalBinaryOp(n.Op, x, y)
  727. }
  728. return e.err("invalid expression")
  729. }
  730. // evalBinaryOp evaluates a binary operator op applied to x and y.
  731. func (e *evaluator) evalBinaryOp(op token.Token, x, y result) result {
  732. if op == token.NEQ {
  733. tmp := e.evalBinaryOp(token.EQL, x, y)
  734. b, ok := tmp.v.(bool)
  735. if !ok {
  736. return tmp
  737. }
  738. return result{nil, !b}
  739. }
  740. if op == token.GTR {
  741. return e.evalBinaryOp(token.LSS, y, x)
  742. }
  743. if op == token.GEQ {
  744. return e.evalBinaryOp(token.LEQ, x, y)
  745. }
  746. x = convertUntyped(x, y)
  747. y = convertUntyped(y, x)
  748. switch a := x.v.(type) {
  749. m4_define(INT_OPS, @case $1:
  750. b, ok := y.v.($1)
  751. if !ok {
  752. return e.err("type mismatch")
  753. }
  754. var c $1
  755. switch op {
  756. case token.EQL:
  757. return result{nil, a == b}
  758. case token.LSS:
  759. return result{nil, a < b}
  760. case token.LEQ:
  761. return result{nil, a <= b}
  762. case token.ADD:
  763. c = a + b
  764. case token.SUB:
  765. c = a - b
  766. case token.OR:
  767. c = a | b
  768. case token.XOR:
  769. c = a ^ b
  770. case token.MUL:
  771. c = a * b
  772. case token.QUO:
  773. if b == 0 {
  774. return e.err("integer divide by zero")
  775. }
  776. c = a / b
  777. case token.REM:
  778. if b == 0 {
  779. return e.err("integer divide by zero")
  780. }
  781. c = a % b
  782. case token.AND:
  783. c = a & b
  784. case token.AND_NOT:
  785. c = a &^ b
  786. default:
  787. return e.err("invalid operation")
  788. }
  789. return result{x.d, c}
  790. @)
  791. m4_define(UINT_OPS, @case $1:
  792. b, ok := y.v.($1)
  793. if !ok {
  794. return e.err("type mismatch")
  795. }
  796. var c $1
  797. switch op {
  798. case token.EQL:
  799. return result{nil, a == b}
  800. case token.LSS:
  801. return result{nil, a < b}
  802. case token.LEQ:
  803. return result{nil, a <= b}
  804. case token.ADD:
  805. c = a + b
  806. case token.SUB:
  807. c = a - b
  808. case token.OR:
  809. c = a | b
  810. case token.XOR:
  811. c = a ^ b
  812. case token.MUL:
  813. c = a * b
  814. case token.QUO:
  815. if b == 0 {
  816. return e.err("integer divide by zero")
  817. }
  818. c = a / b
  819. case token.REM:
  820. if b == 0 {
  821. return e.err("integer divide by zero")
  822. }
  823. c = a % b
  824. case token.AND:
  825. c = a & b
  826. case token.AND_NOT:
  827. c = a &^ b
  828. default:
  829. return e.err("invalid operation")
  830. }
  831. return result{x.d, c}
  832. @)
  833. m4_define(FLOAT_OPS, @case $1:
  834. b, ok := y.v.($1)
  835. if !ok {
  836. return e.err("type mismatch")
  837. }
  838. var c $1
  839. switch op {
  840. case token.EQL:
  841. return result{nil, a == b}
  842. case token.LSS:
  843. return result{nil, a < b}
  844. case token.LEQ:
  845. return result{nil, a <= b}
  846. case token.ADD:
  847. c = a + b
  848. case token.SUB:
  849. c = a - b
  850. case token.MUL:
  851. c = a * b
  852. case token.QUO:
  853. c = a / b
  854. default:
  855. return e.err("invalid operation")
  856. }
  857. return result{x.d, c}
  858. @)
  859. m4_define(COMPLEX_OPS, @case $1:
  860. b, ok := y.v.($1)
  861. if !ok {
  862. return e.err("type mismatch")
  863. }
  864. var c $1
  865. switch op {
  866. case token.EQL:
  867. return result{nil, a == b}
  868. case token.ADD:
  869. c = a + b
  870. case token.SUB:
  871. c = a - b
  872. case token.MUL:
  873. c = a * b
  874. case token.QUO:
  875. c = a / b
  876. default:
  877. return e.err("invalid operation")
  878. }
  879. return result{x.d, c}
  880. @)
  881. INT_OPS(int8)
  882. INT_OPS(int16)
  883. INT_OPS(int32)
  884. INT_OPS(int64)
  885. UINT_OPS(uint8)
  886. UINT_OPS(uint16)
  887. UINT_OPS(uint32)
  888. UINT_OPS(uint64)
  889. FLOAT_OPS(float32)
  890. FLOAT_OPS(float64)
  891. COMPLEX_OPS(complex64)
  892. COMPLEX_OPS(complex128)
  893. case bool:
  894. b, ok := y.v.(bool)
  895. if !ok {
  896. return e.err("type mismatch")
  897. }
  898. var c bool
  899. switch op {
  900. case token.LOR:
  901. c = a || b
  902. case token.LAND:
  903. c = a && b
  904. case token.EQL:
  905. c = a == b
  906. default:
  907. return e.err("invalid operation")
  908. }
  909. return result{x.d, c}
  910. case debug.String:
  911. b, ok := y.v.(debug.String)
  912. if !ok {
  913. return e.err("type mismatch")
  914. }
  915. var c debug.String
  916. switch op {
  917. // TODO: these comparison operators only use the part of the string that
  918. // was read. Very large strings do not have their entire contents read by
  919. // server.value.
  920. case token.EQL:
  921. return result{nil, a.Length == b.Length && a.String == b.String}
  922. case token.LSS:
  923. return result{nil, a.String < b.String}
  924. case token.LEQ:
  925. return result{nil, a.String <= b.String}
  926. case token.ADD:
  927. c.Length = a.Length + b.Length
  928. if a.Length == uint64(len(a.String)) {
  929. c.String = a.String + b.String
  930. } else {
  931. // The first string was truncated at a.Length characters, so the sum
  932. // must be truncated there too.
  933. c.String = a.String
  934. }
  935. default:
  936. return e.err("invalid operation")
  937. }
  938. return result{x.d, c}
  939. case untString:
  940. b, ok := y.v.(untString)
  941. if !ok {
  942. return e.err("type mismatch")
  943. }
  944. var c untString
  945. switch op {
  946. case token.EQL:
  947. return result{nil, a == b}
  948. case token.LSS:
  949. return result{nil, a < b}
  950. case token.LEQ:
  951. return result{nil, a <= b}
  952. case token.ADD:
  953. c = a + b
  954. default:
  955. return e.err("invalid operation")
  956. }
  957. return result{x.d, c}
  958. case untInt:
  959. i := a.Int
  960. b, ok := y.v.(untInt)
  961. if !ok {
  962. return e.err("type mismatch")
  963. }
  964. switch op {
  965. case token.EQL:
  966. return result{nil, i.Cmp(b.Int) == 0}
  967. case token.LSS:
  968. return result{nil, i.Cmp(b.Int) < 0}
  969. case token.LEQ:
  970. return result{nil, i.Cmp(b.Int) <= 0}
  971. }
  972. c := new(big.Int)
  973. switch op {
  974. case token.ADD:
  975. c.Add(i, b.Int)
  976. case token.SUB:
  977. c.Sub(i, b.Int)
  978. case token.OR:
  979. c.Or(i, b.Int)
  980. case token.XOR:
  981. c.Xor(i, b.Int)
  982. case token.MUL:
  983. c.Mul(i, b.Int)
  984. case token.QUO:
  985. if b.Sign() == 0 {
  986. return e.err("integer divide by zero")
  987. }
  988. c.Quo(i, b.Int)
  989. case token.REM:
  990. if b.Sign() == 0 {
  991. return e.err("integer divide by zero")
  992. }
  993. c.Mod(i, b.Int)
  994. case token.AND:
  995. c.And(i, b.Int)
  996. case token.AND_NOT:
  997. c.AndNot(i, b.Int)
  998. default:
  999. return e.err("invalid operation")
  1000. }
  1001. return result{nil, untInt{c}}
  1002. case untRune:
  1003. i := a.Int
  1004. b, ok := y.v.(untRune)
  1005. if !ok {
  1006. return e.err("type mismatch")
  1007. }
  1008. switch op {
  1009. case token.EQL:
  1010. return result{nil, i.Cmp(b.Int) == 0}
  1011. case token.LSS:
  1012. return result{nil, i.Cmp(b.Int) < 0}
  1013. case token.LEQ:
  1014. return result{nil, i.Cmp(b.Int) <= 0}
  1015. }
  1016. c := new(big.Int)
  1017. switch op {
  1018. case token.ADD:
  1019. c.Add(i, b.Int)
  1020. case token.SUB:
  1021. c.Sub(i, b.Int)
  1022. case token.OR:
  1023. c.Or(i, b.Int)
  1024. case token.XOR:
  1025. c.Xor(i, b.Int)
  1026. case token.MUL:
  1027. c.Mul(i, b.Int)
  1028. case token.QUO:
  1029. if b.Sign() == 0 {
  1030. return e.err("integer divide by zero")
  1031. }
  1032. c.Quo(i, b.Int)
  1033. case token.REM:
  1034. if b.Sign() == 0 {
  1035. return e.err("integer divide by zero")
  1036. }
  1037. c.Mod(i, b.Int)
  1038. case token.AND:
  1039. c.And(i, b.Int)
  1040. case token.AND_NOT:
  1041. c.AndNot(i, b.Int)
  1042. default:
  1043. return e.err("invalid operation")
  1044. }
  1045. return result{nil, untRune{c}}
  1046. case untFloat:
  1047. r := a.Float
  1048. b, ok := y.v.(untFloat)
  1049. if !ok {
  1050. return e.err("type mismatch")
  1051. }
  1052. switch op {
  1053. case token.EQL:
  1054. return result{nil, r.Cmp(b.Float) == 0}
  1055. case token.LSS:
  1056. return result{nil, r.Cmp(b.Float) < 0}
  1057. case token.LEQ:
  1058. return result{nil, r.Cmp(b.Float) <= 0}
  1059. }
  1060. c := new(big.Float)
  1061. switch op {
  1062. case token.ADD:
  1063. c.Add(r, b.Float)
  1064. case token.SUB:
  1065. c.Sub(r, b.Float)
  1066. case token.MUL:
  1067. c.Mul(r, b.Float)
  1068. case token.QUO:
  1069. if b.Sign() == 0 {
  1070. return e.err("divide by zero")
  1071. }
  1072. c.Quo(r, b.Float)
  1073. default:
  1074. return e.err("invalid operation")
  1075. }
  1076. return result{nil, untFloat{c}}
  1077. case untComplex:
  1078. b, ok := y.v.(untComplex)
  1079. if !ok {
  1080. return e.err("type mismatch")
  1081. }
  1082. var (
  1083. ar = a.r
  1084. br = b.r
  1085. ai = a.i
  1086. bi = b.i
  1087. )
  1088. if op == token.EQL {
  1089. return result{nil, ar.Cmp(br) == 0 && ai.Cmp(bi) == 0}
  1090. }
  1091. var (
  1092. cr = new(big.Float)
  1093. ci = new(big.Float)
  1094. )
  1095. switch op {
  1096. case token.ADD:
  1097. cr.Add(ar, br)
  1098. ci.Add(ai, bi)
  1099. case token.SUB:
  1100. cr.Sub(ar, br)
  1101. ci.Sub(ai, bi)
  1102. case token.MUL:
  1103. var t0, t1 big.Float
  1104. t0.Mul(ar, br)
  1105. t1.Mul(ai, bi)
  1106. cr.Sub(&t0, &t1)
  1107. t0.Mul(ar, bi)
  1108. t1.Mul(ai, br)
  1109. ci.Add(&t0, &t1)
  1110. case token.QUO:
  1111. // a/b = a*conj(b)/|b|^2
  1112. var t0, t1 big.Float
  1113. cr.Mul(ar, br)
  1114. t0.Mul(ai, bi)
  1115. cr.Add(cr, &t0) // cr = Re(a*conj(b))
  1116. ci.Mul(ai, br)
  1117. t0.Mul(ar, bi)
  1118. ci.Sub(ci, &t0) // ci = Im(a*conj(b))
  1119. t0.Mul(br, br)
  1120. t1.Mul(bi, bi)
  1121. t0.Add(&t0, &t1) // t0 = |b|^2
  1122. if t0.Sign() == 0 {
  1123. return e.err("divide by zero")
  1124. }
  1125. cr.Quo(cr, &t0) // cr = Re(a*conj(b))/|b|^2 = Re(a/b)
  1126. ci.Quo(ci, &t0) // ci = Im(a*conj(b))/|b|^2 = Im(a/b)
  1127. }
  1128. return result{nil, untComplex{cr, ci}}
  1129. }
  1130. return e.err("invalid operation")
  1131. }
  1132. // findLocalVar finds a local variable (or function parameter) by name, and
  1133. // returns its address and DWARF type. It returns a nil type on failure.
  1134. // The PC and SP are used to determine the current function and stack frame.
  1135. func (s *Server) findLocalVar(name string, pc, sp uint64) (uint64, dwarf.Type) {
  1136. // Find the DWARF entry for the function at pc.
  1137. funcEntry, _, err := s.dwarfData.PCToFunction(uint64(pc))
  1138. if err != nil {
  1139. return 0, nil
  1140. }
  1141. // Compute the stack frame pointer.
  1142. fpOffset, err := s.dwarfData.PCToSPOffset(uint64(pc))
  1143. if err != nil {
  1144. return 0, nil
  1145. }
  1146. framePointer := sp + uint64(fpOffset)
  1147. // Check each child of the function's DWARF entry to see if it is a parameter
  1148. // or local variable with the right name. If so, return its address and type.
  1149. r := s.dwarfData.Reader()
  1150. r.Seek(funcEntry.Offset)
  1151. for {
  1152. varEntry, err := r.Next()
  1153. if err != nil {
  1154. break
  1155. }
  1156. if varEntry.Tag == 0 {
  1157. // This tag marks the end of the function's DWARF entry's children.
  1158. break
  1159. }
  1160. // Check this entry corresponds to a local variable or function parameter,
  1161. // that it has the correct name, and that we can get its type and location.
  1162. // If so, return them.
  1163. if varEntry.Tag != dwarf.TagFormalParameter && varEntry.Tag != dwarf.TagVariable {
  1164. continue
  1165. }
  1166. varName, ok := varEntry.Val(dwarf.AttrName).(string)
  1167. if !ok {
  1168. continue
  1169. }
  1170. if varName != name {
  1171. continue
  1172. }
  1173. varTypeOffset, ok := varEntry.Val(dwarf.AttrType).(dwarf.Offset)
  1174. if !ok {
  1175. continue
  1176. }
  1177. varType, err := s.dwarfData.Type(varTypeOffset)
  1178. if err != nil {
  1179. continue
  1180. }
  1181. locationAttribute := varEntry.Val(dwarf.AttrLocation)
  1182. if locationAttribute == nil {
  1183. continue
  1184. }
  1185. locationDescription, ok := locationAttribute.([]uint8)
  1186. if !ok {
  1187. continue
  1188. }
  1189. frameOffset, err := evalLocation(locationDescription)
  1190. if err != nil {
  1191. continue
  1192. }
  1193. return framePointer + uint64(frameOffset), varType
  1194. }
  1195. return 0, nil
  1196. }
  1197. // findGlobalVar finds a global variable by name, and returns its address and
  1198. // DWARF type. It returns a nil type on failure.
  1199. func (s *Server) findGlobalVar(name string) (uint64, dwarf.Type) {
  1200. entry, err := s.dwarfData.LookupVariable(name)
  1201. if err != nil {
  1202. return 0, nil
  1203. }
  1204. loc, err := s.dwarfData.EntryLocation(entry)
  1205. if err != nil {
  1206. return 0, nil
  1207. }
  1208. ofs, err := s.dwarfData.EntryTypeOffset(entry)
  1209. if err != nil {
  1210. return 0, nil
  1211. }
  1212. typ, err := s.dwarfData.Type(ofs)
  1213. if err != nil {
  1214. return 0, nil
  1215. }
  1216. return loc, typ
  1217. }
  1218. // intFromInteger converts an untyped integer constant to an int32 or int64,
  1219. // depending on the int size of the debugged program.
  1220. // It returns an error on overflow, or if it can't determine the int size.
  1221. func (e *evaluator) intFromInteger(v untInt) (interface{}, error) {
  1222. t, ok := e.getBaseType("int")
  1223. if !ok {
  1224. return nil, errors.New("couldn't get int size from DWARF info")
  1225. }
  1226. switch t.Common().ByteSize {
  1227. case 4:
  1228. if v.Cmp(bigIntMaxInt32) == +1 || v.Cmp(bigIntMinInt32) == -1 {
  1229. return nil, errors.New("constant overflows int")
  1230. }
  1231. return int32(v.Int64()), nil
  1232. case 8:
  1233. if v.Cmp(bigIntMaxInt64) == +1 || v.Cmp(bigIntMinInt64) == -1 {
  1234. return nil, errors.New("constant overflows int")
  1235. }
  1236. return v.Int64(), nil
  1237. }
  1238. return nil, errors.New("invalid int size in DWARF info")
  1239. }
  1240. // uint8Result constructs a result for a uint8 value.
  1241. func (e *evaluator) uint8Result(v uint8) result {
  1242. t, ok := e.getBaseType("uint8")
  1243. if !ok {
  1244. e.err("couldn't construct uint8")
  1245. }
  1246. return result{t, uint8(v)}
  1247. }
  1248. // stringResult constructs a result for a string value.
  1249. func (e *evaluator) stringResult(s string) result {
  1250. t, ok := e.getBaseType("string")
  1251. if !ok {
  1252. e.err("couldn't construct string")
  1253. }
  1254. return result{t, debug.String{Length: uint64(len(s)), String: s}}
  1255. }
  1256. // getBaseType returns the *dwarf.Type with a given name.
  1257. // TODO: cache this.
  1258. func (e *evaluator) getBaseType(name string) (dwarf.Type, bool) {
  1259. entry, err := e.server.dwarfData.LookupEntry(name)
  1260. if err != nil {
  1261. return nil, false
  1262. }
  1263. t, err := e.server.dwarfData.Type(entry.Offset)
  1264. if err != nil {
  1265. return nil, false
  1266. }
  1267. return t, true
  1268. }
  1269. // resultFrom constructs a result corresponding to a value in the program with
  1270. // the given address and DWARF type.
  1271. // If getAddress is true, the result will be the operand of an address expression,
  1272. // so resultFrom returns a result containing a value of type addressableValue.
  1273. func (e *evaluator) resultFrom(a uint64, t dwarf.Type, getAddress bool) result {
  1274. if a == 0 {
  1275. return e.err("nil pointer dereference")
  1276. }
  1277. if getAddress {
  1278. return result{t, addressableValue{a}}
  1279. }
  1280. v, err := e.server.value(t, a)
  1281. if err != nil {
  1282. return e.err(err.Error())
  1283. }
  1284. return result{t, v}
  1285. }
  1286. // zero returns the zero value of type t.
  1287. // TODO: implement for array and struct.
  1288. func (e *evaluator) zero(t dwarf.Type) result {
  1289. var v interface{}
  1290. switch typ := followTypedefs(t).(type) {
  1291. case *dwarf.CharType, *dwarf.IntType, *dwarf.EnumType:
  1292. switch typ.Common().ByteSize {
  1293. case 1:
  1294. v = int8(0)
  1295. case 2:
  1296. v = int16(0)
  1297. case 4:
  1298. v = int32(0)
  1299. case 8:
  1300. v = int64(0)
  1301. default:
  1302. return e.err("invalid integer size " + fmt.Sprint(typ.Common().ByteSize))
  1303. }
  1304. case *dwarf.UcharType, *dwarf.UintType:
  1305. switch typ.Common().ByteSize {
  1306. case 1:
  1307. v = uint8(0)
  1308. case 2:
  1309. v = uint16(0)
  1310. case 4:
  1311. v = uint32(0)
  1312. case 8:
  1313. v = uint64(0)
  1314. default:
  1315. return e.err("invalid unsigned integer size " + fmt.Sprint(typ.Common().ByteSize))
  1316. }
  1317. case *dwarf.FloatType:
  1318. switch typ.Common().ByteSize {
  1319. case 4:
  1320. v = float32(0)
  1321. case 8:
  1322. v = float64(0)
  1323. default:
  1324. return e.err("invalid float size " + fmt.Sprint(typ.Common().ByteSize))
  1325. }
  1326. case *dwarf.ComplexType:
  1327. switch typ.Common().ByteSize {
  1328. case 8:
  1329. v = complex64(0)
  1330. case 16:
  1331. v = complex128(0)
  1332. default:
  1333. return e.err("invalid complex size " + fmt.Sprint(typ.Common().ByteSize))
  1334. }
  1335. case *dwarf.BoolType:
  1336. v = false
  1337. case *dwarf.PtrType:
  1338. v = debug.Pointer{TypeID: uint64(t.Common().Offset)}
  1339. case *dwarf.SliceType:
  1340. v = debug.Slice{
  1341. Array: debug.Array{
  1342. ElementTypeID: uint64(typ.ElemType.Common().Offset),
  1343. StrideBits: uint64(typ.ElemType.Common().ByteSize) * 8,
  1344. },
  1345. }
  1346. case *dwarf.StringType:
  1347. v = debug.String{}
  1348. case *dwarf.InterfaceType:
  1349. v = debug.Interface{}
  1350. case *dwarf.FuncType:
  1351. v = debug.Func{}
  1352. case *dwarf.MapType:
  1353. v = debug.Map{TypeID: uint64(t.Common().Offset)}
  1354. case *dwarf.ChanType:
  1355. v = debug.Channel{
  1356. ElementTypeID: uint64(typ.ElemType.Common().Offset),
  1357. Stride: uint64(typ.ElemType.Common().ByteSize),
  1358. }
  1359. default:
  1360. return e.err("can't get zero value of this type")
  1361. }
  1362. return result{t, v}
  1363. }
  1364. // convertUntyped converts x to be the same type as y, if x is untyped and the
  1365. // conversion is possible.
  1366. //
  1367. // An untyped bool can be converted to a boolean type.
  1368. // An untyped string can be converted to a string type.
  1369. // An untyped integer, rune, float or complex value can be converted to a
  1370. // numeric type, or to an untyped value later in that list.
  1371. //
  1372. // x is returned unchanged if none of these cases apply.
  1373. func convertUntyped(x, y result) result {
  1374. switch a := x.v.(type) {
  1375. case untInt:
  1376. i := a.Int
  1377. switch y.v.(type) {
  1378. case int8:
  1379. return result{y.d, int8(i.Int64())}
  1380. case int16:
  1381. return result{y.d, int16(i.Int64())}
  1382. case int32:
  1383. return result{y.d, int32(i.Int64())}
  1384. case int64:
  1385. return result{y.d, int64(i.Int64())}
  1386. case uint8:
  1387. return result{y.d, uint8(i.Uint64())}
  1388. case uint16:
  1389. return result{y.d, uint16(i.Uint64())}
  1390. case uint32:
  1391. return result{y.d, uint32(i.Uint64())}
  1392. case uint64:
  1393. return result{y.d, uint64(i.Uint64())}
  1394. case float32:
  1395. f, _ := new(big.Float).SetInt(i).Float32()
  1396. return result{y.d, f}
  1397. case float64:
  1398. f, _ := new(big.Float).SetInt(i).Float64()
  1399. return result{y.d, f}
  1400. case complex64:
  1401. f, _ := new(big.Float).SetInt(i).Float32()
  1402. return result{y.d, complex(f, 0)}
  1403. case complex128:
  1404. f, _ := new(big.Float).SetInt(i).Float64()
  1405. return result{y.d, complex(f, 0)}
  1406. case untRune:
  1407. return result{nil, untRune{i}}
  1408. case untFloat:
  1409. return result{nil, untFloat{new(big.Float).SetPrec(prec).SetInt(i)}}
  1410. case untComplex:
  1411. return result{nil, untComplex{new(big.Float).SetPrec(prec).SetInt(i), new(big.Float)}}
  1412. }
  1413. case untRune:
  1414. i := a.Int
  1415. switch y.v.(type) {
  1416. case int8:
  1417. return result{y.d, int8(i.Int64())}
  1418. case int16:
  1419. return result{y.d, int16(i.Int64())}
  1420. case int32:
  1421. return result{y.d, int32(i.Int64())}
  1422. case int64:
  1423. return result{y.d, int64(i.Int64())}
  1424. case uint8:
  1425. return result{y.d, uint8(i.Uint64())}
  1426. case uint16:
  1427. return result{y.d, uint16(i.Uint64())}
  1428. case uint32:
  1429. return result{y.d, uint32(i.Uint64())}
  1430. case uint64:
  1431. return result{y.d, uint64(i.Uint64())}
  1432. case float32:
  1433. f, _ := new(big.Float).SetInt(i).Float32()
  1434. return result{y.d, f}
  1435. case float64:
  1436. f, _ := new(big.Float).SetInt(i).Float64()
  1437. return result{y.d, f}
  1438. case complex64:
  1439. f, _ := new(big.Float).SetInt(i).Float32()
  1440. return result{y.d, complex(f, 0)}
  1441. case complex128:
  1442. f, _ := new(big.Float).SetInt(i).Float64()
  1443. return result{y.d, complex(f, 0)}
  1444. case untRune:
  1445. return result{nil, untRune{i}}
  1446. case untFloat:
  1447. return result{nil, untFloat{new(big.Float).SetPrec(prec).SetInt(i)}}
  1448. case untComplex:
  1449. return result{nil, untComplex{new(big.Float).SetPrec(prec).SetInt(i), new(big.Float)}}
  1450. }
  1451. case untFloat:
  1452. if a.IsInt() {
  1453. i, _ := a.Int(nil)
  1454. switch y.v.(type) {
  1455. case int8:
  1456. return result{y.d, int8(i.Int64())}
  1457. case int16:
  1458. return result{y.d, int16(i.Int64())}
  1459. case int32:
  1460. return result{y.d, int32(i.Int64())}
  1461. case int64:
  1462. return result{y.d, int64(i.Int64())}
  1463. case uint8:
  1464. return result{y.d, uint8(i.Uint64())}
  1465. case uint16:
  1466. return result{y.d, uint16(i.Uint64())}
  1467. case uint32:
  1468. return result{y.d, uint32(i.Uint64())}
  1469. case uint64:
  1470. return result{y.d, uint64(i.Uint64())}
  1471. }
  1472. }
  1473. switch y.v.(type) {
  1474. case float32:
  1475. f, _ := a.Float32()
  1476. return result{y.d, float32(f)}
  1477. case float64:
  1478. f, _ := a.Float64()
  1479. return result{y.d, float64(f)}
  1480. case complex64:
  1481. f, _ := a.Float32()
  1482. return result{y.d, complex(f, 0)}
  1483. case complex128:
  1484. f, _ := a.Float64()
  1485. return result{y.d, complex(f, 0)}
  1486. case untComplex:
  1487. return result{nil, untComplex{a.Float, new(big.Float)}}
  1488. }
  1489. case untComplex:
  1490. if a.i.Sign() == 0 {
  1491. // a is a real number.
  1492. if a.r.IsInt() {
  1493. // a is an integer.
  1494. i, _ := a.r.Int(nil)
  1495. switch y.v.(type) {
  1496. case int8:
  1497. return result{y.d, int8(i.Int64())}
  1498. case int16:
  1499. return result{y.d, int16(i.Int64())}
  1500. case int32:
  1501. return result{y.d, int32(i.Int64())}
  1502. case int64:
  1503. return result{y.d, int64(i.Int64())}
  1504. case uint8:
  1505. return result{y.d, uint8(i.Uint64())}
  1506. case uint16:
  1507. return result{y.d, uint16(i.Uint64())}
  1508. case uint32:
  1509. return result{y.d, uint32(i.Uint64())}
  1510. case uint64:
  1511. return result{y.d, uint64(i.Uint64())}
  1512. }
  1513. }
  1514. switch y.v.(type) {
  1515. case float32:
  1516. f, _ := a.r.Float32()
  1517. return result{y.d, float32(f)}
  1518. case float64:
  1519. f, _ := a.r.Float64()
  1520. return result{y.d, float64(f)}
  1521. }
  1522. }
  1523. switch y.v.(type) {
  1524. case complex64:
  1525. r, _ := a.r.Float32()
  1526. i, _ := a.i.Float32()
  1527. return result{y.d, complex(r, i)}
  1528. case complex128:
  1529. r, _ := a.r.Float64()
  1530. i, _ := a.i.Float64()
  1531. return result{y.d, complex(r, i)}
  1532. }
  1533. case bool:
  1534. if x.d != nil {
  1535. // x is a typed bool, not an untyped bool.
  1536. break
  1537. }
  1538. switch y.v.(type) {
  1539. case bool:
  1540. return result{y.d, bool(a)}
  1541. }
  1542. case untString:
  1543. switch y.v.(type) {
  1544. case debug.String:
  1545. return result{y.d, debug.String{Length: uint64(len(a)), String: string(a)}}
  1546. }
  1547. }
  1548. return x
  1549. }
  1550. // uint64FromResult converts a result into a uint64 for slice or index expressions.
  1551. // It returns an error if the conversion cannot be done.
  1552. func uint64FromResult(x result) (uint64, error) {
  1553. switch v := x.v.(type) {
  1554. case int8:
  1555. if v < 0 {
  1556. return 0, errors.New("value is negative")
  1557. }
  1558. return uint64(v), nil
  1559. case int16:
  1560. if v < 0 {
  1561. return 0, errors.New("value is negative")
  1562. }
  1563. return uint64(v), nil
  1564. case int32:
  1565. if v < 0 {
  1566. return 0, errors.New("value is negative")
  1567. }
  1568. return uint64(v), nil
  1569. case int64:
  1570. if v < 0 {
  1571. return 0, errors.New("value is negative")
  1572. }
  1573. return uint64(v), nil
  1574. case uint8:
  1575. return uint64(v), nil
  1576. case uint16:
  1577. return uint64(v), nil
  1578. case uint32:
  1579. return uint64(v), nil
  1580. case uint64:
  1581. return v, nil
  1582. case untInt:
  1583. if v.Int.Sign() == -1 {
  1584. return 0, errors.New("value is negative")
  1585. }
  1586. if v.Int.Cmp(bigIntMaxUint64) == +1 {
  1587. return 0, errors.New("value is too large")
  1588. }
  1589. return v.Int.Uint64(), nil
  1590. case untRune:
  1591. if v.Sign() == -1 {
  1592. return 0, errors.New("value is negative")
  1593. }
  1594. if v.Cmp(bigIntMaxUint64) == +1 {
  1595. return 0, errors.New("value is too large")
  1596. }
  1597. return v.Uint64(), nil
  1598. case untFloat:
  1599. if !v.IsInt() {
  1600. return 0, errors.New("value is not an integer")
  1601. }
  1602. if v.Sign() == -1 {
  1603. return 0, errors.New("value is negative")
  1604. }
  1605. i, _ := v.Int(nil)
  1606. if i.Cmp(bigIntMaxUint64) == +1 {
  1607. return 0, errors.New("value is too large")
  1608. }
  1609. return i.Uint64(), nil
  1610. case untComplex:
  1611. if v.i.Sign() != 0 {
  1612. return 0, errors.New("value is complex")
  1613. }
  1614. if !v.r.IsInt() {
  1615. return 0, errors.New("value is not an integer")
  1616. }
  1617. if v.r.Sign() == -1 {
  1618. return 0, errors.New("value is negative")
  1619. }
  1620. i, _ := v.r.Int(nil)
  1621. if i.Cmp(bigIntMaxUint64) == +1 {
  1622. return 0, errors.New("value is too large")
  1623. }
  1624. return i.Uint64(), nil
  1625. }
  1626. return 0, fmt.Errorf("cannot convert to unsigned integer")
  1627. }
  1628. // followTypedefs returns the underlying type of t, removing any typedefs.
  1629. // If t leads to a cycle of typedefs, followTypedefs returns nil.
  1630. func followTypedefs(t dwarf.Type) dwarf.Type {
  1631. // If t is a *dwarf.TypedefType, next returns t.Type, otherwise it returns t.
  1632. // The bool returned is true when the argument was a typedef.
  1633. next := func(t dwarf.Type) (dwarf.Type, bool) {
  1634. tt, ok := t.(*dwarf.TypedefType)
  1635. if !ok {
  1636. return t, false
  1637. }
  1638. return tt.Type, true
  1639. }
  1640. // Advance two pointers, one at twice the speed, so we can detect if we get
  1641. // stuck in a cycle.
  1642. slow, fast := t, t
  1643. for {
  1644. var wasTypedef bool
  1645. fast, wasTypedef = next(fast)
  1646. if !wasTypedef {
  1647. return fast
  1648. }
  1649. fast, wasTypedef = next(fast)
  1650. if !wasTypedef {
  1651. return fast
  1652. }
  1653. slow, _ = next(slow)
  1654. if slow == fast {
  1655. return nil
  1656. }
  1657. }
  1658. }