# Author Robert Michel - Posted on March 22, 2019
# source: https://github.com/GDATAAdvancedAnalytics/IDA-Python/blob/master/Trickbot/stringDecryption.py#L104
# article: https://cyber.wtf/2019/03/22/using-ida-python-to-analyze-trickbot/
def setCommentToDecompilation(address, comment):
#Works in IDA 6.9 (worked fine in IDA 7.5 - dz)
#see https://www.hex-rays.com/products/decompiler/manual/sdk/hexrays_8hpp_source.shtml used structures, const and functions
cfunc = idaapi.decompile(address)
#get the line of the decompilation for this address
eamap = cfunc.get_eamap()
decompObjAddr = eamap[address][0].ea
#get a ctree location object to place a comment there
tl = idaapi.treeloc_t()
tl.ea = decompObjAddr
commentSet = False
#since the public documentation on IDAs APIs is crap and I don't know any other way, we have to brute force the item preciser
#we do this by setting the comments with different idaapi.ITP_* types until our comment does not create an orphaned comment
for itp in range(idaapi.ITP_SEMI, idaapi.ITP_COLON):
tl.itp = itp
cfunc.set_user_cmt(tl, comment)
cfunc.save_user_cmts()
#apparently you have to cast cfunc to a string, to make it update itself
unused = cfunc.__str__()
if not cfunc.has_orphan_cmts():
commentSet = True
cfunc.save_user_cmts()
break
cfunc.del_orphan_cmts()
if not commentSet:
print("[ERROR] Please set "%s" to line %s manually" % (comment, hex(int(address))))