AddressSanitizer.cpp 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037
  1. //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file is a part of AddressSanitizer, an address sanity checker.
  11. // Details of the algorithm:
  12. // http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Instrumentation.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/DenseSet.h"
  19. #include "llvm/ADT/DepthFirstIterator.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/ADT/Statistic.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/ADT/Triple.h"
  26. #include "llvm/Analysis/MemoryBuiltins.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/IR/CallSite.h"
  30. #include "llvm/IR/DIBuilder.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/Dominators.h"
  33. #include "llvm/IR/Function.h"
  34. #include "llvm/IR/IRBuilder.h"
  35. #include "llvm/IR/InlineAsm.h"
  36. #include "llvm/IR/InstVisitor.h"
  37. #include "llvm/IR/IntrinsicInst.h"
  38. #include "llvm/IR/LLVMContext.h"
  39. #include "llvm/IR/MDBuilder.h"
  40. #include "llvm/IR/Module.h"
  41. #include "llvm/IR/Type.h"
  42. #include "llvm/MC/MCSectionMachO.h"
  43. #include "llvm/Support/CommandLine.h"
  44. #include "llvm/Support/DataTypes.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/Endian.h"
  47. #include "llvm/Support/SwapByteOrder.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include "llvm/Transforms/Scalar.h"
  50. #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
  51. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  52. #include "llvm/Transforms/Utils/Cloning.h"
  53. #include "llvm/Transforms/Utils/Local.h"
  54. #include "llvm/Transforms/Utils/ModuleUtils.h"
  55. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  56. #include <algorithm>
  57. #include <string>
  58. #include <system_error>
  59. using namespace llvm;
  60. #define DEBUG_TYPE "asan"
  61. static const uint64_t kDefaultShadowScale = 3;
  62. static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
  63. static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
  64. static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
  65. static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
  66. static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
  67. static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
  68. static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
  69. static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
  70. static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
  71. static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
  72. static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
  73. static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
  74. static const size_t kMinStackMallocSize = 1 << 6; // 64B
  75. static const size_t kMaxStackMallocSize = 1 << 16; // 64K
  76. static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
  77. static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
  78. static const char *const kAsanModuleCtorName = "asan.module_ctor";
  79. static const char *const kAsanModuleDtorName = "asan.module_dtor";
  80. static const uint64_t kAsanCtorAndDtorPriority = 1;
  81. static const char *const kAsanReportErrorTemplate = "__asan_report_";
  82. static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
  83. static const char *const kAsanUnregisterGlobalsName =
  84. "__asan_unregister_globals";
  85. static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
  86. static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
  87. static const char *const kAsanInitName = "__asan_init_v5";
  88. static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
  89. static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
  90. static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
  91. static const int kMaxAsanStackMallocSizeClass = 10;
  92. static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
  93. static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
  94. static const char *const kAsanGenPrefix = "__asan_gen_";
  95. static const char *const kSanCovGenPrefix = "__sancov_gen_";
  96. static const char *const kAsanPoisonStackMemoryName =
  97. "__asan_poison_stack_memory";
  98. static const char *const kAsanUnpoisonStackMemoryName =
  99. "__asan_unpoison_stack_memory";
  100. static const char *const kAsanOptionDetectUAR =
  101. "__asan_option_detect_stack_use_after_return";
  102. static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
  103. static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
  104. // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
  105. static const size_t kNumberOfAccessSizes = 5;
  106. static const unsigned kAllocaRzSize = 32;
  107. // Command-line flags.
  108. static cl::opt<bool> ClEnableKasan(
  109. "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
  110. cl::Hidden, cl::init(false));
  111. // This flag may need to be replaced with -f[no-]asan-reads.
  112. static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
  113. cl::desc("instrument read instructions"),
  114. cl::Hidden, cl::init(true));
  115. static cl::opt<bool> ClInstrumentWrites(
  116. "asan-instrument-writes", cl::desc("instrument write instructions"),
  117. cl::Hidden, cl::init(true));
  118. static cl::opt<bool> ClInstrumentAtomics(
  119. "asan-instrument-atomics",
  120. cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
  121. cl::init(true));
  122. static cl::opt<bool> ClAlwaysSlowPath(
  123. "asan-always-slow-path",
  124. cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
  125. cl::init(false));
  126. // This flag limits the number of instructions to be instrumented
  127. // in any given BB. Normally, this should be set to unlimited (INT_MAX),
  128. // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
  129. // set it to 10000.
  130. static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
  131. "asan-max-ins-per-bb", cl::init(10000),
  132. cl::desc("maximal number of instructions to instrument in any given BB"),
  133. cl::Hidden);
  134. // This flag may need to be replaced with -f[no]asan-stack.
  135. static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
  136. cl::Hidden, cl::init(true));
  137. static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
  138. cl::desc("Check return-after-free"),
  139. cl::Hidden, cl::init(true));
  140. // This flag may need to be replaced with -f[no]asan-globals.
  141. static cl::opt<bool> ClGlobals("asan-globals",
  142. cl::desc("Handle global objects"), cl::Hidden,
  143. cl::init(true));
  144. static cl::opt<bool> ClInitializers("asan-initialization-order",
  145. cl::desc("Handle C++ initializer order"),
  146. cl::Hidden, cl::init(true));
  147. static cl::opt<bool> ClInvalidPointerPairs(
  148. "asan-detect-invalid-pointer-pair",
  149. cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
  150. cl::init(false));
  151. static cl::opt<unsigned> ClRealignStack(
  152. "asan-realign-stack",
  153. cl::desc("Realign stack to the value of this flag (power of two)"),
  154. cl::Hidden, cl::init(32));
  155. static cl::opt<int> ClInstrumentationWithCallsThreshold(
  156. "asan-instrumentation-with-call-threshold",
  157. cl::desc(
  158. "If the function being instrumented contains more than "
  159. "this number of memory accesses, use callbacks instead of "
  160. "inline checks (-1 means never use callbacks)."),
  161. cl::Hidden, cl::init(7000));
  162. static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
  163. "asan-memory-access-callback-prefix",
  164. cl::desc("Prefix for memory access callbacks"), cl::Hidden,
  165. cl::init("__asan_"));
  166. static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
  167. cl::desc("instrument dynamic allocas"),
  168. cl::Hidden, cl::init(false));
  169. static cl::opt<bool> ClSkipPromotableAllocas(
  170. "asan-skip-promotable-allocas",
  171. cl::desc("Do not instrument promotable allocas"), cl::Hidden,
  172. cl::init(true));
  173. // These flags allow to change the shadow mapping.
  174. // The shadow mapping looks like
  175. // Shadow = (Mem >> scale) + (1 << offset_log)
  176. static cl::opt<int> ClMappingScale("asan-mapping-scale",
  177. cl::desc("scale of asan shadow mapping"),
  178. cl::Hidden, cl::init(0));
  179. // Optimization flags. Not user visible, used mostly for testing
  180. // and benchmarking the tool.
  181. static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
  182. cl::Hidden, cl::init(true));
  183. static cl::opt<bool> ClOptSameTemp(
  184. "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
  185. cl::Hidden, cl::init(true));
  186. static cl::opt<bool> ClOptGlobals("asan-opt-globals",
  187. cl::desc("Don't instrument scalar globals"),
  188. cl::Hidden, cl::init(true));
  189. static cl::opt<bool> ClOptStack(
  190. "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
  191. cl::Hidden, cl::init(false));
  192. static cl::opt<bool> ClCheckLifetime(
  193. "asan-check-lifetime",
  194. cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
  195. cl::init(false));
  196. static cl::opt<bool> ClDynamicAllocaStack(
  197. "asan-stack-dynamic-alloca",
  198. cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
  199. cl::init(true));
  200. static cl::opt<uint32_t> ClForceExperiment(
  201. "asan-force-experiment",
  202. cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
  203. cl::init(0));
  204. // Debug flags.
  205. static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
  206. cl::init(0));
  207. static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
  208. cl::Hidden, cl::init(0));
  209. static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
  210. cl::desc("Debug func"));
  211. static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
  212. cl::Hidden, cl::init(-1));
  213. static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
  214. cl::Hidden, cl::init(-1));
  215. STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
  216. STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
  217. STATISTIC(NumOptimizedAccessesToGlobalVar,
  218. "Number of optimized accesses to global vars");
  219. STATISTIC(NumOptimizedAccessesToStackVar,
  220. "Number of optimized accesses to stack vars");
  221. namespace {
  222. /// Frontend-provided metadata for source location.
  223. struct LocationMetadata {
  224. StringRef Filename;
  225. int LineNo;
  226. int ColumnNo;
  227. LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
  228. bool empty() const { return Filename.empty(); }
  229. void parse(MDNode *MDN) {
  230. assert(MDN->getNumOperands() == 3);
  231. MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
  232. Filename = DIFilename->getString();
  233. LineNo =
  234. mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
  235. ColumnNo =
  236. mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
  237. }
  238. };
  239. /// Frontend-provided metadata for global variables.
  240. class GlobalsMetadata {
  241. public:
  242. struct Entry {
  243. Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
  244. LocationMetadata SourceLoc;
  245. StringRef Name;
  246. bool IsDynInit;
  247. bool IsBlacklisted;
  248. };
  249. GlobalsMetadata() : inited_(false) {}
  250. void init(Module &M) {
  251. assert(!inited_);
  252. inited_ = true;
  253. NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
  254. if (!Globals) return;
  255. for (auto MDN : Globals->operands()) {
  256. // Metadata node contains the global and the fields of "Entry".
  257. assert(MDN->getNumOperands() == 5);
  258. auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
  259. // The optimizer may optimize away a global entirely.
  260. if (!GV) continue;
  261. // We can already have an entry for GV if it was merged with another
  262. // global.
  263. Entry &E = Entries[GV];
  264. if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
  265. E.SourceLoc.parse(Loc);
  266. if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
  267. E.Name = Name->getString();
  268. ConstantInt *IsDynInit =
  269. mdconst::extract<ConstantInt>(MDN->getOperand(3));
  270. E.IsDynInit |= IsDynInit->isOne();
  271. ConstantInt *IsBlacklisted =
  272. mdconst::extract<ConstantInt>(MDN->getOperand(4));
  273. E.IsBlacklisted |= IsBlacklisted->isOne();
  274. }
  275. }
  276. /// Returns metadata entry for a given global.
  277. Entry get(GlobalVariable *G) const {
  278. auto Pos = Entries.find(G);
  279. return (Pos != Entries.end()) ? Pos->second : Entry();
  280. }
  281. private:
  282. bool inited_;
  283. DenseMap<GlobalVariable *, Entry> Entries;
  284. };
  285. /// This struct defines the shadow mapping using the rule:
  286. /// shadow = (mem >> Scale) ADD-or-OR Offset.
  287. struct ShadowMapping {
  288. int Scale;
  289. uint64_t Offset;
  290. bool OrShadowOffset;
  291. };
  292. static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
  293. bool IsKasan) {
  294. bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
  295. bool IsIOS = TargetTriple.isiOS();
  296. bool IsFreeBSD = TargetTriple.isOSFreeBSD();
  297. bool IsLinux = TargetTriple.isOSLinux();
  298. bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
  299. TargetTriple.getArch() == llvm::Triple::ppc64le;
  300. bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
  301. bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
  302. TargetTriple.getArch() == llvm::Triple::mipsel;
  303. bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
  304. TargetTriple.getArch() == llvm::Triple::mips64el;
  305. bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
  306. bool IsWindows = TargetTriple.isOSWindows();
  307. ShadowMapping Mapping;
  308. if (LongSize == 32) {
  309. if (IsAndroid)
  310. Mapping.Offset = 0;
  311. else if (IsMIPS32)
  312. Mapping.Offset = kMIPS32_ShadowOffset32;
  313. else if (IsFreeBSD)
  314. Mapping.Offset = kFreeBSD_ShadowOffset32;
  315. else if (IsIOS)
  316. Mapping.Offset = kIOSShadowOffset32;
  317. else if (IsWindows)
  318. Mapping.Offset = kWindowsShadowOffset32;
  319. else
  320. Mapping.Offset = kDefaultShadowOffset32;
  321. } else { // LongSize == 64
  322. if (IsPPC64)
  323. Mapping.Offset = kPPC64_ShadowOffset64;
  324. else if (IsFreeBSD)
  325. Mapping.Offset = kFreeBSD_ShadowOffset64;
  326. else if (IsLinux && IsX86_64) {
  327. if (IsKasan)
  328. Mapping.Offset = kLinuxKasan_ShadowOffset64;
  329. else
  330. Mapping.Offset = kSmallX86_64ShadowOffset;
  331. } else if (IsMIPS64)
  332. Mapping.Offset = kMIPS64_ShadowOffset64;
  333. else if (IsAArch64)
  334. Mapping.Offset = kAArch64_ShadowOffset64;
  335. else
  336. Mapping.Offset = kDefaultShadowOffset64;
  337. }
  338. Mapping.Scale = kDefaultShadowScale;
  339. if (ClMappingScale) {
  340. Mapping.Scale = ClMappingScale;
  341. }
  342. // OR-ing shadow offset if more efficient (at least on x86) if the offset
  343. // is a power of two, but on ppc64 we have to use add since the shadow
  344. // offset is not necessary 1/8-th of the address space.
  345. Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
  346. return Mapping;
  347. }
  348. static size_t RedzoneSizeForScale(int MappingScale) {
  349. // Redzone used for stack and globals is at least 32 bytes.
  350. // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
  351. return std::max(32U, 1U << MappingScale);
  352. }
  353. /// AddressSanitizer: instrument the code in module to find memory bugs.
  354. struct AddressSanitizer : public FunctionPass {
  355. explicit AddressSanitizer(bool CompileKernel = false)
  356. : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
  357. initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
  358. }
  359. const char *getPassName() const override {
  360. return "AddressSanitizerFunctionPass";
  361. }
  362. void getAnalysisUsage(AnalysisUsage &AU) const override {
  363. AU.addRequired<DominatorTreeWrapperPass>();
  364. AU.addRequired<TargetLibraryInfoWrapperPass>();
  365. }
  366. uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
  367. Type *Ty = AI->getAllocatedType();
  368. uint64_t SizeInBytes =
  369. AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
  370. return SizeInBytes;
  371. }
  372. /// Check if we want (and can) handle this alloca.
  373. bool isInterestingAlloca(AllocaInst &AI);
  374. // Check if we have dynamic alloca.
  375. bool isDynamicAlloca(AllocaInst &AI) const {
  376. return AI.isArrayAllocation() || !AI.isStaticAlloca();
  377. }
  378. /// If it is an interesting memory access, return the PointerOperand
  379. /// and set IsWrite/Alignment. Otherwise return nullptr.
  380. Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
  381. uint64_t *TypeSize, unsigned *Alignment);
  382. void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
  383. bool UseCalls, const DataLayout &DL);
  384. void instrumentPointerComparisonOrSubtraction(Instruction *I);
  385. void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
  386. Value *Addr, uint32_t TypeSize, bool IsWrite,
  387. Value *SizeArgument, bool UseCalls, uint32_t Exp);
  388. void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
  389. uint32_t TypeSize, bool IsWrite,
  390. Value *SizeArgument, bool UseCalls,
  391. uint32_t Exp);
  392. Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
  393. Value *ShadowValue, uint32_t TypeSize);
  394. Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
  395. bool IsWrite, size_t AccessSizeIndex,
  396. Value *SizeArgument, uint32_t Exp);
  397. void instrumentMemIntrinsic(MemIntrinsic *MI);
  398. Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
  399. bool runOnFunction(Function &F) override;
  400. bool maybeInsertAsanInitAtFunctionEntry(Function &F);
  401. bool doInitialization(Module &M) override;
  402. static char ID; // Pass identification, replacement for typeid
  403. DominatorTree &getDominatorTree() const { return *DT; }
  404. private:
  405. void initializeCallbacks(Module &M);
  406. bool LooksLikeCodeInBug11395(Instruction *I);
  407. bool GlobalIsLinkerInitialized(GlobalVariable *G);
  408. bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
  409. uint64_t TypeSize) const;
  410. LLVMContext *C;
  411. Triple TargetTriple;
  412. int LongSize;
  413. bool CompileKernel;
  414. Type *IntptrTy;
  415. ShadowMapping Mapping;
  416. DominatorTree *DT;
  417. Function *AsanCtorFunction = nullptr;
  418. Function *AsanInitFunction = nullptr;
  419. Function *AsanHandleNoReturnFunc;
  420. Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
  421. // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
  422. Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
  423. Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
  424. // This array is indexed by AccessIsWrite and Experiment.
  425. Function *AsanErrorCallbackSized[2][2];
  426. Function *AsanMemoryAccessCallbackSized[2][2];
  427. Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
  428. InlineAsm *EmptyAsm;
  429. GlobalsMetadata GlobalsMD;
  430. DenseMap<AllocaInst *, bool> ProcessedAllocas;
  431. friend struct FunctionStackPoisoner;
  432. };
  433. class AddressSanitizerModule : public ModulePass {
  434. public:
  435. explicit AddressSanitizerModule(bool CompileKernel = false)
  436. : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
  437. bool runOnModule(Module &M) override;
  438. static char ID; // Pass identification, replacement for typeid
  439. const char *getPassName() const override { return "AddressSanitizerModule"; }
  440. private:
  441. void initializeCallbacks(Module &M);
  442. bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
  443. bool ShouldInstrumentGlobal(GlobalVariable *G);
  444. void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
  445. void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
  446. size_t MinRedzoneSizeForGlobal() const {
  447. return RedzoneSizeForScale(Mapping.Scale);
  448. }
  449. GlobalsMetadata GlobalsMD;
  450. bool CompileKernel;
  451. Type *IntptrTy;
  452. LLVMContext *C;
  453. Triple TargetTriple;
  454. ShadowMapping Mapping;
  455. Function *AsanPoisonGlobals;
  456. Function *AsanUnpoisonGlobals;
  457. Function *AsanRegisterGlobals;
  458. Function *AsanUnregisterGlobals;
  459. };
  460. // Stack poisoning does not play well with exception handling.
  461. // When an exception is thrown, we essentially bypass the code
  462. // that unpoisones the stack. This is why the run-time library has
  463. // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
  464. // stack in the interceptor. This however does not work inside the
  465. // actual function which catches the exception. Most likely because the
  466. // compiler hoists the load of the shadow value somewhere too high.
  467. // This causes asan to report a non-existing bug on 453.povray.
  468. // It sounds like an LLVM bug.
  469. struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
  470. Function &F;
  471. AddressSanitizer &ASan;
  472. DIBuilder DIB;
  473. LLVMContext *C;
  474. Type *IntptrTy;
  475. Type *IntptrPtrTy;
  476. ShadowMapping Mapping;
  477. SmallVector<AllocaInst *, 16> AllocaVec;
  478. SmallVector<Instruction *, 8> RetVec;
  479. unsigned StackAlignment;
  480. Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
  481. *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
  482. Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
  483. Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
  484. // Stores a place and arguments of poisoning/unpoisoning call for alloca.
  485. struct AllocaPoisonCall {
  486. IntrinsicInst *InsBefore;
  487. AllocaInst *AI;
  488. uint64_t Size;
  489. bool DoPoison;
  490. };
  491. SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
  492. SmallVector<AllocaInst *, 1> DynamicAllocaVec;
  493. SmallVector<IntrinsicInst *, 1> StackRestoreVec;
  494. AllocaInst *DynamicAllocaLayout = nullptr;
  495. // Maps Value to an AllocaInst from which the Value is originated.
  496. typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
  497. AllocaForValueMapTy AllocaForValue;
  498. bool HasNonEmptyInlineAsm;
  499. std::unique_ptr<CallInst> EmptyInlineAsm;
  500. FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
  501. : F(F),
  502. ASan(ASan),
  503. DIB(*F.getParent(), /*AllowUnresolved*/ false),
  504. C(ASan.C),
  505. IntptrTy(ASan.IntptrTy),
  506. IntptrPtrTy(PointerType::get(IntptrTy, 0)),
  507. Mapping(ASan.Mapping),
  508. StackAlignment(1 << Mapping.Scale),
  509. HasNonEmptyInlineAsm(false),
  510. EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
  511. bool runOnFunction() {
  512. if (!ClStack) return false;
  513. // Collect alloca, ret, lifetime instructions etc.
  514. for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
  515. if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
  516. initializeCallbacks(*F.getParent());
  517. poisonStack();
  518. if (ClDebugStack) {
  519. DEBUG(dbgs() << F);
  520. }
  521. return true;
  522. }
  523. // Finds all Alloca instructions and puts
  524. // poisoned red zones around all of them.
  525. // Then unpoison everything back before the function returns.
  526. void poisonStack();
  527. void createDynamicAllocasInitStorage();
  528. // ----------------------- Visitors.
  529. /// \brief Collect all Ret instructions.
  530. void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
  531. void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
  532. Value *SavedStack) {
  533. IRBuilder<> IRB(InstBefore);
  534. IRB.CreateCall(AsanAllocasUnpoisonFunc,
  535. {IRB.CreateLoad(DynamicAllocaLayout),
  536. IRB.CreatePtrToInt(SavedStack, IntptrTy)});
  537. }
  538. // Unpoison dynamic allocas redzones.
  539. void unpoisonDynamicAllocas() {
  540. for (auto &Ret : RetVec)
  541. unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
  542. for (auto &StackRestoreInst : StackRestoreVec)
  543. unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
  544. StackRestoreInst->getOperand(0));
  545. }
  546. // Deploy and poison redzones around dynamic alloca call. To do this, we
  547. // should replace this call with another one with changed parameters and
  548. // replace all its uses with new address, so
  549. // addr = alloca type, old_size, align
  550. // is replaced by
  551. // new_size = (old_size + additional_size) * sizeof(type)
  552. // tmp = alloca i8, new_size, max(align, 32)
  553. // addr = tmp + 32 (first 32 bytes are for the left redzone).
  554. // Additional_size is added to make new memory allocation contain not only
  555. // requested memory, but also left, partial and right redzones.
  556. void handleDynamicAllocaCall(AllocaInst *AI);
  557. /// \brief Collect Alloca instructions we want (and can) handle.
  558. void visitAllocaInst(AllocaInst &AI) {
  559. if (!ASan.isInterestingAlloca(AI)) return;
  560. StackAlignment = std::max(StackAlignment, AI.getAlignment());
  561. if (ASan.isDynamicAlloca(AI))
  562. DynamicAllocaVec.push_back(&AI);
  563. else
  564. AllocaVec.push_back(&AI);
  565. }
  566. /// \brief Collect lifetime intrinsic calls to check for use-after-scope
  567. /// errors.
  568. void visitIntrinsicInst(IntrinsicInst &II) {
  569. Intrinsic::ID ID = II.getIntrinsicID();
  570. if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
  571. if (!ClCheckLifetime) return;
  572. if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
  573. return;
  574. // Found lifetime intrinsic, add ASan instrumentation if necessary.
  575. ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
  576. // If size argument is undefined, don't do anything.
  577. if (Size->isMinusOne()) return;
  578. // Check that size doesn't saturate uint64_t and can
  579. // be stored in IntptrTy.
  580. const uint64_t SizeValue = Size->getValue().getLimitedValue();
  581. if (SizeValue == ~0ULL ||
  582. !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
  583. return;
  584. // Find alloca instruction that corresponds to llvm.lifetime argument.
  585. AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
  586. if (!AI) return;
  587. bool DoPoison = (ID == Intrinsic::lifetime_end);
  588. AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
  589. AllocaPoisonCallVec.push_back(APC);
  590. }
  591. void visitCallInst(CallInst &CI) {
  592. HasNonEmptyInlineAsm |=
  593. CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
  594. }
  595. // ---------------------- Helpers.
  596. void initializeCallbacks(Module &M);
  597. bool doesDominateAllExits(const Instruction *I) const {
  598. for (auto Ret : RetVec) {
  599. if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
  600. }
  601. return true;
  602. }
  603. /// Finds alloca where the value comes from.
  604. AllocaInst *findAllocaForValue(Value *V);
  605. void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
  606. Value *ShadowBase, bool DoPoison);
  607. void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
  608. void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
  609. int Size);
  610. Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
  611. bool Dynamic);
  612. PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
  613. Instruction *ThenTerm, Value *ValueIfFalse);
  614. };
  615. } // namespace
  616. char AddressSanitizer::ID = 0;
  617. INITIALIZE_PASS_BEGIN(
  618. AddressSanitizer, "asan",
  619. "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
  620. false)
  621. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  622. INITIALIZE_PASS_END(
  623. AddressSanitizer, "asan",
  624. "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
  625. false)
  626. FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
  627. return new AddressSanitizer(CompileKernel);
  628. }
  629. char AddressSanitizerModule::ID = 0;
  630. INITIALIZE_PASS(
  631. AddressSanitizerModule, "asan-module",
  632. "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
  633. "ModulePass",
  634. false, false)
  635. ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
  636. return new AddressSanitizerModule(CompileKernel);
  637. }
  638. static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
  639. size_t Res = countTrailingZeros(TypeSize / 8);
  640. assert(Res < kNumberOfAccessSizes);
  641. return Res;
  642. }
  643. // \brief Create a constant for Str so that we can pass it to the run-time lib.
  644. static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
  645. bool AllowMerging) {
  646. Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
  647. // We use private linkage for module-local strings. If they can be merged
  648. // with another one, we set the unnamed_addr attribute.
  649. GlobalVariable *GV =
  650. new GlobalVariable(M, StrConst->getType(), true,
  651. GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
  652. if (AllowMerging) GV->setUnnamedAddr(true);
  653. GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
  654. return GV;
  655. }
  656. /// \brief Create a global describing a source location.
  657. static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
  658. LocationMetadata MD) {
  659. Constant *LocData[] = {
  660. createPrivateGlobalForString(M, MD.Filename, true),
  661. ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
  662. ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
  663. };
  664. auto LocStruct = ConstantStruct::getAnon(LocData);
  665. auto GV = new GlobalVariable(M, LocStruct->getType(), true,
  666. GlobalValue::PrivateLinkage, LocStruct,
  667. kAsanGenPrefix);
  668. GV->setUnnamedAddr(true);
  669. return GV;
  670. }
  671. static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
  672. return G->getName().find(kAsanGenPrefix) == 0 ||
  673. G->getName().find(kSanCovGenPrefix) == 0;
  674. }
  675. Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
  676. // Shadow >> scale
  677. Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
  678. if (Mapping.Offset == 0) return Shadow;
  679. // (Shadow >> scale) | offset
  680. if (Mapping.OrShadowOffset)
  681. return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
  682. else
  683. return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
  684. }
  685. // Instrument memset/memmove/memcpy
  686. void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
  687. IRBuilder<> IRB(MI);
  688. if (isa<MemTransferInst>(MI)) {
  689. IRB.CreateCall(
  690. isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
  691. {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
  692. IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
  693. IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
  694. } else if (isa<MemSetInst>(MI)) {
  695. IRB.CreateCall(
  696. AsanMemset,
  697. {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
  698. IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
  699. IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
  700. }
  701. MI->eraseFromParent();
  702. }
  703. /// Check if we want (and can) handle this alloca.
  704. bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
  705. auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
  706. if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
  707. return PreviouslySeenAllocaInfo->getSecond();
  708. bool IsInteresting =
  709. (AI.getAllocatedType()->isSized() &&
  710. // alloca() may be called with 0 size, ignore it.
  711. getAllocaSizeInBytes(&AI) > 0 &&
  712. // We are only interested in allocas not promotable to registers.
  713. // Promotable allocas are common under -O0.
  714. (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
  715. isDynamicAlloca(AI)));
  716. ProcessedAllocas[&AI] = IsInteresting;
  717. return IsInteresting;
  718. }
  719. /// If I is an interesting memory access, return the PointerOperand
  720. /// and set IsWrite/Alignment. Otherwise return nullptr.
  721. Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
  722. bool *IsWrite,
  723. uint64_t *TypeSize,
  724. unsigned *Alignment) {
  725. // Skip memory accesses inserted by another instrumentation.
  726. if (I->getMetadata("nosanitize")) return nullptr;
  727. Value *PtrOperand = nullptr;
  728. const DataLayout &DL = I->getModule()->getDataLayout();
  729. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  730. if (!ClInstrumentReads) return nullptr;
  731. *IsWrite = false;
  732. *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
  733. *Alignment = LI->getAlignment();
  734. PtrOperand = LI->getPointerOperand();
  735. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  736. if (!ClInstrumentWrites) return nullptr;
  737. *IsWrite = true;
  738. *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
  739. *Alignment = SI->getAlignment();
  740. PtrOperand = SI->getPointerOperand();
  741. } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  742. if (!ClInstrumentAtomics) return nullptr;
  743. *IsWrite = true;
  744. *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
  745. *Alignment = 0;
  746. PtrOperand = RMW->getPointerOperand();
  747. } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
  748. if (!ClInstrumentAtomics) return nullptr;
  749. *IsWrite = true;
  750. *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
  751. *Alignment = 0;
  752. PtrOperand = XCHG->getPointerOperand();
  753. }
  754. // Treat memory accesses to promotable allocas as non-interesting since they
  755. // will not cause memory violations. This greatly speeds up the instrumented
  756. // executable at -O0.
  757. if (ClSkipPromotableAllocas)
  758. if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
  759. return isInterestingAlloca(*AI) ? AI : nullptr;
  760. return PtrOperand;
  761. }
  762. static bool isPointerOperand(Value *V) {
  763. return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
  764. }
  765. // This is a rough heuristic; it may cause both false positives and
  766. // false negatives. The proper implementation requires cooperation with
  767. // the frontend.
  768. static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
  769. if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
  770. if (!Cmp->isRelational()) return false;
  771. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  772. if (BO->getOpcode() != Instruction::Sub) return false;
  773. } else {
  774. return false;
  775. }
  776. if (!isPointerOperand(I->getOperand(0)) ||
  777. !isPointerOperand(I->getOperand(1)))
  778. return false;
  779. return true;
  780. }
  781. bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
  782. // If a global variable does not have dynamic initialization we don't
  783. // have to instrument it. However, if a global does not have initializer
  784. // at all, we assume it has dynamic initializer (in other TU).
  785. return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
  786. }
  787. void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
  788. Instruction *I) {
  789. IRBuilder<> IRB(I);
  790. Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
  791. Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
  792. for (int i = 0; i < 2; i++) {
  793. if (Param[i]->getType()->isPointerTy())
  794. Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
  795. }
  796. IRB.CreateCall(F, Param);
  797. }
  798. void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
  799. Instruction *I, bool UseCalls,
  800. const DataLayout &DL) {
  801. bool IsWrite = false;
  802. unsigned Alignment = 0;
  803. uint64_t TypeSize = 0;
  804. Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
  805. assert(Addr);
  806. // Optimization experiments.
  807. // The experiments can be used to evaluate potential optimizations that remove
  808. // instrumentation (assess false negatives). Instead of completely removing
  809. // some instrumentation, you set Exp to a non-zero value (mask of optimization
  810. // experiments that want to remove instrumentation of this instruction).
  811. // If Exp is non-zero, this pass will emit special calls into runtime
  812. // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
  813. // make runtime terminate the program in a special way (with a different
  814. // exit status). Then you run the new compiler on a buggy corpus, collect
  815. // the special terminations (ideally, you don't see them at all -- no false
  816. // negatives) and make the decision on the optimization.
  817. uint32_t Exp = ClForceExperiment;
  818. if (ClOpt && ClOptGlobals) {
  819. // If initialization order checking is disabled, a simple access to a
  820. // dynamically initialized global is always valid.
  821. GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
  822. if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
  823. isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
  824. NumOptimizedAccessesToGlobalVar++;
  825. return;
  826. }
  827. }
  828. if (ClOpt && ClOptStack) {
  829. // A direct inbounds access to a stack variable is always valid.
  830. if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
  831. isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
  832. NumOptimizedAccessesToStackVar++;
  833. return;
  834. }
  835. }
  836. if (IsWrite)
  837. NumInstrumentedWrites++;
  838. else
  839. NumInstrumentedReads++;
  840. unsigned Granularity = 1 << Mapping.Scale;
  841. // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
  842. // if the data is properly aligned.
  843. if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
  844. TypeSize == 128) &&
  845. (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
  846. return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
  847. Exp);
  848. instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
  849. UseCalls, Exp);
  850. }
  851. Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
  852. Value *Addr, bool IsWrite,
  853. size_t AccessSizeIndex,
  854. Value *SizeArgument,
  855. uint32_t Exp) {
  856. IRBuilder<> IRB(InsertBefore);
  857. Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
  858. CallInst *Call = nullptr;
  859. if (SizeArgument) {
  860. if (Exp == 0)
  861. Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
  862. {Addr, SizeArgument});
  863. else
  864. Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
  865. {Addr, SizeArgument, ExpVal});
  866. } else {
  867. if (Exp == 0)
  868. Call =
  869. IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
  870. else
  871. Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
  872. {Addr, ExpVal});
  873. }
  874. // We don't do Call->setDoesNotReturn() because the BB already has
  875. // UnreachableInst at the end.
  876. // This EmptyAsm is required to avoid callback merge.
  877. IRB.CreateCall(EmptyAsm, {});
  878. return Call;
  879. }
  880. Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
  881. Value *ShadowValue,
  882. uint32_t TypeSize) {
  883. size_t Granularity = 1 << Mapping.Scale;
  884. // Addr & (Granularity - 1)
  885. Value *LastAccessedByte =
  886. IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
  887. // (Addr & (Granularity - 1)) + size - 1
  888. if (TypeSize / 8 > 1)
  889. LastAccessedByte = IRB.CreateAdd(
  890. LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
  891. // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
  892. LastAccessedByte =
  893. IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
  894. // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
  895. return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
  896. }
  897. void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
  898. Instruction *InsertBefore, Value *Addr,
  899. uint32_t TypeSize, bool IsWrite,
  900. Value *SizeArgument, bool UseCalls,
  901. uint32_t Exp) {
  902. IRBuilder<> IRB(InsertBefore);
  903. Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
  904. size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
  905. if (UseCalls) {
  906. if (Exp == 0)
  907. IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
  908. AddrLong);
  909. else
  910. IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
  911. {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
  912. return;
  913. }
  914. Type *ShadowTy =
  915. IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
  916. Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
  917. Value *ShadowPtr = memToShadow(AddrLong, IRB);
  918. Value *CmpVal = Constant::getNullValue(ShadowTy);
  919. Value *ShadowValue =
  920. IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
  921. Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
  922. size_t Granularity = 1 << Mapping.Scale;
  923. TerminatorInst *CrashTerm = nullptr;
  924. if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
  925. // We use branch weights for the slow path check, to indicate that the slow
  926. // path is rarely taken. This seems to be the case for SPEC benchmarks.
  927. TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
  928. Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
  929. assert(cast<BranchInst>(CheckTerm)->isUnconditional());
  930. BasicBlock *NextBB = CheckTerm->getSuccessor(0);
  931. IRB.SetInsertPoint(CheckTerm);
  932. Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
  933. BasicBlock *CrashBlock =
  934. BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
  935. CrashTerm = new UnreachableInst(*C, CrashBlock);
  936. BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
  937. ReplaceInstWithInst(CheckTerm, NewTerm);
  938. } else {
  939. CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
  940. }
  941. Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
  942. AccessSizeIndex, SizeArgument, Exp);
  943. Crash->setDebugLoc(OrigIns->getDebugLoc());
  944. }
  945. // Instrument unusual size or unusual alignment.
  946. // We can not do it with a single check, so we do 1-byte check for the first
  947. // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
  948. // to report the actual access size.
  949. void AddressSanitizer::instrumentUnusualSizeOrAlignment(
  950. Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
  951. Value *SizeArgument, bool UseCalls, uint32_t Exp) {
  952. IRBuilder<> IRB(I);
  953. Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
  954. Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
  955. if (UseCalls) {
  956. if (Exp == 0)
  957. IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
  958. {AddrLong, Size});
  959. else
  960. IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
  961. {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
  962. } else {
  963. Value *LastByte = IRB.CreateIntToPtr(
  964. IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
  965. Addr->getType());
  966. instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
  967. instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
  968. }
  969. }
  970. void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
  971. GlobalValue *ModuleName) {
  972. // Set up the arguments to our poison/unpoison functions.
  973. IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
  974. // Add a call to poison all external globals before the given function starts.
  975. Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
  976. IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
  977. // Add calls to unpoison all globals before each return instruction.
  978. for (auto &BB : GlobalInit.getBasicBlockList())
  979. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
  980. CallInst::Create(AsanUnpoisonGlobals, "", RI);
  981. }
  982. void AddressSanitizerModule::createInitializerPoisonCalls(
  983. Module &M, GlobalValue *ModuleName) {
  984. GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
  985. ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
  986. for (Use &OP : CA->operands()) {
  987. if (isa<ConstantAggregateZero>(OP)) continue;
  988. ConstantStruct *CS = cast<ConstantStruct>(OP);
  989. // Must have a function or null ptr.
  990. if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
  991. if (F->getName() == kAsanModuleCtorName) continue;
  992. ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
  993. // Don't instrument CTORs that will run before asan.module_ctor.
  994. if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
  995. poisonOneInitializer(*F, ModuleName);
  996. }
  997. }
  998. }
  999. bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
  1000. Type *Ty = cast<PointerType>(G->getType())->getElementType();
  1001. DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
  1002. if (GlobalsMD.get(G).IsBlacklisted) return false;
  1003. if (!Ty->isSized()) return false;
  1004. if (!G->hasInitializer()) return false;
  1005. if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
  1006. // Touch only those globals that will not be defined in other modules.
  1007. // Don't handle ODR linkage types and COMDATs since other modules may be built
  1008. // without ASan.
  1009. if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
  1010. G->getLinkage() != GlobalVariable::PrivateLinkage &&
  1011. G->getLinkage() != GlobalVariable::InternalLinkage)
  1012. return false;
  1013. if (G->hasComdat()) return false;
  1014. // Two problems with thread-locals:
  1015. // - The address of the main thread's copy can't be computed at link-time.
  1016. // - Need to poison all copies, not just the main thread's one.
  1017. if (G->isThreadLocal()) return false;
  1018. // For now, just ignore this Global if the alignment is large.
  1019. if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
  1020. if (G->hasSection()) {
  1021. StringRef Section(G->getSection());
  1022. // Globals from llvm.metadata aren't emitted, do not instrument them.
  1023. if (Section == "llvm.metadata") return false;
  1024. // Do not instrument globals from special LLVM sections.
  1025. if (Section.find("__llvm") != StringRef::npos) return false;
  1026. // Callbacks put into the CRT initializer/terminator sections
  1027. // should not be instrumented.
  1028. // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
  1029. // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
  1030. if (Section.startswith(".CRT")) {
  1031. DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
  1032. return false;
  1033. }
  1034. if (TargetTriple.isOSBinFormatMachO()) {
  1035. StringRef ParsedSegment, ParsedSection;
  1036. unsigned TAA = 0, StubSize = 0;
  1037. bool TAAParsed;
  1038. std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
  1039. Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
  1040. if (!ErrorCode.empty()) {
  1041. assert(false && "Invalid section specifier.");
  1042. return false;
  1043. }
  1044. // Ignore the globals from the __OBJC section. The ObjC runtime assumes
  1045. // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
  1046. // them.
  1047. if (ParsedSegment == "__OBJC" ||
  1048. (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
  1049. DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
  1050. return false;
  1051. }
  1052. // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
  1053. // Constant CFString instances are compiled in the following way:
  1054. // -- the string buffer is emitted into
  1055. // __TEXT,__cstring,cstring_literals
  1056. // -- the constant NSConstantString structure referencing that buffer
  1057. // is placed into __DATA,__cfstring
  1058. // Therefore there's no point in placing redzones into __DATA,__cfstring.
  1059. // Moreover, it causes the linker to crash on OS X 10.7
  1060. if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
  1061. DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
  1062. return false;
  1063. }
  1064. // The linker merges the contents of cstring_literals and removes the
  1065. // trailing zeroes.
  1066. if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
  1067. DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
  1068. return false;
  1069. }
  1070. }
  1071. }
  1072. return true;
  1073. }
  1074. void AddressSanitizerModule::initializeCallbacks(Module &M) {
  1075. IRBuilder<> IRB(*C);
  1076. // Declare our poisoning and unpoisoning functions.
  1077. AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1078. kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
  1079. AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
  1080. AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1081. kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
  1082. AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
  1083. // Declare functions that register/unregister globals.
  1084. AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1085. kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
  1086. AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
  1087. AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
  1088. M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
  1089. IntptrTy, IntptrTy, nullptr));
  1090. AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
  1091. }
  1092. // This function replaces all global variables with new variables that have
  1093. // trailing redzones. It also creates a function that poisons
  1094. // redzones and inserts this function into llvm.global_ctors.
  1095. bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
  1096. GlobalsMD.init(M);
  1097. SmallVector<GlobalVariable *, 16> GlobalsToChange;
  1098. for (auto &G : M.globals()) {
  1099. if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
  1100. }
  1101. size_t n = GlobalsToChange.size();
  1102. if (n == 0) return false;
  1103. // A global is described by a structure
  1104. // size_t beg;
  1105. // size_t size;
  1106. // size_t size_with_redzone;
  1107. // const char *name;
  1108. // const char *module_name;
  1109. // size_t has_dynamic_init;
  1110. // void *source_location;
  1111. // We initialize an array of such structures and pass it to a run-time call.
  1112. StructType *GlobalStructTy =
  1113. StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
  1114. IntptrTy, IntptrTy, nullptr);
  1115. SmallVector<Constant *, 16> Initializers(n);
  1116. bool HasDynamicallyInitializedGlobals = false;
  1117. // We shouldn't merge same module names, as this string serves as unique
  1118. // module ID in runtime.
  1119. GlobalVariable *ModuleName = createPrivateGlobalForString(
  1120. M, M.getModuleIdentifier(), /*AllowMerging*/ false);
  1121. auto &DL = M.getDataLayout();
  1122. for (size_t i = 0; i < n; i++) {
  1123. static const uint64_t kMaxGlobalRedzone = 1 << 18;
  1124. GlobalVariable *G = GlobalsToChange[i];
  1125. auto MD = GlobalsMD.get(G);
  1126. // Create string holding the global name (use global name from metadata
  1127. // if it's available, otherwise just write the name of global variable).
  1128. GlobalVariable *Name = createPrivateGlobalForString(
  1129. M, MD.Name.empty() ? G->getName() : MD.Name,
  1130. /*AllowMerging*/ true);
  1131. PointerType *PtrTy = cast<PointerType>(G->getType());
  1132. Type *Ty = PtrTy->getElementType();
  1133. uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
  1134. uint64_t MinRZ = MinRedzoneSizeForGlobal();
  1135. // MinRZ <= RZ <= kMaxGlobalRedzone
  1136. // and trying to make RZ to be ~ 1/4 of SizeInBytes.
  1137. uint64_t RZ = std::max(
  1138. MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
  1139. uint64_t RightRedzoneSize = RZ;
  1140. // Round up to MinRZ
  1141. if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
  1142. assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
  1143. Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
  1144. StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
  1145. Constant *NewInitializer =
  1146. ConstantStruct::get(NewTy, G->getInitializer(),
  1147. Constant::getNullValue(RightRedZoneTy), nullptr);
  1148. // Create a new global variable with enough space for a redzone.
  1149. GlobalValue::LinkageTypes Linkage = G->getLinkage();
  1150. if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
  1151. Linkage = GlobalValue::InternalLinkage;
  1152. GlobalVariable *NewGlobal =
  1153. new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
  1154. "", G, G->getThreadLocalMode());
  1155. NewGlobal->copyAttributesFrom(G);
  1156. NewGlobal->setAlignment(MinRZ);
  1157. Value *Indices2[2];
  1158. Indices2[0] = IRB.getInt32(0);
  1159. Indices2[1] = IRB.getInt32(0);
  1160. G->replaceAllUsesWith(
  1161. ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
  1162. NewGlobal->takeName(G);
  1163. G->eraseFromParent();
  1164. Constant *SourceLoc;
  1165. if (!MD.SourceLoc.empty()) {
  1166. auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
  1167. SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
  1168. } else {
  1169. SourceLoc = ConstantInt::get(IntptrTy, 0);
  1170. }
  1171. Initializers[i] = ConstantStruct::get(
  1172. GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
  1173. ConstantInt::get(IntptrTy, SizeInBytes),
  1174. ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
  1175. ConstantExpr::getPointerCast(Name, IntptrTy),
  1176. ConstantExpr::getPointerCast(ModuleName, IntptrTy),
  1177. ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
  1178. if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
  1179. DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
  1180. }
  1181. ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
  1182. GlobalVariable *AllGlobals = new GlobalVariable(
  1183. M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
  1184. ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
  1185. // Create calls for poisoning before initializers run and unpoisoning after.
  1186. if (HasDynamicallyInitializedGlobals)
  1187. createInitializerPoisonCalls(M, ModuleName);
  1188. IRB.CreateCall(AsanRegisterGlobals,
  1189. {IRB.CreatePointerCast(AllGlobals, IntptrTy),
  1190. ConstantInt::get(IntptrTy, n)});
  1191. // We also need to unregister globals at the end, e.g. when a shared library
  1192. // gets closed.
  1193. Function *AsanDtorFunction =
  1194. Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
  1195. GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
  1196. BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
  1197. IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
  1198. IRB_Dtor.CreateCall(AsanUnregisterGlobals,
  1199. {IRB.CreatePointerCast(AllGlobals, IntptrTy),
  1200. ConstantInt::get(IntptrTy, n)});
  1201. appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
  1202. DEBUG(dbgs() << M);
  1203. return true;
  1204. }
  1205. bool AddressSanitizerModule::runOnModule(Module &M) {
  1206. C = &(M.getContext());
  1207. int LongSize = M.getDataLayout().getPointerSizeInBits();
  1208. IntptrTy = Type::getIntNTy(*C, LongSize);
  1209. TargetTriple = Triple(M.getTargetTriple());
  1210. Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
  1211. initializeCallbacks(M);
  1212. bool Changed = false;
  1213. // TODO(glider): temporarily disabled globals instrumentation for KASan.
  1214. if (ClGlobals && !CompileKernel) {
  1215. Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
  1216. assert(CtorFunc);
  1217. IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
  1218. Changed |= InstrumentGlobals(IRB, M);
  1219. }
  1220. return Changed;
  1221. }
  1222. void AddressSanitizer::initializeCallbacks(Module &M) {
  1223. IRBuilder<> IRB(*C);
  1224. // Create __asan_report* callbacks.
  1225. // IsWrite, TypeSize and Exp are encoded in the function name.
  1226. for (int Exp = 0; Exp < 2; Exp++) {
  1227. for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
  1228. const std::string TypeStr = AccessIsWrite ? "store" : "load";
  1229. const std::string ExpStr = Exp ? "exp_" : "";
  1230. const std::string SuffixStr = CompileKernel ? "N" : "_n";
  1231. const std::string EndingStr = CompileKernel ? "_noabort" : "";
  1232. const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
  1233. // TODO(glider): for KASan builds add _noabort to error reporting
  1234. // functions and make them actually noabort (remove the UnreachableInst).
  1235. AsanErrorCallbackSized[AccessIsWrite][Exp] =
  1236. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1237. kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
  1238. IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
  1239. AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
  1240. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1241. ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
  1242. IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
  1243. for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
  1244. AccessSizeIndex++) {
  1245. const std::string Suffix = TypeStr + itostr((int64_t)(1) << AccessSizeIndex); // HLSL Change - keep as 64-bit operation
  1246. AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
  1247. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1248. kAsanReportErrorTemplate + ExpStr + Suffix,
  1249. IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
  1250. AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
  1251. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1252. ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
  1253. IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
  1254. }
  1255. }
  1256. }
  1257. const std::string MemIntrinCallbackPrefix =
  1258. CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
  1259. AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1260. MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
  1261. IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
  1262. AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1263. MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
  1264. IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
  1265. AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1266. MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
  1267. IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
  1268. AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
  1269. M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
  1270. AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1271. kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
  1272. AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1273. kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
  1274. // We insert an empty inline asm after __asan_report* to avoid callback merge.
  1275. EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
  1276. StringRef(""), StringRef(""),
  1277. /*hasSideEffects=*/true);
  1278. }
  1279. // virtual
  1280. bool AddressSanitizer::doInitialization(Module &M) {
  1281. // Initialize the private fields. No one has accessed them before.
  1282. GlobalsMD.init(M);
  1283. C = &(M.getContext());
  1284. LongSize = M.getDataLayout().getPointerSizeInBits();
  1285. IntptrTy = Type::getIntNTy(*C, LongSize);
  1286. TargetTriple = Triple(M.getTargetTriple());
  1287. if (!CompileKernel) {
  1288. std::tie(AsanCtorFunction, AsanInitFunction) =
  1289. createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
  1290. /*InitArgTypes=*/{},
  1291. /*InitArgs=*/{});
  1292. appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
  1293. }
  1294. Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
  1295. return true;
  1296. }
  1297. bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
  1298. // For each NSObject descendant having a +load method, this method is invoked
  1299. // by the ObjC runtime before any of the static constructors is called.
  1300. // Therefore we need to instrument such methods with a call to __asan_init
  1301. // at the beginning in order to initialize our runtime before any access to
  1302. // the shadow memory.
  1303. // We cannot just ignore these methods, because they may call other
  1304. // instrumented functions.
  1305. if (F.getName().find(" load]") != std::string::npos) {
  1306. IRBuilder<> IRB(F.begin()->begin());
  1307. IRB.CreateCall(AsanInitFunction, {});
  1308. return true;
  1309. }
  1310. return false;
  1311. }
  1312. bool AddressSanitizer::runOnFunction(Function &F) {
  1313. if (&F == AsanCtorFunction) return false;
  1314. if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
  1315. DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
  1316. initializeCallbacks(*F.getParent());
  1317. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1318. // If needed, insert __asan_init before checking for SanitizeAddress attr.
  1319. maybeInsertAsanInitAtFunctionEntry(F);
  1320. if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
  1321. if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
  1322. // We want to instrument every address only once per basic block (unless there
  1323. // are calls between uses).
  1324. SmallSet<Value *, 16> TempsToInstrument;
  1325. SmallVector<Instruction *, 16> ToInstrument;
  1326. SmallVector<Instruction *, 8> NoReturnCalls;
  1327. SmallVector<BasicBlock *, 16> AllBlocks;
  1328. SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
  1329. int NumAllocas = 0;
  1330. bool IsWrite;
  1331. unsigned Alignment;
  1332. uint64_t TypeSize;
  1333. // Fill the set of memory operations to instrument.
  1334. for (auto &BB : F) {
  1335. AllBlocks.push_back(&BB);
  1336. TempsToInstrument.clear();
  1337. int NumInsnsPerBB = 0;
  1338. for (auto &Inst : BB) {
  1339. if (LooksLikeCodeInBug11395(&Inst)) return false;
  1340. if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
  1341. &Alignment)) {
  1342. if (ClOpt && ClOptSameTemp) {
  1343. if (!TempsToInstrument.insert(Addr).second)
  1344. continue; // We've seen this temp in the current BB.
  1345. }
  1346. } else if (ClInvalidPointerPairs &&
  1347. isInterestingPointerComparisonOrSubtraction(&Inst)) {
  1348. PointerComparisonsOrSubtracts.push_back(&Inst);
  1349. continue;
  1350. } else if (isa<MemIntrinsic>(Inst)) {
  1351. // ok, take it.
  1352. } else {
  1353. if (isa<AllocaInst>(Inst)) NumAllocas++;
  1354. CallSite CS(&Inst);
  1355. if (CS) {
  1356. // A call inside BB.
  1357. TempsToInstrument.clear();
  1358. if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
  1359. }
  1360. continue;
  1361. }
  1362. ToInstrument.push_back(&Inst);
  1363. NumInsnsPerBB++;
  1364. if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
  1365. }
  1366. }
  1367. bool UseCalls =
  1368. CompileKernel ||
  1369. (ClInstrumentationWithCallsThreshold >= 0 &&
  1370. ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
  1371. const TargetLibraryInfo *TLI =
  1372. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  1373. const DataLayout &DL = F.getParent()->getDataLayout();
  1374. ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
  1375. /*RoundToAlign=*/true);
  1376. // Instrument.
  1377. int NumInstrumented = 0;
  1378. for (auto Inst : ToInstrument) {
  1379. if (ClDebugMin < 0 || ClDebugMax < 0 ||
  1380. (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
  1381. if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
  1382. instrumentMop(ObjSizeVis, Inst, UseCalls,
  1383. F.getParent()->getDataLayout());
  1384. else
  1385. instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
  1386. }
  1387. NumInstrumented++;
  1388. }
  1389. FunctionStackPoisoner FSP(F, *this);
  1390. bool ChangedStack = FSP.runOnFunction();
  1391. // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
  1392. // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
  1393. for (auto CI : NoReturnCalls) {
  1394. IRBuilder<> IRB(CI);
  1395. IRB.CreateCall(AsanHandleNoReturnFunc, {});
  1396. }
  1397. for (auto Inst : PointerComparisonsOrSubtracts) {
  1398. instrumentPointerComparisonOrSubtraction(Inst);
  1399. NumInstrumented++;
  1400. }
  1401. bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
  1402. DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
  1403. return res;
  1404. }
  1405. // Workaround for bug 11395: we don't want to instrument stack in functions
  1406. // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
  1407. // FIXME: remove once the bug 11395 is fixed.
  1408. bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
  1409. if (LongSize != 32) return false;
  1410. CallInst *CI = dyn_cast<CallInst>(I);
  1411. if (!CI || !CI->isInlineAsm()) return false;
  1412. if (CI->getNumArgOperands() <= 5) return false;
  1413. // We have inline assembly with quite a few arguments.
  1414. return true;
  1415. }
  1416. void FunctionStackPoisoner::initializeCallbacks(Module &M) {
  1417. IRBuilder<> IRB(*C);
  1418. for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
  1419. std::string Suffix = itostr(i);
  1420. AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
  1421. M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
  1422. IntptrTy, nullptr));
  1423. AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
  1424. M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
  1425. IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
  1426. }
  1427. AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
  1428. M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
  1429. IntptrTy, IntptrTy, nullptr));
  1430. AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
  1431. M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
  1432. IntptrTy, IntptrTy, nullptr));
  1433. AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1434. kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
  1435. AsanAllocasUnpoisonFunc =
  1436. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1437. kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
  1438. }
  1439. void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
  1440. IRBuilder<> &IRB, Value *ShadowBase,
  1441. bool DoPoison) {
  1442. size_t n = ShadowBytes.size();
  1443. size_t i = 0;
  1444. // We need to (un)poison n bytes of stack shadow. Poison as many as we can
  1445. // using 64-bit stores (if we are on 64-bit arch), then poison the rest
  1446. // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
  1447. for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
  1448. LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
  1449. for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
  1450. uint64_t Val = 0;
  1451. for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
  1452. if (F.getParent()->getDataLayout().isLittleEndian())
  1453. Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
  1454. else
  1455. Val = (Val << 8) | ShadowBytes[i + j];
  1456. }
  1457. if (!Val) continue;
  1458. Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
  1459. Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
  1460. Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
  1461. IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
  1462. }
  1463. }
  1464. }
  1465. // Fake stack allocator (asan_fake_stack.h) has 11 size classes
  1466. // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
  1467. _Ret_range_(0, kMaxAsanStackMallocSizeClass)
  1468. static int StackMallocSizeClass(_In_range_(0, kMaxAsanStackMallocSizeClass) uint64_t LocalStackSize) {
  1469. assert(LocalStackSize <= kMaxStackMallocSize);
  1470. uint64_t MaxSize = kMinStackMallocSize;
  1471. for (int i = 0;; i++, MaxSize *= 2)
  1472. if (LocalStackSize <= MaxSize) return i;
  1473. llvm_unreachable("impossible LocalStackSize");
  1474. }
  1475. // Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
  1476. // We can not use MemSet intrinsic because it may end up calling the actual
  1477. // memset. Size is a multiple of 8.
  1478. // Currently this generates 8-byte stores on x86_64; it may be better to
  1479. // generate wider stores.
  1480. void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
  1481. IRBuilder<> &IRB, Value *ShadowBase, int Size) {
  1482. assert(!(Size % 8));
  1483. // kAsanStackAfterReturnMagic is 0xf5.
  1484. const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
  1485. for (int i = 0; i < Size; i += 8) {
  1486. Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
  1487. IRB.CreateStore(
  1488. ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
  1489. IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
  1490. }
  1491. }
  1492. PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
  1493. Value *ValueIfTrue,
  1494. Instruction *ThenTerm,
  1495. Value *ValueIfFalse) {
  1496. PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
  1497. BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
  1498. PHI->addIncoming(ValueIfFalse, CondBlock);
  1499. BasicBlock *ThenBlock = ThenTerm->getParent();
  1500. PHI->addIncoming(ValueIfTrue, ThenBlock);
  1501. return PHI;
  1502. }
  1503. Value *FunctionStackPoisoner::createAllocaForLayout(
  1504. IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
  1505. AllocaInst *Alloca;
  1506. if (Dynamic) {
  1507. Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
  1508. ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
  1509. "MyAlloca");
  1510. } else {
  1511. Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
  1512. nullptr, "MyAlloca");
  1513. assert(Alloca->isStaticAlloca());
  1514. }
  1515. assert((ClRealignStack & (ClRealignStack - 1)) == 0);
  1516. size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
  1517. Alloca->setAlignment(FrameAlignment);
  1518. return IRB.CreatePointerCast(Alloca, IntptrTy);
  1519. }
  1520. void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
  1521. BasicBlock &FirstBB = *F.begin();
  1522. IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
  1523. DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
  1524. IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
  1525. DynamicAllocaLayout->setAlignment(32);
  1526. }
  1527. void FunctionStackPoisoner::poisonStack() {
  1528. assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
  1529. if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
  1530. // Handle dynamic allocas.
  1531. createDynamicAllocasInitStorage();
  1532. for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
  1533. unpoisonDynamicAllocas();
  1534. }
  1535. if (AllocaVec.size() == 0) return;
  1536. int StackMallocIdx = -1;
  1537. DebugLoc EntryDebugLocation;
  1538. if (auto SP = getDISubprogram(&F))
  1539. EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
  1540. Instruction *InsBefore = AllocaVec[0];
  1541. IRBuilder<> IRB(InsBefore);
  1542. IRB.SetCurrentDebugLocation(EntryDebugLocation);
  1543. SmallVector<ASanStackVariableDescription, 16> SVD;
  1544. SVD.reserve(AllocaVec.size());
  1545. for (AllocaInst *AI : AllocaVec) {
  1546. ASanStackVariableDescription D = {AI->getName().data(),
  1547. ASan.getAllocaSizeInBytes(AI),
  1548. AI->getAlignment(), AI, 0};
  1549. SVD.push_back(D);
  1550. }
  1551. // Minimal header size (left redzone) is 4 pointers,
  1552. // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
  1553. size_t MinHeaderSize = ASan.LongSize / 2;
  1554. ASanStackFrameLayout L;
  1555. ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
  1556. DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
  1557. uint64_t LocalStackSize = L.FrameSize;
  1558. bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
  1559. LocalStackSize <= kMaxStackMallocSize;
  1560. // Don't do dynamic alloca or stack malloc in presence of inline asm:
  1561. // too often it makes assumptions on which registers are available.
  1562. bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
  1563. DoStackMalloc &= !HasNonEmptyInlineAsm;
  1564. Value *StaticAlloca =
  1565. DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
  1566. Value *FakeStack;
  1567. Value *LocalStackBase;
  1568. if (DoStackMalloc) {
  1569. // void *FakeStack = __asan_option_detect_stack_use_after_return
  1570. // ? __asan_stack_malloc_N(LocalStackSize)
  1571. // : nullptr;
  1572. // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
  1573. Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
  1574. kAsanOptionDetectUAR, IRB.getInt32Ty());
  1575. Value *UARIsEnabled =
  1576. IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
  1577. Constant::getNullValue(IRB.getInt32Ty()));
  1578. Instruction *Term =
  1579. SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
  1580. IRBuilder<> IRBIf(Term);
  1581. IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
  1582. StackMallocIdx = StackMallocSizeClass(LocalStackSize);
  1583. assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
  1584. Value *FakeStackValue =
  1585. IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
  1586. ConstantInt::get(IntptrTy, LocalStackSize));
  1587. IRB.SetInsertPoint(InsBefore);
  1588. IRB.SetCurrentDebugLocation(EntryDebugLocation);
  1589. FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
  1590. ConstantInt::get(IntptrTy, 0));
  1591. Value *NoFakeStack =
  1592. IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
  1593. Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
  1594. IRBIf.SetInsertPoint(Term);
  1595. IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
  1596. Value *AllocaValue =
  1597. DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
  1598. IRB.SetInsertPoint(InsBefore);
  1599. IRB.SetCurrentDebugLocation(EntryDebugLocation);
  1600. LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
  1601. } else {
  1602. // void *FakeStack = nullptr;
  1603. // void *LocalStackBase = alloca(LocalStackSize);
  1604. FakeStack = ConstantInt::get(IntptrTy, 0);
  1605. LocalStackBase =
  1606. DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
  1607. }
  1608. // Insert poison calls for lifetime intrinsics for alloca.
  1609. bool HavePoisonedAllocas = false;
  1610. for (const auto &APC : AllocaPoisonCallVec) {
  1611. assert(APC.InsBefore);
  1612. assert(APC.AI);
  1613. IRBuilder<> IRB(APC.InsBefore);
  1614. poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
  1615. HavePoisonedAllocas |= APC.DoPoison;
  1616. }
  1617. // Replace Alloca instructions with base+offset.
  1618. for (const auto &Desc : SVD) {
  1619. AllocaInst *AI = Desc.AI;
  1620. Value *NewAllocaPtr = IRB.CreateIntToPtr(
  1621. IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
  1622. AI->getType());
  1623. replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
  1624. AI->replaceAllUsesWith(NewAllocaPtr);
  1625. }
  1626. // The left-most redzone has enough space for at least 4 pointers.
  1627. // Write the Magic value to redzone[0].
  1628. Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
  1629. IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
  1630. BasePlus0);
  1631. // Write the frame description constant to redzone[1].
  1632. Value *BasePlus1 = IRB.CreateIntToPtr(
  1633. IRB.CreateAdd(LocalStackBase,
  1634. ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
  1635. IntptrPtrTy);
  1636. GlobalVariable *StackDescriptionGlobal =
  1637. createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
  1638. /*AllowMerging*/ true);
  1639. Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
  1640. IRB.CreateStore(Description, BasePlus1);
  1641. // Write the PC to redzone[2].
  1642. Value *BasePlus2 = IRB.CreateIntToPtr(
  1643. IRB.CreateAdd(LocalStackBase,
  1644. ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
  1645. IntptrPtrTy);
  1646. IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
  1647. // Poison the stack redzones at the entry.
  1648. Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
  1649. poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
  1650. // (Un)poison the stack before all ret instructions.
  1651. for (auto Ret : RetVec) {
  1652. IRBuilder<> IRBRet(Ret);
  1653. // Mark the current frame as retired.
  1654. IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
  1655. BasePlus0);
  1656. if (DoStackMalloc) {
  1657. assert(StackMallocIdx >= 0);
  1658. // if FakeStack != 0 // LocalStackBase == FakeStack
  1659. // // In use-after-return mode, poison the whole stack frame.
  1660. // if StackMallocIdx <= 4
  1661. // // For small sizes inline the whole thing:
  1662. // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
  1663. // **SavedFlagPtr(FakeStack) = 0
  1664. // else
  1665. // __asan_stack_free_N(FakeStack, LocalStackSize)
  1666. // else
  1667. // <This is not a fake stack; unpoison the redzones>
  1668. Value *Cmp =
  1669. IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
  1670. TerminatorInst *ThenTerm, *ElseTerm;
  1671. SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
  1672. IRBuilder<> IRBPoison(ThenTerm);
  1673. if (StackMallocIdx <= 4) {
  1674. int ClassSize = kMinStackMallocSize << StackMallocIdx;
  1675. SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
  1676. ClassSize >> Mapping.Scale);
  1677. Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
  1678. FakeStack,
  1679. ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
  1680. Value *SavedFlagPtr = IRBPoison.CreateLoad(
  1681. IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
  1682. IRBPoison.CreateStore(
  1683. Constant::getNullValue(IRBPoison.getInt8Ty()),
  1684. IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
  1685. } else {
  1686. // For larger frames call __asan_stack_free_*.
  1687. IRBPoison.CreateCall(
  1688. AsanStackFreeFunc[StackMallocIdx],
  1689. {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
  1690. }
  1691. IRBuilder<> IRBElse(ElseTerm);
  1692. poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
  1693. } else if (HavePoisonedAllocas) {
  1694. // If we poisoned some allocas in llvm.lifetime analysis,
  1695. // unpoison whole stack frame now.
  1696. poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
  1697. } else {
  1698. poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
  1699. }
  1700. }
  1701. // We are done. Remove the old unused alloca instructions.
  1702. for (auto AI : AllocaVec) AI->eraseFromParent();
  1703. }
  1704. void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
  1705. IRBuilder<> &IRB, bool DoPoison) {
  1706. // For now just insert the call to ASan runtime.
  1707. Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
  1708. Value *SizeArg = ConstantInt::get(IntptrTy, Size);
  1709. IRB.CreateCall(
  1710. DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
  1711. {AddrArg, SizeArg});
  1712. }
  1713. // Handling llvm.lifetime intrinsics for a given %alloca:
  1714. // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
  1715. // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
  1716. // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
  1717. // could be poisoned by previous llvm.lifetime.end instruction, as the
  1718. // variable may go in and out of scope several times, e.g. in loops).
  1719. // (3) if we poisoned at least one %alloca in a function,
  1720. // unpoison the whole stack frame at function exit.
  1721. AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
  1722. if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
  1723. // We're intested only in allocas we can handle.
  1724. return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
  1725. // See if we've already calculated (or started to calculate) alloca for a
  1726. // given value.
  1727. AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
  1728. if (I != AllocaForValue.end()) return I->second;
  1729. // Store 0 while we're calculating alloca for value V to avoid
  1730. // infinite recursion if the value references itself.
  1731. AllocaForValue[V] = nullptr;
  1732. AllocaInst *Res = nullptr;
  1733. if (CastInst *CI = dyn_cast<CastInst>(V))
  1734. Res = findAllocaForValue(CI->getOperand(0));
  1735. else if (PHINode *PN = dyn_cast<PHINode>(V)) {
  1736. for (Value *IncValue : PN->incoming_values()) {
  1737. // Allow self-referencing phi-nodes.
  1738. if (IncValue == PN) continue;
  1739. AllocaInst *IncValueAI = findAllocaForValue(IncValue);
  1740. // AI for incoming values should exist and should all be equal.
  1741. if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
  1742. return nullptr;
  1743. Res = IncValueAI;
  1744. }
  1745. }
  1746. if (Res) AllocaForValue[V] = Res;
  1747. return Res;
  1748. }
  1749. void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
  1750. IRBuilder<> IRB(AI);
  1751. const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
  1752. const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
  1753. Value *Zero = Constant::getNullValue(IntptrTy);
  1754. Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
  1755. Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
  1756. // Since we need to extend alloca with additional memory to locate
  1757. // redzones, and OldSize is number of allocated blocks with
  1758. // ElementSize size, get allocated memory size in bytes by
  1759. // OldSize * ElementSize.
  1760. const unsigned ElementSize =
  1761. F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
  1762. Value *OldSize =
  1763. IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
  1764. ConstantInt::get(IntptrTy, ElementSize));
  1765. // PartialSize = OldSize % 32
  1766. Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
  1767. // Misalign = kAllocaRzSize - PartialSize;
  1768. Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
  1769. // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
  1770. Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
  1771. Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
  1772. // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
  1773. // Align is added to locate left redzone, PartialPadding for possible
  1774. // partial redzone and kAllocaRzSize for right redzone respectively.
  1775. Value *AdditionalChunkSize = IRB.CreateAdd(
  1776. ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
  1777. Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
  1778. // Insert new alloca with new NewSize and Align params.
  1779. AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
  1780. NewAlloca->setAlignment(Align);
  1781. // NewAddress = Address + Align
  1782. Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
  1783. ConstantInt::get(IntptrTy, Align));
  1784. // Insert __asan_alloca_poison call for new created alloca.
  1785. IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
  1786. // Store the last alloca's address to DynamicAllocaLayout. We'll need this
  1787. // for unpoisoning stuff.
  1788. IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
  1789. Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
  1790. // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
  1791. AI->replaceAllUsesWith(NewAddressPtr);
  1792. // We are done. Erase old alloca from parent.
  1793. AI->eraseFromParent();
  1794. }
  1795. // isSafeAccess returns true if Addr is always inbounds with respect to its
  1796. // base object. For example, it is a field access or an array access with
  1797. // constant inbounds index.
  1798. bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
  1799. Value *Addr, uint64_t TypeSize) const {
  1800. SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
  1801. if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
  1802. uint64_t Size = SizeOffset.first.getZExtValue();
  1803. int64_t Offset = SizeOffset.second.getSExtValue();
  1804. // Three checks are required to ensure safety:
  1805. // . Offset >= 0 (since the offset is given from the base ptr)
  1806. // . Size >= Offset (unsigned)
  1807. // . Size - Offset >= NeededSize (unsigned)
  1808. return Offset >= 0 && Size >= uint64_t(Offset) &&
  1809. Size - uint64_t(Offset) >= TypeSize / 8;
  1810. }