sighashes.nim 14 KB

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