sighashes.nim 13 KB

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