debug.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Copyright 2014 beego Author. 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. package utils
  15. import (
  16. "bytes"
  17. "fmt"
  18. "log"
  19. "reflect"
  20. "runtime"
  21. )
  22. var (
  23. dunno = []byte("???")
  24. centerDot = []byte("·")
  25. dot = []byte(".")
  26. )
  27. type pointerInfo struct {
  28. prev *pointerInfo
  29. n int
  30. addr uintptr
  31. pos int
  32. used []int
  33. }
  34. // Display print the data in console
  35. func Display(data ...interface{}) {
  36. display(true, data...)
  37. }
  38. // GetDisplayString return data print string
  39. func GetDisplayString(data ...interface{}) string {
  40. return display(false, data...)
  41. }
  42. func display(displayed bool, data ...interface{}) string {
  43. var pc, file, line, ok = runtime.Caller(2)
  44. if !ok {
  45. return ""
  46. }
  47. var buf = new(bytes.Buffer)
  48. fmt.Fprintf(buf, "[Debug] at %s() [%s:%d]\n", function(pc), file, line)
  49. fmt.Fprintf(buf, "\n[Variables]\n")
  50. for i := 0; i < len(data); i += 2 {
  51. var output = fomateinfo(len(data[i].(string))+3, data[i+1])
  52. fmt.Fprintf(buf, "%s = %s", data[i], output)
  53. }
  54. if displayed {
  55. log.Print(buf)
  56. }
  57. return buf.String()
  58. }
  59. // return data dump and format bytes
  60. func fomateinfo(headlen int, data ...interface{}) []byte {
  61. var buf = new(bytes.Buffer)
  62. if len(data) > 1 {
  63. fmt.Fprint(buf, " ")
  64. fmt.Fprint(buf, "[")
  65. fmt.Fprintln(buf)
  66. }
  67. for k, v := range data {
  68. var buf2 = new(bytes.Buffer)
  69. var pointers *pointerInfo
  70. var interfaces = make([]reflect.Value, 0, 10)
  71. printKeyValue(buf2, reflect.ValueOf(v), &pointers, &interfaces, nil, true, " ", 1)
  72. if k < len(data)-1 {
  73. fmt.Fprint(buf2, ", ")
  74. }
  75. fmt.Fprintln(buf2)
  76. buf.Write(buf2.Bytes())
  77. }
  78. if len(data) > 1 {
  79. fmt.Fprintln(buf)
  80. fmt.Fprint(buf, " ")
  81. fmt.Fprint(buf, "]")
  82. }
  83. return buf.Bytes()
  84. }
  85. // check data is golang basic type
  86. func isSimpleType(val reflect.Value, kind reflect.Kind, pointers **pointerInfo, interfaces *[]reflect.Value) bool {
  87. switch kind {
  88. case reflect.Bool:
  89. return true
  90. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  91. return true
  92. case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
  93. return true
  94. case reflect.Float32, reflect.Float64:
  95. return true
  96. case reflect.Complex64, reflect.Complex128:
  97. return true
  98. case reflect.String:
  99. return true
  100. case reflect.Chan:
  101. return true
  102. case reflect.Invalid:
  103. return true
  104. case reflect.Interface:
  105. for _, in := range *interfaces {
  106. if reflect.DeepEqual(in, val) {
  107. return true
  108. }
  109. }
  110. return false
  111. case reflect.UnsafePointer:
  112. if val.IsNil() {
  113. return true
  114. }
  115. var elem = val.Elem()
  116. if isSimpleType(elem, elem.Kind(), pointers, interfaces) {
  117. return true
  118. }
  119. var addr = val.Elem().UnsafeAddr()
  120. for p := *pointers; p != nil; p = p.prev {
  121. if addr == p.addr {
  122. return true
  123. }
  124. }
  125. return false
  126. }
  127. return false
  128. }
  129. // dump value
  130. func printKeyValue(buf *bytes.Buffer, val reflect.Value, pointers **pointerInfo, interfaces *[]reflect.Value, structFilter func(string, string) bool, formatOutput bool, indent string, level int) {
  131. var t = val.Kind()
  132. switch t {
  133. case reflect.Bool:
  134. fmt.Fprint(buf, val.Bool())
  135. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  136. fmt.Fprint(buf, val.Int())
  137. case reflect.Uint8, reflect.Uint16, reflect.Uint, reflect.Uint32, reflect.Uint64:
  138. fmt.Fprint(buf, val.Uint())
  139. case reflect.Float32, reflect.Float64:
  140. fmt.Fprint(buf, val.Float())
  141. case reflect.Complex64, reflect.Complex128:
  142. fmt.Fprint(buf, val.Complex())
  143. case reflect.UnsafePointer:
  144. fmt.Fprintf(buf, "unsafe.Pointer(0x%X)", val.Pointer())
  145. case reflect.Ptr:
  146. if val.IsNil() {
  147. fmt.Fprint(buf, "nil")
  148. return
  149. }
  150. var addr = val.Elem().UnsafeAddr()
  151. for p := *pointers; p != nil; p = p.prev {
  152. if addr == p.addr {
  153. p.used = append(p.used, buf.Len())
  154. fmt.Fprintf(buf, "0x%X", addr)
  155. return
  156. }
  157. }
  158. *pointers = &pointerInfo{
  159. prev: *pointers,
  160. addr: addr,
  161. pos: buf.Len(),
  162. used: make([]int, 0),
  163. }
  164. fmt.Fprint(buf, "&")
  165. printKeyValue(buf, val.Elem(), pointers, interfaces, structFilter, formatOutput, indent, level)
  166. case reflect.String:
  167. fmt.Fprint(buf, "\"", val.String(), "\"")
  168. case reflect.Interface:
  169. var value = val.Elem()
  170. if !value.IsValid() {
  171. fmt.Fprint(buf, "nil")
  172. } else {
  173. for _, in := range *interfaces {
  174. if reflect.DeepEqual(in, val) {
  175. fmt.Fprint(buf, "repeat")
  176. return
  177. }
  178. }
  179. *interfaces = append(*interfaces, val)
  180. printKeyValue(buf, value, pointers, interfaces, structFilter, formatOutput, indent, level+1)
  181. }
  182. case reflect.Struct:
  183. var t = val.Type()
  184. fmt.Fprint(buf, t)
  185. fmt.Fprint(buf, "{")
  186. for i := 0; i < val.NumField(); i++ {
  187. if formatOutput {
  188. fmt.Fprintln(buf)
  189. } else {
  190. fmt.Fprint(buf, " ")
  191. }
  192. var name = t.Field(i).Name
  193. if formatOutput {
  194. for ind := 0; ind < level; ind++ {
  195. fmt.Fprint(buf, indent)
  196. }
  197. }
  198. fmt.Fprint(buf, name)
  199. fmt.Fprint(buf, ": ")
  200. if structFilter != nil && structFilter(t.String(), name) {
  201. fmt.Fprint(buf, "ignore")
  202. } else {
  203. printKeyValue(buf, val.Field(i), pointers, interfaces, structFilter, formatOutput, indent, level+1)
  204. }
  205. fmt.Fprint(buf, ",")
  206. }
  207. if formatOutput {
  208. fmt.Fprintln(buf)
  209. for ind := 0; ind < level-1; ind++ {
  210. fmt.Fprint(buf, indent)
  211. }
  212. } else {
  213. fmt.Fprint(buf, " ")
  214. }
  215. fmt.Fprint(buf, "}")
  216. case reflect.Array, reflect.Slice:
  217. fmt.Fprint(buf, val.Type())
  218. fmt.Fprint(buf, "{")
  219. var allSimple = true
  220. for i := 0; i < val.Len(); i++ {
  221. var elem = val.Index(i)
  222. var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces)
  223. if !isSimple {
  224. allSimple = false
  225. }
  226. if formatOutput && !isSimple {
  227. fmt.Fprintln(buf)
  228. } else {
  229. fmt.Fprint(buf, " ")
  230. }
  231. if formatOutput && !isSimple {
  232. for ind := 0; ind < level; ind++ {
  233. fmt.Fprint(buf, indent)
  234. }
  235. }
  236. printKeyValue(buf, elem, pointers, interfaces, structFilter, formatOutput, indent, level+1)
  237. if i != val.Len()-1 || !allSimple {
  238. fmt.Fprint(buf, ",")
  239. }
  240. }
  241. if formatOutput && !allSimple {
  242. fmt.Fprintln(buf)
  243. for ind := 0; ind < level-1; ind++ {
  244. fmt.Fprint(buf, indent)
  245. }
  246. } else {
  247. fmt.Fprint(buf, " ")
  248. }
  249. fmt.Fprint(buf, "}")
  250. case reflect.Map:
  251. var t = val.Type()
  252. var keys = val.MapKeys()
  253. fmt.Fprint(buf, t)
  254. fmt.Fprint(buf, "{")
  255. var allSimple = true
  256. for i := 0; i < len(keys); i++ {
  257. var elem = val.MapIndex(keys[i])
  258. var isSimple = isSimpleType(elem, elem.Kind(), pointers, interfaces)
  259. if !isSimple {
  260. allSimple = false
  261. }
  262. if formatOutput && !isSimple {
  263. fmt.Fprintln(buf)
  264. } else {
  265. fmt.Fprint(buf, " ")
  266. }
  267. if formatOutput && !isSimple {
  268. for ind := 0; ind <= level; ind++ {
  269. fmt.Fprint(buf, indent)
  270. }
  271. }
  272. printKeyValue(buf, keys[i], pointers, interfaces, structFilter, formatOutput, indent, level+1)
  273. fmt.Fprint(buf, ": ")
  274. printKeyValue(buf, elem, pointers, interfaces, structFilter, formatOutput, indent, level+1)
  275. if i != val.Len()-1 || !allSimple {
  276. fmt.Fprint(buf, ",")
  277. }
  278. }
  279. if formatOutput && !allSimple {
  280. fmt.Fprintln(buf)
  281. for ind := 0; ind < level-1; ind++ {
  282. fmt.Fprint(buf, indent)
  283. }
  284. } else {
  285. fmt.Fprint(buf, " ")
  286. }
  287. fmt.Fprint(buf, "}")
  288. case reflect.Chan:
  289. fmt.Fprint(buf, val.Type())
  290. case reflect.Invalid:
  291. fmt.Fprint(buf, "invalid")
  292. default:
  293. fmt.Fprint(buf, "unknow")
  294. }
  295. }
  296. // PrintPointerInfo dump pointer value
  297. func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo) {
  298. var anyused = false
  299. var pointerNum = 0
  300. for p := pointers; p != nil; p = p.prev {
  301. if len(p.used) > 0 {
  302. anyused = true
  303. }
  304. pointerNum++
  305. p.n = pointerNum
  306. }
  307. if anyused {
  308. var pointerBufs = make([][]rune, pointerNum+1)
  309. for i := 0; i < len(pointerBufs); i++ {
  310. var pointerBuf = make([]rune, buf.Len()+headlen)
  311. for j := 0; j < len(pointerBuf); j++ {
  312. pointerBuf[j] = ' '
  313. }
  314. pointerBufs[i] = pointerBuf
  315. }
  316. for pn := 0; pn <= pointerNum; pn++ {
  317. for p := pointers; p != nil; p = p.prev {
  318. if len(p.used) > 0 && p.n >= pn {
  319. if pn == p.n {
  320. pointerBufs[pn][p.pos+headlen] = '└'
  321. var maxpos = 0
  322. for i, pos := range p.used {
  323. if i < len(p.used)-1 {
  324. pointerBufs[pn][pos+headlen] = '┴'
  325. } else {
  326. pointerBufs[pn][pos+headlen] = '┘'
  327. }
  328. maxpos = pos
  329. }
  330. for i := 0; i < maxpos-p.pos-1; i++ {
  331. if pointerBufs[pn][i+p.pos+headlen+1] == ' ' {
  332. pointerBufs[pn][i+p.pos+headlen+1] = '─'
  333. }
  334. }
  335. } else {
  336. pointerBufs[pn][p.pos+headlen] = '│'
  337. for _, pos := range p.used {
  338. if pointerBufs[pn][pos+headlen] == ' ' {
  339. pointerBufs[pn][pos+headlen] = '│'
  340. } else {
  341. pointerBufs[pn][pos+headlen] = '┼'
  342. }
  343. }
  344. }
  345. }
  346. }
  347. buf.WriteString(string(pointerBufs[pn]) + "\n")
  348. }
  349. }
  350. }
  351. // Stack get stack bytes
  352. func Stack(skip int, indent string) []byte {
  353. var buf = new(bytes.Buffer)
  354. for i := skip; ; i++ {
  355. var pc, file, line, ok = runtime.Caller(i)
  356. if !ok {
  357. break
  358. }
  359. buf.WriteString(indent)
  360. fmt.Fprintf(buf, "at %s() [%s:%d]\n", function(pc), file, line)
  361. }
  362. return buf.Bytes()
  363. }
  364. // return the name of the function containing the PC if possible,
  365. func function(pc uintptr) []byte {
  366. fn := runtime.FuncForPC(pc)
  367. if fn == nil {
  368. return dunno
  369. }
  370. name := []byte(fn.Name())
  371. // The name includes the path name to the package, which is unnecessary
  372. // since the file name is already included. Plus, it has center dots.
  373. // That is, we see
  374. // runtime/debug.*T·ptrmethod
  375. // and want
  376. // *T.ptrmethod
  377. if period := bytes.Index(name, dot); period >= 0 {
  378. name = name[period+1:]
  379. }
  380. name = bytes.Replace(name, centerDot, dot, -1)
  381. return name
  382. }