common.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. * Copyright (c) 2013 Dave Collins <dave@davec.name>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. package spew
  17. import (
  18. "fmt"
  19. "io"
  20. "reflect"
  21. "sort"
  22. "strconv"
  23. "unsafe"
  24. )
  25. const (
  26. // ptrSize is the size of a pointer on the current arch.
  27. ptrSize = unsafe.Sizeof((*byte)(nil))
  28. )
  29. var (
  30. // offsetPtr, offsetScalar, and offsetFlag are the offsets for the
  31. // internal reflect.Value fields. These values are valid before golang
  32. // commit ecccf07e7f9d which changed the format. The are also valid
  33. // after commit 82f48826c6c7 which changed the format again to mirror
  34. // the original format. Code in the init function updates these offsets
  35. // as necessary.
  36. offsetPtr = uintptr(ptrSize)
  37. offsetScalar = uintptr(0)
  38. offsetFlag = uintptr(ptrSize * 2)
  39. // flagKindWidth and flagKindShift indicate various bits that the
  40. // reflect package uses internally to track kind information.
  41. //
  42. // flagRO indicates whether or not the value field of a reflect.Value is
  43. // read-only.
  44. //
  45. // flagIndir indicates whether the value field of a reflect.Value is
  46. // the actual data or a pointer to the data.
  47. //
  48. // These values are valid before golang commit 90a7c3c86944 which
  49. // changed their positions. Code in the init function updates these
  50. // flags as necessary.
  51. flagKindWidth = uintptr(5)
  52. flagKindShift = uintptr(flagKindWidth - 1)
  53. flagRO = uintptr(1 << 0)
  54. flagIndir = uintptr(1 << 1)
  55. )
  56. func init() {
  57. // Older versions of reflect.Value stored small integers directly in the
  58. // ptr field (which is named val in the older versions). Versions
  59. // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
  60. // scalar for this purpose which unfortunately came before the flag
  61. // field, so the offset of the flag field is different for those
  62. // versions.
  63. //
  64. // This code constructs a new reflect.Value from a known small integer
  65. // and checks if the size of the reflect.Value struct indicates it has
  66. // the scalar field. When it does, the offsets are updated accordingly.
  67. vv := reflect.ValueOf(0xf00)
  68. if unsafe.Sizeof(vv) == (ptrSize * 4) {
  69. offsetScalar = ptrSize * 2
  70. offsetFlag = ptrSize * 3
  71. }
  72. // Commit 90a7c3c86944 changed the flag positions such that the low
  73. // order bits are the kind. This code extracts the kind from the flags
  74. // field and ensures it's the correct type. When it's not, the flag
  75. // order has been changed to the newer format, so the flags are updated
  76. // accordingly.
  77. upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
  78. upfv := *(*uintptr)(upf)
  79. flagKindMask := uintptr((1<<flagKindWidth - 1) << flagKindShift)
  80. if (upfv&flagKindMask)>>flagKindShift != uintptr(reflect.Int) {
  81. flagKindShift = 0
  82. flagRO = 1 << 5
  83. flagIndir = 1 << 6
  84. }
  85. }
  86. // unsafeReflectValue converts the passed reflect.Value into a one that bypasses
  87. // the typical safety restrictions preventing access to unaddressable and
  88. // unexported data. It works by digging the raw pointer to the underlying
  89. // value out of the protected value and generating a new unprotected (unsafe)
  90. // reflect.Value to it.
  91. //
  92. // This allows us to check for implementations of the Stringer and error
  93. // interfaces to be used for pretty printing ordinarily unaddressable and
  94. // inaccessible values such as unexported struct fields.
  95. func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
  96. indirects := 1
  97. vt := v.Type()
  98. upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
  99. rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
  100. if rvf&flagIndir != 0 {
  101. vt = reflect.PtrTo(v.Type())
  102. indirects++
  103. } else if offsetScalar != 0 {
  104. // The value is in the scalar field when it's not one of the
  105. // reference types.
  106. switch vt.Kind() {
  107. case reflect.Uintptr:
  108. case reflect.Chan:
  109. case reflect.Func:
  110. case reflect.Map:
  111. case reflect.Ptr:
  112. case reflect.UnsafePointer:
  113. default:
  114. upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
  115. offsetScalar)
  116. }
  117. }
  118. pv := reflect.NewAt(vt, upv)
  119. rv = pv
  120. for i := 0; i < indirects; i++ {
  121. rv = rv.Elem()
  122. }
  123. return rv
  124. }
  125. // Some constants in the form of bytes to avoid string overhead. This mirrors
  126. // the technique used in the fmt package.
  127. var (
  128. panicBytes = []byte("(PANIC=")
  129. plusBytes = []byte("+")
  130. iBytes = []byte("i")
  131. trueBytes = []byte("true")
  132. falseBytes = []byte("false")
  133. interfaceBytes = []byte("(interface {})")
  134. commaNewlineBytes = []byte(",\n")
  135. newlineBytes = []byte("\n")
  136. openBraceBytes = []byte("{")
  137. openBraceNewlineBytes = []byte("{\n")
  138. closeBraceBytes = []byte("}")
  139. asteriskBytes = []byte("*")
  140. colonBytes = []byte(":")
  141. colonSpaceBytes = []byte(": ")
  142. openParenBytes = []byte("(")
  143. closeParenBytes = []byte(")")
  144. spaceBytes = []byte(" ")
  145. pointerChainBytes = []byte("->")
  146. nilAngleBytes = []byte("<nil>")
  147. maxNewlineBytes = []byte("<max depth reached>\n")
  148. maxShortBytes = []byte("<max>")
  149. circularBytes = []byte("<already shown>")
  150. circularShortBytes = []byte("<shown>")
  151. invalidAngleBytes = []byte("<invalid>")
  152. openBracketBytes = []byte("[")
  153. closeBracketBytes = []byte("]")
  154. percentBytes = []byte("%")
  155. precisionBytes = []byte(".")
  156. openAngleBytes = []byte("<")
  157. closeAngleBytes = []byte(">")
  158. openMapBytes = []byte("map[")
  159. closeMapBytes = []byte("]")
  160. lenEqualsBytes = []byte("len=")
  161. capEqualsBytes = []byte("cap=")
  162. )
  163. // hexDigits is used to map a decimal value to a hex digit.
  164. var hexDigits = "0123456789abcdef"
  165. // catchPanic handles any panics that might occur during the handleMethods
  166. // calls.
  167. func catchPanic(w io.Writer, v reflect.Value) {
  168. if err := recover(); err != nil {
  169. w.Write(panicBytes)
  170. fmt.Fprintf(w, "%v", err)
  171. w.Write(closeParenBytes)
  172. }
  173. }
  174. // handleMethods attempts to call the Error and String methods on the underlying
  175. // type the passed reflect.Value represents and outputes the result to Writer w.
  176. //
  177. // It handles panics in any called methods by catching and displaying the error
  178. // as the formatted value.
  179. func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
  180. // We need an interface to check if the type implements the error or
  181. // Stringer interface. However, the reflect package won't give us an
  182. // interface on certain things like unexported struct fields in order
  183. // to enforce visibility rules. We use unsafe to bypass these restrictions
  184. // since this package does not mutate the values.
  185. if !v.CanInterface() {
  186. v = unsafeReflectValue(v)
  187. }
  188. // Choose whether or not to do error and Stringer interface lookups against
  189. // the base type or a pointer to the base type depending on settings.
  190. // Technically calling one of these methods with a pointer receiver can
  191. // mutate the value, however, types which choose to satisify an error or
  192. // Stringer interface with a pointer receiver should not be mutating their
  193. // state inside these interface methods.
  194. var viface interface{}
  195. if !cs.DisablePointerMethods {
  196. if !v.CanAddr() {
  197. v = unsafeReflectValue(v)
  198. }
  199. viface = v.Addr().Interface()
  200. } else {
  201. if v.CanAddr() {
  202. v = v.Addr()
  203. }
  204. viface = v.Interface()
  205. }
  206. // Is it an error or Stringer?
  207. switch iface := viface.(type) {
  208. case error:
  209. defer catchPanic(w, v)
  210. if cs.ContinueOnMethod {
  211. w.Write(openParenBytes)
  212. w.Write([]byte(iface.Error()))
  213. w.Write(closeParenBytes)
  214. w.Write(spaceBytes)
  215. return false
  216. }
  217. w.Write([]byte(iface.Error()))
  218. return true
  219. case fmt.Stringer:
  220. defer catchPanic(w, v)
  221. if cs.ContinueOnMethod {
  222. w.Write(openParenBytes)
  223. w.Write([]byte(iface.String()))
  224. w.Write(closeParenBytes)
  225. w.Write(spaceBytes)
  226. return false
  227. }
  228. w.Write([]byte(iface.String()))
  229. return true
  230. }
  231. return false
  232. }
  233. // printBool outputs a boolean value as true or false to Writer w.
  234. func printBool(w io.Writer, val bool) {
  235. if val {
  236. w.Write(trueBytes)
  237. } else {
  238. w.Write(falseBytes)
  239. }
  240. }
  241. // printInt outputs a signed integer value to Writer w.
  242. func printInt(w io.Writer, val int64, base int) {
  243. w.Write([]byte(strconv.FormatInt(val, base)))
  244. }
  245. // printUint outputs an unsigned integer value to Writer w.
  246. func printUint(w io.Writer, val uint64, base int) {
  247. w.Write([]byte(strconv.FormatUint(val, base)))
  248. }
  249. // printFloat outputs a floating point value using the specified precision,
  250. // which is expected to be 32 or 64bit, to Writer w.
  251. func printFloat(w io.Writer, val float64, precision int) {
  252. w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
  253. }
  254. // printComplex outputs a complex value using the specified float precision
  255. // for the real and imaginary parts to Writer w.
  256. func printComplex(w io.Writer, c complex128, floatPrecision int) {
  257. r := real(c)
  258. w.Write(openParenBytes)
  259. w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
  260. i := imag(c)
  261. if i >= 0 {
  262. w.Write(plusBytes)
  263. }
  264. w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
  265. w.Write(iBytes)
  266. w.Write(closeParenBytes)
  267. }
  268. // printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
  269. // prefix to Writer w.
  270. func printHexPtr(w io.Writer, p uintptr) {
  271. // Null pointer.
  272. num := uint64(p)
  273. if num == 0 {
  274. w.Write(nilAngleBytes)
  275. return
  276. }
  277. // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
  278. buf := make([]byte, 18)
  279. // It's simpler to construct the hex string right to left.
  280. base := uint64(16)
  281. i := len(buf) - 1
  282. for num >= base {
  283. buf[i] = hexDigits[num%base]
  284. num /= base
  285. i--
  286. }
  287. buf[i] = hexDigits[num]
  288. // Add '0x' prefix.
  289. i--
  290. buf[i] = 'x'
  291. i--
  292. buf[i] = '0'
  293. // Strip unused leading bytes.
  294. buf = buf[i:]
  295. w.Write(buf)
  296. }
  297. // valuesSorter implements sort.Interface to allow a slice of reflect.Value
  298. // elements to be sorted.
  299. type valuesSorter struct {
  300. values []reflect.Value
  301. }
  302. // Len returns the number of values in the slice. It is part of the
  303. // sort.Interface implementation.
  304. func (s *valuesSorter) Len() int {
  305. return len(s.values)
  306. }
  307. // Swap swaps the values at the passed indices. It is part of the
  308. // sort.Interface implementation.
  309. func (s *valuesSorter) Swap(i, j int) {
  310. s.values[i], s.values[j] = s.values[j], s.values[i]
  311. }
  312. // valueSortLess returns whether the first value should sort before the second
  313. // value. It is used by valueSorter.Less as part of the sort.Interface
  314. // implementation.
  315. func valueSortLess(a, b reflect.Value) bool {
  316. switch a.Kind() {
  317. case reflect.Bool:
  318. return !a.Bool() && b.Bool()
  319. case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
  320. return a.Int() < b.Int()
  321. case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
  322. return a.Uint() < b.Uint()
  323. case reflect.Float32, reflect.Float64:
  324. return a.Float() < b.Float()
  325. case reflect.String:
  326. return a.String() < b.String()
  327. case reflect.Uintptr:
  328. return a.Uint() < b.Uint()
  329. case reflect.Array:
  330. // Compare the contents of both arrays.
  331. l := a.Len()
  332. for i := 0; i < l; i++ {
  333. av := a.Index(i)
  334. bv := b.Index(i)
  335. if av.Interface() == bv.Interface() {
  336. continue
  337. }
  338. return valueSortLess(av, bv)
  339. }
  340. }
  341. return a.String() < b.String()
  342. }
  343. // Less returns whether the value at index i should sort before the
  344. // value at index j. It is part of the sort.Interface implementation.
  345. func (s *valuesSorter) Less(i, j int) bool {
  346. return valueSortLess(s.values[i], s.values[j])
  347. }
  348. // sortValues is a generic sort function for native types: int, uint, bool,
  349. // string and uintptr. Other inputs are sorted according to their
  350. // Value.String() value to ensure display stability.
  351. func sortValues(values []reflect.Value) {
  352. if len(values) == 0 {
  353. return
  354. }
  355. sort.Sort(&valuesSorter{values})
  356. }