sighashes.nim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Computes hash values for routine (proc, method etc) signatures.
  10. import ast, tables, ropes, md5_old, modulegraphs
  11. from hashes import Hash
  12. import types
  13. when defined(nimPreviewSlimSystem):
  14. import std/assertions
  15. proc `&=`(c: var MD5Context, s: string) = md5Update(c, s, s.len)
  16. proc `&=`(c: var MD5Context, ch: char) =
  17. # XXX suspicious code here; relies on ch being zero terminated?
  18. md5Update(c, cast[cstring](unsafeAddr ch), 1)
  19. proc `&=`(c: var MD5Context, i: BiggestInt) =
  20. md5Update(c, cast[cstring](unsafeAddr i), sizeof(i))
  21. proc `&=`(c: var MD5Context, f: BiggestFloat) =
  22. md5Update(c, cast[cstring](unsafeAddr f), sizeof(f))
  23. proc `&=`(c: var MD5Context, s: SigHash) =
  24. md5Update(c, cast[cstring](unsafeAddr s), sizeof(s))
  25. template lowlevel(v) =
  26. md5Update(c, cast[cstring](unsafeAddr(v)), sizeof(v))
  27. type
  28. ConsiderFlag* = enum
  29. CoProc
  30. CoType
  31. CoOwnerSig
  32. CoIgnoreRange
  33. CoConsiderOwned
  34. CoDistinct
  35. CoHashTypeInsideNode
  36. proc hashType(c: var MD5Context, t: PType; flags: set[ConsiderFlag])
  37. proc hashSym(c: var MD5Context, s: PSym) =
  38. if sfAnon in s.flags or s.kind == skGenericParam:
  39. c &= ":anon"
  40. else:
  41. var it = s
  42. while it != nil:
  43. c &= it.name.s
  44. c &= "."
  45. it = it.owner
  46. proc hashTypeSym(c: var MD5Context, s: PSym) =
  47. if sfAnon in s.flags or s.kind == skGenericParam:
  48. c &= ":anon"
  49. else:
  50. var it = s
  51. while it != nil:
  52. if sfFromGeneric in it.flags and it.kind in routineKinds and
  53. it.typ != nil:
  54. hashType c, it.typ, {CoProc}
  55. c &= it.name.s
  56. c &= "."
  57. it = it.owner
  58. proc hashTree(c: var MD5Context, n: PNode; flags: set[ConsiderFlag]) =
  59. if n == nil:
  60. c &= "\255"
  61. return
  62. let k = n.kind
  63. c &= char(k)
  64. # we really must not hash line information. 'n.typ' is debatable but
  65. # shouldn't be necessary for now and avoids potential infinite recursions.
  66. case n.kind
  67. of nkEmpty, nkNilLit, nkType: discard
  68. of nkIdent:
  69. c &= n.ident.s
  70. of nkSym:
  71. hashSym(c, n.sym)
  72. if CoHashTypeInsideNode in flags and n.sym.typ != nil:
  73. hashType(c, n.sym.typ, flags)
  74. of nkCharLit..nkUInt64Lit:
  75. let v = n.intVal
  76. lowlevel v
  77. of nkFloatLit..nkFloat64Lit:
  78. let v = n.floatVal
  79. lowlevel v
  80. of nkStrLit..nkTripleStrLit:
  81. c &= n.strVal
  82. else:
  83. for i in 0..<n.len: hashTree(c, n[i], flags)
  84. proc hashType(c: var MD5Context, t: PType; flags: set[ConsiderFlag]) =
  85. if t == nil:
  86. c &= "\254"
  87. return
  88. case t.kind
  89. of tyGenericInvocation:
  90. for i in 0..<t.len:
  91. c.hashType t[i], flags
  92. of tyDistinct:
  93. if CoDistinct in flags:
  94. if t.sym != nil: c.hashSym(t.sym)
  95. if t.sym == nil or tfFromGeneric in t.flags:
  96. c.hashType t.lastSon, flags
  97. elif CoType in flags or t.sym == nil:
  98. c.hashType t.lastSon, flags
  99. else:
  100. c.hashSym(t.sym)
  101. of tyGenericInst:
  102. if sfInfixCall in t.base.sym.flags:
  103. # This is an imported C++ generic type.
  104. # We cannot trust the `lastSon` to hold a properly populated and unique
  105. # value for each instantiation, so we hash the generic parameters here:
  106. let normalizedType = t.skipGenericAlias
  107. for i in 0..<normalizedType.len - 1:
  108. c.hashType t[i], flags
  109. else:
  110. c.hashType t.lastSon, flags
  111. of tyAlias, tySink, tyUserTypeClasses, tyInferred:
  112. c.hashType t.lastSon, flags
  113. of tyOwned:
  114. if CoConsiderOwned in flags:
  115. c &= char(t.kind)
  116. c.hashType t.lastSon, flags
  117. of tyBool, tyChar, tyInt..tyUInt64:
  118. # no canonicalization for integral types, so that e.g. ``pid_t`` is
  119. # produced instead of ``NI``:
  120. c &= char(t.kind)
  121. if t.sym != nil and {sfImportc, sfExportc} * t.sym.flags != {}:
  122. c.hashSym(t.sym)
  123. of tyObject, tyEnum:
  124. if t.typeInst != nil:
  125. # prevent against infinite recursions here, see bug #8883:
  126. let inst = t.typeInst
  127. t.typeInst = nil
  128. assert inst.kind == tyGenericInst
  129. for i in 0..<inst.len - 1:
  130. c.hashType inst[i], flags
  131. t.typeInst = inst
  132. return
  133. c &= char(t.kind)
  134. # Every cyclic type in Nim need to be constructed via some 't.sym', so this
  135. # is actually safe without an infinite recursion check:
  136. if t.sym != nil:
  137. if {sfCompilerProc} * t.sym.flags != {}:
  138. doAssert t.sym.loc.r != ""
  139. # The user has set a specific name for this type
  140. c &= t.sym.loc.r
  141. elif CoOwnerSig in flags:
  142. c.hashTypeSym(t.sym)
  143. else:
  144. c.hashSym(t.sym)
  145. var symWithFlags: PSym
  146. template hasFlag(sym): bool =
  147. let ret = {sfAnon, sfGenSym} * sym.flags != {}
  148. if ret: symWithFlags = sym
  149. ret
  150. if hasFlag(t.sym) or (t.kind == tyObject and t.owner.kind == skType and t.owner.typ.kind == tyRef and hasFlag(t.owner)):
  151. # for `PFoo:ObjectType`, arising from `type PFoo = ref object`
  152. # Generated object names can be identical, so we need to
  153. # disambiguate furthermore by hashing the field types and names.
  154. if t.n.len > 0:
  155. let oldFlags = symWithFlags.flags
  156. # Hack to prevent endless recursion
  157. # xxx instead, use a hash table to indicate we've already visited a type, which
  158. # would also be more efficient.
  159. symWithFlags.flags.excl {sfAnon, sfGenSym}
  160. hashTree(c, t.n, flags + {CoHashTypeInsideNode})
  161. symWithFlags.flags = oldFlags
  162. else:
  163. # The object has no fields: we _must_ add something here in order to
  164. # make the hash different from the one we produce by hashing only the
  165. # type name.
  166. c &= ".empty"
  167. else:
  168. c &= t.id
  169. if t.len > 0 and t[0] != nil:
  170. hashType c, t[0], flags
  171. of tyRef, tyPtr, tyGenericBody, tyVar:
  172. c &= char(t.kind)
  173. if t.sons.len > 0:
  174. c.hashType t.lastSon, flags
  175. if tfVarIsPtr in t.flags: c &= ".varisptr"
  176. of tyFromExpr:
  177. c &= char(t.kind)
  178. c.hashTree(t.n, {})
  179. of tyTuple:
  180. c &= char(t.kind)
  181. if t.n != nil and CoType notin flags:
  182. assert(t.n.len == t.len)
  183. for i in 0..<t.n.len:
  184. assert(t.n[i].kind == nkSym)
  185. c &= t.n[i].sym.name.s
  186. c &= ':'
  187. c.hashType(t[i], flags+{CoIgnoreRange})
  188. c &= ','
  189. else:
  190. for i in 0..<t.len: c.hashType t[i], flags+{CoIgnoreRange}
  191. of tyRange:
  192. if CoIgnoreRange notin flags:
  193. c &= char(t.kind)
  194. c.hashTree(t.n, {})
  195. c.hashType(t[0], flags)
  196. of tyStatic:
  197. c &= char(t.kind)
  198. c.hashTree(t.n, {})
  199. c.hashType(t[0], flags)
  200. of tyProc:
  201. c &= char(t.kind)
  202. c &= (if tfIterator in t.flags: "iterator " else: "proc ")
  203. if CoProc in flags and t.n != nil:
  204. let params = t.n
  205. for i in 1..<params.len:
  206. let param = params[i].sym
  207. c &= param.name.s
  208. c &= ':'
  209. c.hashType(param.typ, flags)
  210. c &= ','
  211. c.hashType(t[0], flags)
  212. else:
  213. for i in 0..<t.len: c.hashType(t[i], flags)
  214. c &= char(t.callConv)
  215. # purity of functions doesn't have to affect the mangling (which is in fact
  216. # problematic for HCR - someone could have cached a pointer to another
  217. # function which changes its purity and suddenly the cached pointer is danglign)
  218. # IMHO anything that doesn't affect the overload resolution shouldn't be part of the mangling...
  219. # if CoType notin flags:
  220. # if tfNoSideEffect in t.flags: c &= ".noSideEffect"
  221. # if tfThread in t.flags: c &= ".thread"
  222. if tfVarargs in t.flags: c &= ".varargs"
  223. of tyArray:
  224. c &= char(t.kind)
  225. for i in 0..<t.len: c.hashType(t[i], flags-{CoIgnoreRange})
  226. else:
  227. c &= char(t.kind)
  228. for i in 0..<t.len: c.hashType(t[i], flags)
  229. if tfNotNil in t.flags and CoType notin flags: c &= "not nil"
  230. when defined(debugSigHashes):
  231. import db_sqlite
  232. let db = open(connection="sighashes.db", user="araq", password="",
  233. database="sighashes")
  234. db.exec(sql"DROP TABLE IF EXISTS sighashes")
  235. db.exec sql"""CREATE TABLE sighashes(
  236. id integer primary key,
  237. hash varchar(5000) not null,
  238. type varchar(5000) not null,
  239. unique (hash, type))"""
  240. # select hash, type from sighashes where hash in
  241. # (select hash from sighashes group by hash having count(*) > 1) order by hash;
  242. proc hashType*(t: PType; flags: set[ConsiderFlag] = {CoType}): SigHash =
  243. var c: MD5Context
  244. md5Init c
  245. hashType c, t, flags+{CoOwnerSig}
  246. md5Final c, result.MD5Digest
  247. when defined(debugSigHashes):
  248. db.exec(sql"INSERT OR IGNORE INTO sighashes(type, hash) VALUES (?, ?)",
  249. typeToString(t), $result)
  250. proc hashProc*(s: PSym): SigHash =
  251. var c: MD5Context
  252. md5Init c
  253. hashType c, s.typ, {CoProc}
  254. var m = s
  255. while m.kind != skModule: m = m.owner
  256. let p = m.owner
  257. assert p.kind == skPackage
  258. c &= p.name.s
  259. c &= "."
  260. c &= m.name.s
  261. if sfDispatcher in s.flags:
  262. c &= ".dispatcher"
  263. # so that createThread[void]() (aka generic specialization) gets a unique
  264. # hash, we also hash the line information. This is pretty bad, but the best
  265. # solution for now:
  266. #c &= s.info.line
  267. md5Final c, result.MD5Digest
  268. proc hashNonProc*(s: PSym): SigHash =
  269. var c: MD5Context
  270. md5Init c
  271. hashSym(c, s)
  272. var it = s
  273. while it != nil:
  274. c &= it.name.s
  275. c &= "."
  276. it = it.owner
  277. # for bug #5135 we also take the position into account, but only
  278. # for parameters, because who knows what else position dependency
  279. # might cause:
  280. if s.kind == skParam:
  281. c &= s.position
  282. md5Final c, result.MD5Digest
  283. proc hashOwner*(s: PSym): SigHash =
  284. var c: MD5Context
  285. md5Init c
  286. var m = s
  287. while m.kind != skModule: m = m.owner
  288. let p = m.owner
  289. assert p.kind == skPackage
  290. c &= p.name.s
  291. c &= "."
  292. c &= m.name.s
  293. md5Final c, result.MD5Digest
  294. proc sigHash*(s: PSym): SigHash =
  295. if s.kind in routineKinds and s.typ != nil:
  296. result = hashProc(s)
  297. else:
  298. result = hashNonProc(s)
  299. proc symBodyDigest*(graph: ModuleGraph, sym: PSym): SigHash
  300. proc hashBodyTree(graph: ModuleGraph, c: var MD5Context, n: PNode)
  301. proc hashVarSymBody(graph: ModuleGraph, c: var MD5Context, s: PSym) =
  302. assert: s.kind in {skParam, skResult, skVar, skLet, skConst, skForVar}
  303. if sfGlobal notin s.flags:
  304. c &= char(s.kind)
  305. c &= s.name.s
  306. else:
  307. c &= hashNonProc(s)
  308. # this one works for let and const but not for var. True variables can change value
  309. # later on. it is user resposibility to hash his global state if required
  310. if s.ast != nil and s.ast.kind in {nkIdentDefs, nkConstDef}:
  311. hashBodyTree(graph, c, s.ast[^1])
  312. else:
  313. hashBodyTree(graph, c, s.ast)
  314. proc hashBodyTree(graph: ModuleGraph, c: var MD5Context, n: PNode) =
  315. # hash Nim tree recursing into simply
  316. if n == nil:
  317. c &= "nil"
  318. return
  319. c &= char(n.kind)
  320. case n.kind
  321. of nkEmpty, nkNilLit, nkType: discard
  322. of nkIdent:
  323. c &= n.ident.s
  324. of nkSym:
  325. if n.sym.kind in skProcKinds:
  326. c &= symBodyDigest(graph, n.sym)
  327. elif n.sym.kind in {skParam, skResult, skVar, skLet, skConst, skForVar}:
  328. hashVarSymBody(graph, c, n.sym)
  329. else:
  330. c &= hashNonProc(n.sym)
  331. of nkProcDef, nkFuncDef, nkTemplateDef, nkMacroDef:
  332. discard # we track usage of proc symbols not their definition
  333. of nkCharLit..nkUInt64Lit:
  334. c &= n.intVal
  335. of nkFloatLit..nkFloat64Lit:
  336. c &= n.floatVal
  337. of nkStrLit..nkTripleStrLit:
  338. c &= n.strVal
  339. else:
  340. for i in 0..<n.len:
  341. hashBodyTree(graph, c, n[i])
  342. proc symBodyDigest*(graph: ModuleGraph, sym: PSym): SigHash =
  343. ## compute unique digest of the proc/func/method symbols
  344. ## recursing into invoked symbols as well
  345. assert(sym.kind in skProcKinds, $sym.kind)
  346. graph.symBodyHashes.withValue(sym.id, value):
  347. return value[]
  348. var c: MD5Context
  349. md5Init(c)
  350. c.hashType(sym.typ, {CoProc})
  351. c &= char(sym.kind)
  352. c.md5Final(result.MD5Digest)
  353. graph.symBodyHashes[sym.id] = result # protect from recursion in the body
  354. if sym.ast != nil:
  355. md5Init(c)
  356. c.md5Update(cast[cstring](result.addr), sizeof(result))
  357. hashBodyTree(graph, c, getBody(graph, sym))
  358. c.md5Final(result.MD5Digest)
  359. graph.symBodyHashes[sym.id] = result
  360. proc idOrSig*(s: PSym, currentModule: string,
  361. sigCollisions: var CountTable[SigHash]): Rope =
  362. if s.kind in routineKinds and s.typ != nil:
  363. # signatures for exported routines are reliable enough to
  364. # produce a unique name and this means produced C++ is more stable regarding
  365. # Nim changes:
  366. let sig = hashProc(s)
  367. result = rope($sig)
  368. #let m = if s.typ.callConv != ccInline: findPendingModule(m, s) else: m
  369. let counter = sigCollisions.getOrDefault(sig)
  370. #if sigs == "_jckmNePK3i2MFnWwZlp6Lg" and s.name.s == "contains":
  371. # echo "counter ", counter, " ", s.id
  372. if counter != 0:
  373. result.add "_" & rope(counter+1)
  374. # this minor hack is necessary to make tests/collections/thashes compile.
  375. # The inlined hash function's original module is ambiguous so we end up
  376. # generating duplicate names otherwise:
  377. if s.typ.callConv == ccInline:
  378. result.add rope(currentModule)
  379. sigCollisions.inc(sig)
  380. else:
  381. let sig = hashNonProc(s)
  382. result = rope($sig)
  383. let counter = sigCollisions.getOrDefault(sig)
  384. if counter != 0:
  385. result.add "_" & rope(counter+1)
  386. sigCollisions.inc(sig)