AddressSanitizer.cpp 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964
  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/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/DepthFirstIterator.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/ADT/StringExtras.h"
  23. #include "llvm/ADT/Triple.h"
  24. #include "llvm/Analysis/MemoryBuiltins.h"
  25. #include "llvm/Analysis/TargetLibraryInfo.h"
  26. #include "llvm/Analysis/ValueTracking.h"
  27. #include "llvm/IR/CallSite.h"
  28. #include "llvm/IR/DIBuilder.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/Dominators.h"
  31. #include "llvm/IR/Function.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/InlineAsm.h"
  34. #include "llvm/IR/InstVisitor.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/LLVMContext.h"
  37. #include "llvm/IR/MDBuilder.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/MC/MCSectionMachO.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/DataTypes.h"
  43. #include "llvm/Support/Debug.h"
  44. #include "llvm/Support/Endian.h"
  45. #include "llvm/Support/SwapByteOrder.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include "llvm/Transforms/Instrumentation.h"
  48. #include "llvm/Transforms/Scalar.h"
  49. #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
  50. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  51. #include "llvm/Transforms/Utils/Cloning.h"
  52. #include "llvm/Transforms/Utils/Local.h"
  53. #include "llvm/Transforms/Utils/ModuleUtils.h"
  54. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  55. #include <algorithm>
  56. #include <iomanip>
  57. #include <limits>
  58. #include <sstream>
  59. #include <string>
  60. #include <system_error>
  61. using namespace llvm;
  62. #define DEBUG_TYPE "asan"
  63. static const uint64_t kDefaultShadowScale = 3;
  64. static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
  65. static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
  66. static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
  67. static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
  68. static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
  69. static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
  70. static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
  71. static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
  72. static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
  73. static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
  74. static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
  75. static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
  76. static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
  77. static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
  78. static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
  79. static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
  80. static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
  81. // The shadow memory space is dynamically allocated.
  82. static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
  83. static const size_t kMinStackMallocSize = 1 << 6; // 64B
  84. static const size_t kMaxStackMallocSize = 1 << 16; // 64K
  85. static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
  86. static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
  87. static const char *const kAsanModuleCtorName = "asan.module_ctor";
  88. static const char *const kAsanModuleDtorName = "asan.module_dtor";
  89. static const uint64_t kAsanCtorAndDtorPriority = 1;
  90. static const char *const kAsanReportErrorTemplate = "__asan_report_";
  91. static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
  92. static const char *const kAsanUnregisterGlobalsName =
  93. "__asan_unregister_globals";
  94. static const char *const kAsanRegisterImageGlobalsName =
  95. "__asan_register_image_globals";
  96. static const char *const kAsanUnregisterImageGlobalsName =
  97. "__asan_unregister_image_globals";
  98. static const char *const kAsanRegisterElfGlobalsName =
  99. "__asan_register_elf_globals";
  100. static const char *const kAsanUnregisterElfGlobalsName =
  101. "__asan_unregister_elf_globals";
  102. static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
  103. static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
  104. static const char *const kAsanInitName = "__asan_init";
  105. static const char *const kAsanVersionCheckName =
  106. "__asan_version_mismatch_check_v8";
  107. static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
  108. static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
  109. static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
  110. static const int kMaxAsanStackMallocSizeClass = 10;
  111. static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
  112. static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
  113. static const char *const kAsanGenPrefix = "__asan_gen_";
  114. static const char *const kODRGenPrefix = "__odr_asan_gen_";
  115. static const char *const kSanCovGenPrefix = "__sancov_gen_";
  116. static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
  117. static const char *const kAsanPoisonStackMemoryName =
  118. "__asan_poison_stack_memory";
  119. static const char *const kAsanUnpoisonStackMemoryName =
  120. "__asan_unpoison_stack_memory";
  121. // ASan version script has __asan_* wildcard. Triple underscore prevents a
  122. // linker (gold) warning about attempting to export a local symbol.
  123. static const char *const kAsanGlobalsRegisteredFlagName =
  124. "___asan_globals_registered";
  125. static const char *const kAsanOptionDetectUseAfterReturn =
  126. "__asan_option_detect_stack_use_after_return";
  127. static const char *const kAsanShadowMemoryDynamicAddress =
  128. "__asan_shadow_memory_dynamic_address";
  129. static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
  130. static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
  131. // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
  132. static const size_t kNumberOfAccessSizes = 5;
  133. static const unsigned kAllocaRzSize = 32;
  134. // Command-line flags.
  135. static cl::opt<bool> ClEnableKasan(
  136. "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
  137. cl::Hidden, cl::init(false));
  138. static cl::opt<bool> ClRecover(
  139. "asan-recover",
  140. cl::desc("Enable recovery mode (continue-after-error)."),
  141. cl::Hidden, cl::init(false));
  142. // This flag may need to be replaced with -f[no-]asan-reads.
  143. static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
  144. cl::desc("instrument read instructions"),
  145. cl::Hidden, cl::init(true));
  146. static cl::opt<bool> ClInstrumentWrites(
  147. "asan-instrument-writes", cl::desc("instrument write instructions"),
  148. cl::Hidden, cl::init(true));
  149. static cl::opt<bool> ClInstrumentAtomics(
  150. "asan-instrument-atomics",
  151. cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
  152. cl::init(true));
  153. static cl::opt<bool> ClAlwaysSlowPath(
  154. "asan-always-slow-path",
  155. cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
  156. cl::init(false));
  157. static cl::opt<bool> ClForceDynamicShadow(
  158. "asan-force-dynamic-shadow",
  159. cl::desc("Load shadow address into a local variable for each function"),
  160. cl::Hidden, cl::init(false));
  161. // This flag limits the number of instructions to be instrumented
  162. // in any given BB. Normally, this should be set to unlimited (INT_MAX),
  163. // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
  164. // set it to 10000.
  165. static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
  166. "asan-max-ins-per-bb", cl::init(10000),
  167. cl::desc("maximal number of instructions to instrument in any given BB"),
  168. cl::Hidden);
  169. // This flag may need to be replaced with -f[no]asan-stack.
  170. static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
  171. cl::Hidden, cl::init(true));
  172. static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
  173. "asan-max-inline-poisoning-size",
  174. cl::desc(
  175. "Inline shadow poisoning for blocks up to the given size in bytes."),
  176. cl::Hidden, cl::init(64));
  177. static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
  178. cl::desc("Check stack-use-after-return"),
  179. cl::Hidden, cl::init(true));
  180. static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
  181. cl::desc("Check stack-use-after-scope"),
  182. cl::Hidden, cl::init(false));
  183. // This flag may need to be replaced with -f[no]asan-globals.
  184. static cl::opt<bool> ClGlobals("asan-globals",
  185. cl::desc("Handle global objects"), cl::Hidden,
  186. cl::init(true));
  187. static cl::opt<bool> ClInitializers("asan-initialization-order",
  188. cl::desc("Handle C++ initializer order"),
  189. cl::Hidden, cl::init(true));
  190. static cl::opt<bool> ClInvalidPointerPairs(
  191. "asan-detect-invalid-pointer-pair",
  192. cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
  193. cl::init(false));
  194. static cl::opt<unsigned> ClRealignStack(
  195. "asan-realign-stack",
  196. cl::desc("Realign stack to the value of this flag (power of two)"),
  197. cl::Hidden, cl::init(32));
  198. static cl::opt<int> ClInstrumentationWithCallsThreshold(
  199. "asan-instrumentation-with-call-threshold",
  200. cl::desc(
  201. "If the function being instrumented contains more than "
  202. "this number of memory accesses, use callbacks instead of "
  203. "inline checks (-1 means never use callbacks)."),
  204. cl::Hidden, cl::init(7000));
  205. static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
  206. "asan-memory-access-callback-prefix",
  207. cl::desc("Prefix for memory access callbacks"), cl::Hidden,
  208. cl::init("__asan_"));
  209. static cl::opt<bool>
  210. ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
  211. cl::desc("instrument dynamic allocas"),
  212. cl::Hidden, cl::init(true));
  213. static cl::opt<bool> ClSkipPromotableAllocas(
  214. "asan-skip-promotable-allocas",
  215. cl::desc("Do not instrument promotable allocas"), cl::Hidden,
  216. cl::init(true));
  217. // These flags allow to change the shadow mapping.
  218. // The shadow mapping looks like
  219. // Shadow = (Mem >> scale) + offset
  220. static cl::opt<int> ClMappingScale("asan-mapping-scale",
  221. cl::desc("scale of asan shadow mapping"),
  222. cl::Hidden, cl::init(0));
  223. static cl::opt<unsigned long long> ClMappingOffset(
  224. "asan-mapping-offset",
  225. cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
  226. cl::init(0));
  227. // Optimization flags. Not user visible, used mostly for testing
  228. // and benchmarking the tool.
  229. static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
  230. cl::Hidden, cl::init(true));
  231. static cl::opt<bool> ClOptSameTemp(
  232. "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
  233. cl::Hidden, cl::init(true));
  234. static cl::opt<bool> ClOptGlobals("asan-opt-globals",
  235. cl::desc("Don't instrument scalar globals"),
  236. cl::Hidden, cl::init(true));
  237. static cl::opt<bool> ClOptStack(
  238. "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
  239. cl::Hidden, cl::init(false));
  240. static cl::opt<bool> ClDynamicAllocaStack(
  241. "asan-stack-dynamic-alloca",
  242. cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
  243. cl::init(true));
  244. static cl::opt<uint32_t> ClForceExperiment(
  245. "asan-force-experiment",
  246. cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
  247. cl::init(0));
  248. static cl::opt<bool>
  249. ClUsePrivateAliasForGlobals("asan-use-private-alias",
  250. cl::desc("Use private aliases for global"
  251. " variables"),
  252. cl::Hidden, cl::init(false));
  253. static cl::opt<bool>
  254. ClUseGlobalsGC("asan-globals-live-support",
  255. cl::desc("Use linker features to support dead "
  256. "code stripping of globals"),
  257. cl::Hidden, cl::init(true));
  258. // This is on by default even though there is a bug in gold:
  259. // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
  260. static cl::opt<bool>
  261. ClWithComdat("asan-with-comdat",
  262. cl::desc("Place ASan constructors in comdat sections"),
  263. cl::Hidden, cl::init(true));
  264. // Debug flags.
  265. static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
  266. cl::init(0));
  267. static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
  268. cl::Hidden, cl::init(0));
  269. static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
  270. cl::desc("Debug func"));
  271. static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
  272. cl::Hidden, cl::init(-1));
  273. static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
  274. cl::Hidden, cl::init(-1));
  275. STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
  276. STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
  277. STATISTIC(NumOptimizedAccessesToGlobalVar,
  278. "Number of optimized accesses to global vars");
  279. STATISTIC(NumOptimizedAccessesToStackVar,
  280. "Number of optimized accesses to stack vars");
  281. namespace {
  282. /// Frontend-provided metadata for source location.
  283. struct LocationMetadata {
  284. StringRef Filename;
  285. int LineNo;
  286. int ColumnNo;
  287. LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
  288. bool empty() const { return Filename.empty(); }
  289. void parse(MDNode *MDN) {
  290. assert(MDN->getNumOperands() == 3);
  291. MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
  292. Filename = DIFilename->getString();
  293. LineNo =
  294. mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
  295. ColumnNo =
  296. mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
  297. }
  298. };
  299. /// Frontend-provided metadata for global variables.
  300. class GlobalsMetadata {
  301. public:
  302. struct Entry {
  303. Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
  304. LocationMetadata SourceLoc;
  305. StringRef Name;
  306. bool IsDynInit;
  307. bool IsBlacklisted;
  308. };
  309. GlobalsMetadata() : inited_(false) {}
  310. void reset() {
  311. inited_ = false;
  312. Entries.clear();
  313. }
  314. void init(Module &M) {
  315. assert(!inited_);
  316. inited_ = true;
  317. NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
  318. if (!Globals) return;
  319. for (auto MDN : Globals->operands()) {
  320. // Metadata node contains the global and the fields of "Entry".
  321. assert(MDN->getNumOperands() == 5);
  322. auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
  323. // The optimizer may optimize away a global entirely.
  324. if (!GV) continue;
  325. // We can already have an entry for GV if it was merged with another
  326. // global.
  327. Entry &E = Entries[GV];
  328. if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
  329. E.SourceLoc.parse(Loc);
  330. if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
  331. E.Name = Name->getString();
  332. ConstantInt *IsDynInit =
  333. mdconst::extract<ConstantInt>(MDN->getOperand(3));
  334. E.IsDynInit |= IsDynInit->isOne();
  335. ConstantInt *IsBlacklisted =
  336. mdconst::extract<ConstantInt>(MDN->getOperand(4));
  337. E.IsBlacklisted |= IsBlacklisted->isOne();
  338. }
  339. }
  340. /// Returns metadata entry for a given global.
  341. Entry get(GlobalVariable *G) const {
  342. auto Pos = Entries.find(G);
  343. return (Pos != Entries.end()) ? Pos->second : Entry();
  344. }
  345. private:
  346. bool inited_;
  347. DenseMap<GlobalVariable *, Entry> Entries;
  348. };
  349. /// This struct defines the shadow mapping using the rule:
  350. /// shadow = (mem >> Scale) ADD-or-OR Offset.
  351. struct ShadowMapping {
  352. int Scale;
  353. uint64_t Offset;
  354. bool OrShadowOffset;
  355. };
  356. static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
  357. bool IsKasan) {
  358. bool IsAndroid = TargetTriple.isAndroid();
  359. bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
  360. bool IsFreeBSD = TargetTriple.isOSFreeBSD();
  361. bool IsPS4CPU = TargetTriple.isPS4CPU();
  362. bool IsLinux = TargetTriple.isOSLinux();
  363. bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
  364. TargetTriple.getArch() == llvm::Triple::ppc64le;
  365. bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
  366. bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
  367. bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
  368. bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
  369. TargetTriple.getArch() == llvm::Triple::mipsel;
  370. bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
  371. TargetTriple.getArch() == llvm::Triple::mips64el;
  372. bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
  373. bool IsWindows = TargetTriple.isOSWindows();
  374. bool IsFuchsia = TargetTriple.isOSFuchsia();
  375. ShadowMapping Mapping;
  376. if (LongSize == 32) {
  377. // Android is always PIE, which means that the beginning of the address
  378. // space is always available.
  379. if (IsAndroid)
  380. Mapping.Offset = 0;
  381. else if (IsMIPS32)
  382. Mapping.Offset = kMIPS32_ShadowOffset32;
  383. else if (IsFreeBSD)
  384. Mapping.Offset = kFreeBSD_ShadowOffset32;
  385. else if (IsIOS)
  386. // If we're targeting iOS and x86, the binary is built for iOS simulator.
  387. Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
  388. else if (IsWindows)
  389. Mapping.Offset = kWindowsShadowOffset32;
  390. else
  391. Mapping.Offset = kDefaultShadowOffset32;
  392. } else { // LongSize == 64
  393. // Fuchsia is always PIE, which means that the beginning of the address
  394. // space is always available.
  395. if (IsFuchsia)
  396. Mapping.Offset = 0;
  397. else if (IsPPC64)
  398. Mapping.Offset = kPPC64_ShadowOffset64;
  399. else if (IsSystemZ)
  400. Mapping.Offset = kSystemZ_ShadowOffset64;
  401. else if (IsFreeBSD)
  402. Mapping.Offset = kFreeBSD_ShadowOffset64;
  403. else if (IsPS4CPU)
  404. Mapping.Offset = kPS4CPU_ShadowOffset64;
  405. else if (IsLinux && IsX86_64) {
  406. if (IsKasan)
  407. Mapping.Offset = kLinuxKasan_ShadowOffset64;
  408. else
  409. Mapping.Offset = kSmallX86_64ShadowOffset;
  410. } else if (IsWindows && IsX86_64) {
  411. Mapping.Offset = kWindowsShadowOffset64;
  412. } else if (IsMIPS64)
  413. Mapping.Offset = kMIPS64_ShadowOffset64;
  414. else if (IsIOS)
  415. // If we're targeting iOS and x86, the binary is built for iOS simulator.
  416. // We are using dynamic shadow offset on the 64-bit devices.
  417. Mapping.Offset =
  418. IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
  419. else if (IsAArch64)
  420. Mapping.Offset = kAArch64_ShadowOffset64;
  421. else
  422. Mapping.Offset = kDefaultShadowOffset64;
  423. }
  424. if (ClForceDynamicShadow) {
  425. Mapping.Offset = kDynamicShadowSentinel;
  426. }
  427. Mapping.Scale = kDefaultShadowScale;
  428. if (ClMappingScale.getNumOccurrences() > 0) {
  429. Mapping.Scale = ClMappingScale;
  430. }
  431. if (ClMappingOffset.getNumOccurrences() > 0) {
  432. Mapping.Offset = ClMappingOffset;
  433. }
  434. // OR-ing shadow offset if more efficient (at least on x86) if the offset
  435. // is a power of two, but on ppc64 we have to use add since the shadow
  436. // offset is not necessary 1/8-th of the address space. On SystemZ,
  437. // we could OR the constant in a single instruction, but it's more
  438. // efficient to load it once and use indexed addressing.
  439. Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
  440. !(Mapping.Offset & (Mapping.Offset - 1)) &&
  441. Mapping.Offset != kDynamicShadowSentinel;
  442. return Mapping;
  443. }
  444. static size_t RedzoneSizeForScale(int MappingScale) {
  445. // Redzone used for stack and globals is at least 32 bytes.
  446. // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
  447. return std::max(32U, 1U << MappingScale);
  448. }
  449. /// AddressSanitizer: instrument the code in module to find memory bugs.
  450. struct AddressSanitizer : public FunctionPass {
  451. explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
  452. bool UseAfterScope = false)
  453. : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
  454. Recover(Recover || ClRecover),
  455. UseAfterScope(UseAfterScope || ClUseAfterScope),
  456. LocalDynamicShadow(nullptr) {
  457. initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
  458. }
  459. StringRef getPassName() const override {
  460. return "AddressSanitizerFunctionPass";
  461. }
  462. void getAnalysisUsage(AnalysisUsage &AU) const override {
  463. AU.addRequired<DominatorTreeWrapperPass>();
  464. AU.addRequired<TargetLibraryInfoWrapperPass>();
  465. }
  466. uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
  467. uint64_t ArraySize = 1;
  468. if (AI.isArrayAllocation()) {
  469. const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
  470. assert(CI && "non-constant array size");
  471. ArraySize = CI->getZExtValue();
  472. }
  473. Type *Ty = AI.getAllocatedType();
  474. uint64_t SizeInBytes =
  475. AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
  476. return SizeInBytes * ArraySize;
  477. }
  478. /// Check if we want (and can) handle this alloca.
  479. bool isInterestingAlloca(const AllocaInst &AI);
  480. /// If it is an interesting memory access, return the PointerOperand
  481. /// and set IsWrite/Alignment. Otherwise return nullptr.
  482. /// MaybeMask is an output parameter for the mask Value, if we're looking at a
  483. /// masked load/store.
  484. Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
  485. uint64_t *TypeSize, unsigned *Alignment,
  486. Value **MaybeMask = nullptr);
  487. void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
  488. bool UseCalls, const DataLayout &DL);
  489. void instrumentPointerComparisonOrSubtraction(Instruction *I);
  490. void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
  491. Value *Addr, uint32_t TypeSize, bool IsWrite,
  492. Value *SizeArgument, bool UseCalls, uint32_t Exp);
  493. void instrumentUnusualSizeOrAlignment(Instruction *I,
  494. Instruction *InsertBefore, Value *Addr,
  495. uint32_t TypeSize, bool IsWrite,
  496. Value *SizeArgument, bool UseCalls,
  497. uint32_t Exp);
  498. Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
  499. Value *ShadowValue, uint32_t TypeSize);
  500. Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
  501. bool IsWrite, size_t AccessSizeIndex,
  502. Value *SizeArgument, uint32_t Exp);
  503. void instrumentMemIntrinsic(MemIntrinsic *MI);
  504. Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
  505. bool runOnFunction(Function &F) override;
  506. bool maybeInsertAsanInitAtFunctionEntry(Function &F);
  507. void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
  508. void markEscapedLocalAllocas(Function &F);
  509. bool doInitialization(Module &M) override;
  510. bool doFinalization(Module &M) override;
  511. static char ID; // Pass identification, replacement for typeid
  512. DominatorTree &getDominatorTree() const { return *DT; }
  513. private:
  514. void initializeCallbacks(Module &M);
  515. bool LooksLikeCodeInBug11395(Instruction *I);
  516. bool GlobalIsLinkerInitialized(GlobalVariable *G);
  517. bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
  518. uint64_t TypeSize) const;
  519. /// Helper to cleanup per-function state.
  520. struct FunctionStateRAII {
  521. AddressSanitizer *Pass;
  522. FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
  523. assert(Pass->ProcessedAllocas.empty() &&
  524. "last pass forgot to clear cache");
  525. assert(!Pass->LocalDynamicShadow);
  526. }
  527. ~FunctionStateRAII() {
  528. Pass->LocalDynamicShadow = nullptr;
  529. Pass->ProcessedAllocas.clear();
  530. }
  531. };
  532. LLVMContext *C;
  533. Triple TargetTriple;
  534. int LongSize;
  535. bool CompileKernel;
  536. bool Recover;
  537. bool UseAfterScope;
  538. Type *IntptrTy;
  539. ShadowMapping Mapping;
  540. DominatorTree *DT;
  541. Function *AsanHandleNoReturnFunc;
  542. Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
  543. // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
  544. Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
  545. Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
  546. // This array is indexed by AccessIsWrite and Experiment.
  547. Function *AsanErrorCallbackSized[2][2];
  548. Function *AsanMemoryAccessCallbackSized[2][2];
  549. Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
  550. InlineAsm *EmptyAsm;
  551. Value *LocalDynamicShadow;
  552. GlobalsMetadata GlobalsMD;
  553. DenseMap<const AllocaInst *, bool> ProcessedAllocas;
  554. friend struct FunctionStackPoisoner;
  555. };
  556. class AddressSanitizerModule : public ModulePass {
  557. public:
  558. explicit AddressSanitizerModule(bool CompileKernel = false,
  559. bool Recover = false,
  560. bool UseGlobalsGC = true)
  561. : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
  562. Recover(Recover || ClRecover),
  563. UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC) {}
  564. bool runOnModule(Module &M) override;
  565. static char ID; // Pass identification, replacement for typeid
  566. StringRef getPassName() const override { return "AddressSanitizerModule"; }
  567. private:
  568. void initializeCallbacks(Module &M);
  569. bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
  570. void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
  571. ArrayRef<GlobalVariable *> ExtendedGlobals,
  572. ArrayRef<Constant *> MetadataInitializers);
  573. void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
  574. ArrayRef<GlobalVariable *> ExtendedGlobals,
  575. ArrayRef<Constant *> MetadataInitializers,
  576. const std::string &UniqueModuleId);
  577. void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
  578. ArrayRef<GlobalVariable *> ExtendedGlobals,
  579. ArrayRef<Constant *> MetadataInitializers);
  580. void
  581. InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
  582. ArrayRef<GlobalVariable *> ExtendedGlobals,
  583. ArrayRef<Constant *> MetadataInitializers);
  584. GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
  585. StringRef OriginalName);
  586. void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
  587. StringRef InternalSuffix);
  588. IRBuilder<> CreateAsanModuleDtor(Module &M);
  589. bool ShouldInstrumentGlobal(GlobalVariable *G);
  590. bool ShouldUseMachOGlobalsSection() const;
  591. StringRef getGlobalMetadataSection() const;
  592. void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
  593. void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
  594. size_t MinRedzoneSizeForGlobal() const {
  595. return RedzoneSizeForScale(Mapping.Scale);
  596. }
  597. GlobalsMetadata GlobalsMD;
  598. bool CompileKernel;
  599. bool Recover;
  600. bool UseGlobalsGC;
  601. Type *IntptrTy;
  602. LLVMContext *C;
  603. Triple TargetTriple;
  604. ShadowMapping Mapping;
  605. Function *AsanPoisonGlobals;
  606. Function *AsanUnpoisonGlobals;
  607. Function *AsanRegisterGlobals;
  608. Function *AsanUnregisterGlobals;
  609. Function *AsanRegisterImageGlobals;
  610. Function *AsanUnregisterImageGlobals;
  611. Function *AsanRegisterElfGlobals;
  612. Function *AsanUnregisterElfGlobals;
  613. Function *AsanCtorFunction = nullptr;
  614. Function *AsanDtorFunction = nullptr;
  615. };
  616. // Stack poisoning does not play well with exception handling.
  617. // When an exception is thrown, we essentially bypass the code
  618. // that unpoisones the stack. This is why the run-time library has
  619. // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
  620. // stack in the interceptor. This however does not work inside the
  621. // actual function which catches the exception. Most likely because the
  622. // compiler hoists the load of the shadow value somewhere too high.
  623. // This causes asan to report a non-existing bug on 453.povray.
  624. // It sounds like an LLVM bug.
  625. struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
  626. Function &F;
  627. AddressSanitizer &ASan;
  628. DIBuilder DIB;
  629. LLVMContext *C;
  630. Type *IntptrTy;
  631. Type *IntptrPtrTy;
  632. ShadowMapping Mapping;
  633. SmallVector<AllocaInst *, 16> AllocaVec;
  634. SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
  635. SmallVector<Instruction *, 8> RetVec;
  636. unsigned StackAlignment;
  637. Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
  638. *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
  639. Function *AsanSetShadowFunc[0x100] = {};
  640. Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
  641. Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
  642. // Stores a place and arguments of poisoning/unpoisoning call for alloca.
  643. struct AllocaPoisonCall {
  644. IntrinsicInst *InsBefore;
  645. AllocaInst *AI;
  646. uint64_t Size;
  647. bool DoPoison;
  648. };
  649. SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
  650. SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
  651. SmallVector<AllocaInst *, 1> DynamicAllocaVec;
  652. SmallVector<IntrinsicInst *, 1> StackRestoreVec;
  653. AllocaInst *DynamicAllocaLayout = nullptr;
  654. IntrinsicInst *LocalEscapeCall = nullptr;
  655. // Maps Value to an AllocaInst from which the Value is originated.
  656. typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
  657. AllocaForValueMapTy AllocaForValue;
  658. bool HasNonEmptyInlineAsm = false;
  659. bool HasReturnsTwiceCall = false;
  660. std::unique_ptr<CallInst> EmptyInlineAsm;
  661. FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
  662. : F(F),
  663. ASan(ASan),
  664. DIB(*F.getParent(), /*AllowUnresolved*/ false),
  665. C(ASan.C),
  666. IntptrTy(ASan.IntptrTy),
  667. IntptrPtrTy(PointerType::get(IntptrTy, 0)),
  668. Mapping(ASan.Mapping),
  669. StackAlignment(1 << Mapping.Scale),
  670. EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
  671. bool runOnFunction() {
  672. if (!ClStack) return false;
  673. // Collect alloca, ret, lifetime instructions etc.
  674. for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
  675. if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
  676. initializeCallbacks(*F.getParent());
  677. processDynamicAllocas();
  678. processStaticAllocas();
  679. if (ClDebugStack) {
  680. DEBUG(dbgs() << F);
  681. }
  682. return true;
  683. }
  684. // Finds all Alloca instructions and puts
  685. // poisoned red zones around all of them.
  686. // Then unpoison everything back before the function returns.
  687. void processStaticAllocas();
  688. void processDynamicAllocas();
  689. void createDynamicAllocasInitStorage();
  690. // ----------------------- Visitors.
  691. /// \brief Collect all Ret instructions.
  692. void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
  693. /// \brief Collect all Resume instructions.
  694. void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
  695. /// \brief Collect all CatchReturnInst instructions.
  696. void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
  697. void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
  698. Value *SavedStack) {
  699. IRBuilder<> IRB(InstBefore);
  700. Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
  701. // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
  702. // need to adjust extracted SP to compute the address of the most recent
  703. // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
  704. // this purpose.
  705. if (!isa<ReturnInst>(InstBefore)) {
  706. Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
  707. InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
  708. {IntptrTy});
  709. Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
  710. DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
  711. DynamicAreaOffset);
  712. }
  713. IRB.CreateCall(AsanAllocasUnpoisonFunc,
  714. {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
  715. }
  716. // Unpoison dynamic allocas redzones.
  717. void unpoisonDynamicAllocas() {
  718. for (auto &Ret : RetVec)
  719. unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
  720. for (auto &StackRestoreInst : StackRestoreVec)
  721. unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
  722. StackRestoreInst->getOperand(0));
  723. }
  724. // Deploy and poison redzones around dynamic alloca call. To do this, we
  725. // should replace this call with another one with changed parameters and
  726. // replace all its uses with new address, so
  727. // addr = alloca type, old_size, align
  728. // is replaced by
  729. // new_size = (old_size + additional_size) * sizeof(type)
  730. // tmp = alloca i8, new_size, max(align, 32)
  731. // addr = tmp + 32 (first 32 bytes are for the left redzone).
  732. // Additional_size is added to make new memory allocation contain not only
  733. // requested memory, but also left, partial and right redzones.
  734. void handleDynamicAllocaCall(AllocaInst *AI);
  735. /// \brief Collect Alloca instructions we want (and can) handle.
  736. void visitAllocaInst(AllocaInst &AI) {
  737. if (!ASan.isInterestingAlloca(AI)) {
  738. if (AI.isStaticAlloca()) {
  739. // Skip over allocas that are present *before* the first instrumented
  740. // alloca, we don't want to move those around.
  741. if (AllocaVec.empty())
  742. return;
  743. StaticAllocasToMoveUp.push_back(&AI);
  744. }
  745. return;
  746. }
  747. StackAlignment = std::max(StackAlignment, AI.getAlignment());
  748. if (!AI.isStaticAlloca())
  749. DynamicAllocaVec.push_back(&AI);
  750. else
  751. AllocaVec.push_back(&AI);
  752. }
  753. /// \brief Collect lifetime intrinsic calls to check for use-after-scope
  754. /// errors.
  755. void visitIntrinsicInst(IntrinsicInst &II) {
  756. Intrinsic::ID ID = II.getIntrinsicID();
  757. if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
  758. if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
  759. if (!ASan.UseAfterScope)
  760. return;
  761. if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
  762. return;
  763. // Found lifetime intrinsic, add ASan instrumentation if necessary.
  764. ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
  765. // If size argument is undefined, don't do anything.
  766. if (Size->isMinusOne()) return;
  767. // Check that size doesn't saturate uint64_t and can
  768. // be stored in IntptrTy.
  769. const uint64_t SizeValue = Size->getValue().getLimitedValue();
  770. if (SizeValue == ~0ULL ||
  771. !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
  772. return;
  773. // Find alloca instruction that corresponds to llvm.lifetime argument.
  774. AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
  775. if (!AI || !ASan.isInterestingAlloca(*AI))
  776. return;
  777. bool DoPoison = (ID == Intrinsic::lifetime_end);
  778. AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
  779. if (AI->isStaticAlloca())
  780. StaticAllocaPoisonCallVec.push_back(APC);
  781. else if (ClInstrumentDynamicAllocas)
  782. DynamicAllocaPoisonCallVec.push_back(APC);
  783. }
  784. void visitCallSite(CallSite CS) {
  785. Instruction *I = CS.getInstruction();
  786. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  787. HasNonEmptyInlineAsm |=
  788. CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
  789. HasReturnsTwiceCall |= CI->canReturnTwice();
  790. }
  791. }
  792. // ---------------------- Helpers.
  793. void initializeCallbacks(Module &M);
  794. bool doesDominateAllExits(const Instruction *I) const {
  795. for (auto Ret : RetVec) {
  796. if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
  797. }
  798. return true;
  799. }
  800. /// Finds alloca where the value comes from.
  801. AllocaInst *findAllocaForValue(Value *V);
  802. // Copies bytes from ShadowBytes into shadow memory for indexes where
  803. // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
  804. // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
  805. void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
  806. IRBuilder<> &IRB, Value *ShadowBase);
  807. void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
  808. size_t Begin, size_t End, IRBuilder<> &IRB,
  809. Value *ShadowBase);
  810. void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
  811. ArrayRef<uint8_t> ShadowBytes, size_t Begin,
  812. size_t End, IRBuilder<> &IRB, Value *ShadowBase);
  813. void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
  814. Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
  815. bool Dynamic);
  816. PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
  817. Instruction *ThenTerm, Value *ValueIfFalse);
  818. };
  819. } // anonymous namespace
  820. char AddressSanitizer::ID = 0;
  821. INITIALIZE_PASS_BEGIN(
  822. AddressSanitizer, "asan",
  823. "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
  824. false)
  825. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  826. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  827. INITIALIZE_PASS_END(
  828. AddressSanitizer, "asan",
  829. "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
  830. false)
  831. FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
  832. bool Recover,
  833. bool UseAfterScope) {
  834. assert(!CompileKernel || Recover);
  835. return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
  836. }
  837. char AddressSanitizerModule::ID = 0;
  838. INITIALIZE_PASS(
  839. AddressSanitizerModule, "asan-module",
  840. "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
  841. "ModulePass",
  842. false, false)
  843. ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
  844. bool Recover,
  845. bool UseGlobalsGC) {
  846. assert(!CompileKernel || Recover);
  847. return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
  848. }
  849. static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
  850. size_t Res = countTrailingZeros(TypeSize / 8);
  851. assert(Res < kNumberOfAccessSizes);
  852. return Res;
  853. }
  854. // \brief Create a constant for Str so that we can pass it to the run-time lib.
  855. static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
  856. bool AllowMerging) {
  857. Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
  858. // We use private linkage for module-local strings. If they can be merged
  859. // with another one, we set the unnamed_addr attribute.
  860. GlobalVariable *GV =
  861. new GlobalVariable(M, StrConst->getType(), true,
  862. GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
  863. if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
  864. GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
  865. return GV;
  866. }
  867. /// \brief Create a global describing a source location.
  868. static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
  869. LocationMetadata MD) {
  870. Constant *LocData[] = {
  871. createPrivateGlobalForString(M, MD.Filename, true),
  872. ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
  873. ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
  874. };
  875. auto LocStruct = ConstantStruct::getAnon(LocData);
  876. auto GV = new GlobalVariable(M, LocStruct->getType(), true,
  877. GlobalValue::PrivateLinkage, LocStruct,
  878. kAsanGenPrefix);
  879. GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
  880. return GV;
  881. }
  882. /// \brief Check if \p G has been created by a trusted compiler pass.
  883. static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
  884. // Do not instrument asan globals.
  885. if (G->getName().startswith(kAsanGenPrefix) ||
  886. G->getName().startswith(kSanCovGenPrefix) ||
  887. G->getName().startswith(kODRGenPrefix))
  888. return true;
  889. // Do not instrument gcov counter arrays.
  890. if (G->getName() == "__llvm_gcov_ctr")
  891. return true;
  892. return false;
  893. }
  894. Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
  895. // Shadow >> scale
  896. Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
  897. if (Mapping.Offset == 0) return Shadow;
  898. // (Shadow >> scale) | offset
  899. Value *ShadowBase;
  900. if (LocalDynamicShadow)
  901. ShadowBase = LocalDynamicShadow;
  902. else
  903. ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
  904. if (Mapping.OrShadowOffset)
  905. return IRB.CreateOr(Shadow, ShadowBase);
  906. else
  907. return IRB.CreateAdd(Shadow, ShadowBase);
  908. }
  909. // Instrument memset/memmove/memcpy
  910. void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
  911. IRBuilder<> IRB(MI);
  912. if (isa<MemTransferInst>(MI)) {
  913. IRB.CreateCall(
  914. isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
  915. {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
  916. IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
  917. IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
  918. } else if (isa<MemSetInst>(MI)) {
  919. IRB.CreateCall(
  920. AsanMemset,
  921. {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
  922. IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
  923. IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
  924. }
  925. MI->eraseFromParent();
  926. }
  927. /// Check if we want (and can) handle this alloca.
  928. bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
  929. auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
  930. if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
  931. return PreviouslySeenAllocaInfo->getSecond();
  932. bool IsInteresting =
  933. (AI.getAllocatedType()->isSized() &&
  934. // alloca() may be called with 0 size, ignore it.
  935. ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
  936. // We are only interested in allocas not promotable to registers.
  937. // Promotable allocas are common under -O0.
  938. (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
  939. // inalloca allocas are not treated as static, and we don't want
  940. // dynamic alloca instrumentation for them as well.
  941. !AI.isUsedWithInAlloca() &&
  942. // swifterror allocas are register promoted by ISel
  943. !AI.isSwiftError());
  944. ProcessedAllocas[&AI] = IsInteresting;
  945. return IsInteresting;
  946. }
  947. Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
  948. bool *IsWrite,
  949. uint64_t *TypeSize,
  950. unsigned *Alignment,
  951. Value **MaybeMask) {
  952. // Skip memory accesses inserted by another instrumentation.
  953. if (I->getMetadata("nosanitize")) return nullptr;
  954. // Do not instrument the load fetching the dynamic shadow address.
  955. if (LocalDynamicShadow == I)
  956. return nullptr;
  957. Value *PtrOperand = nullptr;
  958. const DataLayout &DL = I->getModule()->getDataLayout();
  959. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  960. if (!ClInstrumentReads) return nullptr;
  961. *IsWrite = false;
  962. *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
  963. *Alignment = LI->getAlignment();
  964. PtrOperand = LI->getPointerOperand();
  965. } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  966. if (!ClInstrumentWrites) return nullptr;
  967. *IsWrite = true;
  968. *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
  969. *Alignment = SI->getAlignment();
  970. PtrOperand = SI->getPointerOperand();
  971. } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  972. if (!ClInstrumentAtomics) return nullptr;
  973. *IsWrite = true;
  974. *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
  975. *Alignment = 0;
  976. PtrOperand = RMW->getPointerOperand();
  977. } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
  978. if (!ClInstrumentAtomics) return nullptr;
  979. *IsWrite = true;
  980. *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
  981. *Alignment = 0;
  982. PtrOperand = XCHG->getPointerOperand();
  983. } else if (auto CI = dyn_cast<CallInst>(I)) {
  984. auto *F = dyn_cast<Function>(CI->getCalledValue());
  985. if (F && (F->getName().startswith("llvm.masked.load.") ||
  986. F->getName().startswith("llvm.masked.store."))) {
  987. unsigned OpOffset = 0;
  988. if (F->getName().startswith("llvm.masked.store.")) {
  989. if (!ClInstrumentWrites)
  990. return nullptr;
  991. // Masked store has an initial operand for the value.
  992. OpOffset = 1;
  993. *IsWrite = true;
  994. } else {
  995. if (!ClInstrumentReads)
  996. return nullptr;
  997. *IsWrite = false;
  998. }
  999. auto BasePtr = CI->getOperand(0 + OpOffset);
  1000. auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
  1001. *TypeSize = DL.getTypeStoreSizeInBits(Ty);
  1002. if (auto AlignmentConstant =
  1003. dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
  1004. *Alignment = (unsigned)AlignmentConstant->getZExtValue();
  1005. else
  1006. *Alignment = 1; // No alignment guarantees. We probably got Undef
  1007. if (MaybeMask)
  1008. *MaybeMask = CI->getOperand(2 + OpOffset);
  1009. PtrOperand = BasePtr;
  1010. }
  1011. }
  1012. if (PtrOperand) {
  1013. // Do not instrument acesses from different address spaces; we cannot deal
  1014. // with them.
  1015. Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
  1016. if (PtrTy->getPointerAddressSpace() != 0)
  1017. return nullptr;
  1018. // Ignore swifterror addresses.
  1019. // swifterror memory addresses are mem2reg promoted by instruction
  1020. // selection. As such they cannot have regular uses like an instrumentation
  1021. // function and it makes no sense to track them as memory.
  1022. if (PtrOperand->isSwiftError())
  1023. return nullptr;
  1024. }
  1025. // Treat memory accesses to promotable allocas as non-interesting since they
  1026. // will not cause memory violations. This greatly speeds up the instrumented
  1027. // executable at -O0.
  1028. if (ClSkipPromotableAllocas)
  1029. if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
  1030. return isInterestingAlloca(*AI) ? AI : nullptr;
  1031. return PtrOperand;
  1032. }
  1033. static bool isPointerOperand(Value *V) {
  1034. return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
  1035. }
  1036. // This is a rough heuristic; it may cause both false positives and
  1037. // false negatives. The proper implementation requires cooperation with
  1038. // the frontend.
  1039. static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
  1040. if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
  1041. if (!Cmp->isRelational()) return false;
  1042. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  1043. if (BO->getOpcode() != Instruction::Sub) return false;
  1044. } else {
  1045. return false;
  1046. }
  1047. return isPointerOperand(I->getOperand(0)) &&
  1048. isPointerOperand(I->getOperand(1));
  1049. }
  1050. bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
  1051. // If a global variable does not have dynamic initialization we don't
  1052. // have to instrument it. However, if a global does not have initializer
  1053. // at all, we assume it has dynamic initializer (in other TU).
  1054. return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
  1055. }
  1056. void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
  1057. Instruction *I) {
  1058. IRBuilder<> IRB(I);
  1059. Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
  1060. Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
  1061. for (Value *&i : Param) {
  1062. if (i->getType()->isPointerTy())
  1063. i = IRB.CreatePointerCast(i, IntptrTy);
  1064. }
  1065. IRB.CreateCall(F, Param);
  1066. }
  1067. static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
  1068. Instruction *InsertBefore, Value *Addr,
  1069. unsigned Alignment, unsigned Granularity,
  1070. uint32_t TypeSize, bool IsWrite,
  1071. Value *SizeArgument, bool UseCalls,
  1072. uint32_t Exp) {
  1073. // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
  1074. // if the data is properly aligned.
  1075. if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
  1076. TypeSize == 128) &&
  1077. (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
  1078. return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
  1079. nullptr, UseCalls, Exp);
  1080. Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
  1081. IsWrite, nullptr, UseCalls, Exp);
  1082. }
  1083. static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
  1084. const DataLayout &DL, Type *IntptrTy,
  1085. Value *Mask, Instruction *I,
  1086. Value *Addr, unsigned Alignment,
  1087. unsigned Granularity, uint32_t TypeSize,
  1088. bool IsWrite, Value *SizeArgument,
  1089. bool UseCalls, uint32_t Exp) {
  1090. auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
  1091. uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
  1092. unsigned Num = VTy->getVectorNumElements();
  1093. auto Zero = ConstantInt::get(IntptrTy, 0);
  1094. for (unsigned Idx = 0; Idx < Num; ++Idx) {
  1095. Value *InstrumentedAddress = nullptr;
  1096. Instruction *InsertBefore = I;
  1097. if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
  1098. // dyn_cast as we might get UndefValue
  1099. if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
  1100. if (Masked->isNullValue())
  1101. // Mask is constant false, so no instrumentation needed.
  1102. continue;
  1103. // If we have a true or undef value, fall through to doInstrumentAddress
  1104. // with InsertBefore == I
  1105. }
  1106. } else {
  1107. IRBuilder<> IRB(I);
  1108. Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
  1109. TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
  1110. InsertBefore = ThenTerm;
  1111. }
  1112. IRBuilder<> IRB(InsertBefore);
  1113. InstrumentedAddress =
  1114. IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
  1115. doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
  1116. Granularity, ElemTypeSize, IsWrite, SizeArgument,
  1117. UseCalls, Exp);
  1118. }
  1119. }
  1120. void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
  1121. Instruction *I, bool UseCalls,
  1122. const DataLayout &DL) {
  1123. bool IsWrite = false;
  1124. unsigned Alignment = 0;
  1125. uint64_t TypeSize = 0;
  1126. Value *MaybeMask = nullptr;
  1127. Value *Addr =
  1128. isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
  1129. assert(Addr);
  1130. // Optimization experiments.
  1131. // The experiments can be used to evaluate potential optimizations that remove
  1132. // instrumentation (assess false negatives). Instead of completely removing
  1133. // some instrumentation, you set Exp to a non-zero value (mask of optimization
  1134. // experiments that want to remove instrumentation of this instruction).
  1135. // If Exp is non-zero, this pass will emit special calls into runtime
  1136. // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
  1137. // make runtime terminate the program in a special way (with a different
  1138. // exit status). Then you run the new compiler on a buggy corpus, collect
  1139. // the special terminations (ideally, you don't see them at all -- no false
  1140. // negatives) and make the decision on the optimization.
  1141. uint32_t Exp = ClForceExperiment;
  1142. if (ClOpt && ClOptGlobals) {
  1143. // If initialization order checking is disabled, a simple access to a
  1144. // dynamically initialized global is always valid.
  1145. GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
  1146. if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
  1147. isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
  1148. NumOptimizedAccessesToGlobalVar++;
  1149. return;
  1150. }
  1151. }
  1152. if (ClOpt && ClOptStack) {
  1153. // A direct inbounds access to a stack variable is always valid.
  1154. if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
  1155. isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
  1156. NumOptimizedAccessesToStackVar++;
  1157. return;
  1158. }
  1159. }
  1160. if (IsWrite)
  1161. NumInstrumentedWrites++;
  1162. else
  1163. NumInstrumentedReads++;
  1164. unsigned Granularity = 1 << Mapping.Scale;
  1165. if (MaybeMask) {
  1166. instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
  1167. Alignment, Granularity, TypeSize, IsWrite,
  1168. nullptr, UseCalls, Exp);
  1169. } else {
  1170. doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
  1171. IsWrite, nullptr, UseCalls, Exp);
  1172. }
  1173. }
  1174. Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
  1175. Value *Addr, bool IsWrite,
  1176. size_t AccessSizeIndex,
  1177. Value *SizeArgument,
  1178. uint32_t Exp) {
  1179. IRBuilder<> IRB(InsertBefore);
  1180. Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
  1181. CallInst *Call = nullptr;
  1182. if (SizeArgument) {
  1183. if (Exp == 0)
  1184. Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
  1185. {Addr, SizeArgument});
  1186. else
  1187. Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
  1188. {Addr, SizeArgument, ExpVal});
  1189. } else {
  1190. if (Exp == 0)
  1191. Call =
  1192. IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
  1193. else
  1194. Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
  1195. {Addr, ExpVal});
  1196. }
  1197. // We don't do Call->setDoesNotReturn() because the BB already has
  1198. // UnreachableInst at the end.
  1199. // This EmptyAsm is required to avoid callback merge.
  1200. IRB.CreateCall(EmptyAsm, {});
  1201. return Call;
  1202. }
  1203. Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
  1204. Value *ShadowValue,
  1205. uint32_t TypeSize) {
  1206. size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
  1207. // Addr & (Granularity - 1)
  1208. Value *LastAccessedByte =
  1209. IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
  1210. // (Addr & (Granularity - 1)) + size - 1
  1211. if (TypeSize / 8 > 1)
  1212. LastAccessedByte = IRB.CreateAdd(
  1213. LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
  1214. // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
  1215. LastAccessedByte =
  1216. IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
  1217. // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
  1218. return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
  1219. }
  1220. void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
  1221. Instruction *InsertBefore, Value *Addr,
  1222. uint32_t TypeSize, bool IsWrite,
  1223. Value *SizeArgument, bool UseCalls,
  1224. uint32_t Exp) {
  1225. IRBuilder<> IRB(InsertBefore);
  1226. Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
  1227. size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
  1228. if (UseCalls) {
  1229. if (Exp == 0)
  1230. IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
  1231. AddrLong);
  1232. else
  1233. IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
  1234. {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
  1235. return;
  1236. }
  1237. Type *ShadowTy =
  1238. IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
  1239. Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
  1240. Value *ShadowPtr = memToShadow(AddrLong, IRB);
  1241. Value *CmpVal = Constant::getNullValue(ShadowTy);
  1242. Value *ShadowValue =
  1243. IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
  1244. Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
  1245. size_t Granularity = 1ULL << Mapping.Scale;
  1246. TerminatorInst *CrashTerm = nullptr;
  1247. if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
  1248. // We use branch weights for the slow path check, to indicate that the slow
  1249. // path is rarely taken. This seems to be the case for SPEC benchmarks.
  1250. TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
  1251. Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
  1252. assert(cast<BranchInst>(CheckTerm)->isUnconditional());
  1253. BasicBlock *NextBB = CheckTerm->getSuccessor(0);
  1254. IRB.SetInsertPoint(CheckTerm);
  1255. Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
  1256. if (Recover) {
  1257. CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
  1258. } else {
  1259. BasicBlock *CrashBlock =
  1260. BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
  1261. CrashTerm = new UnreachableInst(*C, CrashBlock);
  1262. BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
  1263. ReplaceInstWithInst(CheckTerm, NewTerm);
  1264. }
  1265. } else {
  1266. CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
  1267. }
  1268. Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
  1269. AccessSizeIndex, SizeArgument, Exp);
  1270. Crash->setDebugLoc(OrigIns->getDebugLoc());
  1271. }
  1272. // Instrument unusual size or unusual alignment.
  1273. // We can not do it with a single check, so we do 1-byte check for the first
  1274. // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
  1275. // to report the actual access size.
  1276. void AddressSanitizer::instrumentUnusualSizeOrAlignment(
  1277. Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
  1278. bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
  1279. IRBuilder<> IRB(InsertBefore);
  1280. Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
  1281. Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
  1282. if (UseCalls) {
  1283. if (Exp == 0)
  1284. IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
  1285. {AddrLong, Size});
  1286. else
  1287. IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
  1288. {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
  1289. } else {
  1290. Value *LastByte = IRB.CreateIntToPtr(
  1291. IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
  1292. Addr->getType());
  1293. instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
  1294. instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
  1295. }
  1296. }
  1297. void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
  1298. GlobalValue *ModuleName) {
  1299. // Set up the arguments to our poison/unpoison functions.
  1300. IRBuilder<> IRB(&GlobalInit.front(),
  1301. GlobalInit.front().getFirstInsertionPt());
  1302. // Add a call to poison all external globals before the given function starts.
  1303. Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
  1304. IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
  1305. // Add calls to unpoison all globals before each return instruction.
  1306. for (auto &BB : GlobalInit.getBasicBlockList())
  1307. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
  1308. CallInst::Create(AsanUnpoisonGlobals, "", RI);
  1309. }
  1310. void AddressSanitizerModule::createInitializerPoisonCalls(
  1311. Module &M, GlobalValue *ModuleName) {
  1312. GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
  1313. if (!GV)
  1314. return;
  1315. ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
  1316. if (!CA)
  1317. return;
  1318. for (Use &OP : CA->operands()) {
  1319. if (isa<ConstantAggregateZero>(OP)) continue;
  1320. ConstantStruct *CS = cast<ConstantStruct>(OP);
  1321. // Must have a function or null ptr.
  1322. if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
  1323. if (F->getName() == kAsanModuleCtorName) continue;
  1324. ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
  1325. // Don't instrument CTORs that will run before asan.module_ctor.
  1326. if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
  1327. poisonOneInitializer(*F, ModuleName);
  1328. }
  1329. }
  1330. }
  1331. bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
  1332. Type *Ty = G->getValueType();
  1333. DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
  1334. if (GlobalsMD.get(G).IsBlacklisted) return false;
  1335. if (!Ty->isSized()) return false;
  1336. if (!G->hasInitializer()) return false;
  1337. if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
  1338. // Touch only those globals that will not be defined in other modules.
  1339. // Don't handle ODR linkage types and COMDATs since other modules may be built
  1340. // without ASan.
  1341. if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
  1342. G->getLinkage() != GlobalVariable::PrivateLinkage &&
  1343. G->getLinkage() != GlobalVariable::InternalLinkage)
  1344. return false;
  1345. if (G->hasComdat()) return false;
  1346. // Two problems with thread-locals:
  1347. // - The address of the main thread's copy can't be computed at link-time.
  1348. // - Need to poison all copies, not just the main thread's one.
  1349. if (G->isThreadLocal()) return false;
  1350. // For now, just ignore this Global if the alignment is large.
  1351. if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
  1352. if (G->hasSection()) {
  1353. StringRef Section = G->getSection();
  1354. // Globals from llvm.metadata aren't emitted, do not instrument them.
  1355. if (Section == "llvm.metadata") return false;
  1356. // Do not instrument globals from special LLVM sections.
  1357. if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
  1358. // Do not instrument function pointers to initialization and termination
  1359. // routines: dynamic linker will not properly handle redzones.
  1360. if (Section.startswith(".preinit_array") ||
  1361. Section.startswith(".init_array") ||
  1362. Section.startswith(".fini_array")) {
  1363. return false;
  1364. }
  1365. // Callbacks put into the CRT initializer/terminator sections
  1366. // should not be instrumented.
  1367. // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
  1368. // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
  1369. if (Section.startswith(".CRT")) {
  1370. DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
  1371. return false;
  1372. }
  1373. if (TargetTriple.isOSBinFormatMachO()) {
  1374. StringRef ParsedSegment, ParsedSection;
  1375. unsigned TAA = 0, StubSize = 0;
  1376. bool TAAParsed;
  1377. std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
  1378. Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
  1379. assert(ErrorCode.empty() && "Invalid section specifier.");
  1380. // Ignore the globals from the __OBJC section. The ObjC runtime assumes
  1381. // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
  1382. // them.
  1383. if (ParsedSegment == "__OBJC" ||
  1384. (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
  1385. DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
  1386. return false;
  1387. }
  1388. // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
  1389. // Constant CFString instances are compiled in the following way:
  1390. // -- the string buffer is emitted into
  1391. // __TEXT,__cstring,cstring_literals
  1392. // -- the constant NSConstantString structure referencing that buffer
  1393. // is placed into __DATA,__cfstring
  1394. // Therefore there's no point in placing redzones into __DATA,__cfstring.
  1395. // Moreover, it causes the linker to crash on OS X 10.7
  1396. if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
  1397. DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
  1398. return false;
  1399. }
  1400. // The linker merges the contents of cstring_literals and removes the
  1401. // trailing zeroes.
  1402. if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
  1403. DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
  1404. return false;
  1405. }
  1406. }
  1407. }
  1408. return true;
  1409. }
  1410. // On Mach-O platforms, we emit global metadata in a separate section of the
  1411. // binary in order to allow the linker to properly dead strip. This is only
  1412. // supported on recent versions of ld64.
  1413. bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
  1414. if (!TargetTriple.isOSBinFormatMachO())
  1415. return false;
  1416. if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
  1417. return true;
  1418. if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
  1419. return true;
  1420. if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
  1421. return true;
  1422. return false;
  1423. }
  1424. StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
  1425. switch (TargetTriple.getObjectFormat()) {
  1426. case Triple::COFF: return ".ASAN$GL";
  1427. case Triple::ELF: return "asan_globals";
  1428. case Triple::MachO: return "__DATA,__asan_globals,regular";
  1429. default: break;
  1430. }
  1431. llvm_unreachable("unsupported object format");
  1432. }
  1433. void AddressSanitizerModule::initializeCallbacks(Module &M) {
  1434. IRBuilder<> IRB(*C);
  1435. // Declare our poisoning and unpoisoning functions.
  1436. AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1437. kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
  1438. AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
  1439. AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1440. kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
  1441. AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
  1442. // Declare functions that register/unregister globals.
  1443. AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1444. kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
  1445. AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
  1446. AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
  1447. M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
  1448. IntptrTy, IntptrTy));
  1449. AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
  1450. // Declare the functions that find globals in a shared object and then invoke
  1451. // the (un)register function on them.
  1452. AsanRegisterImageGlobals =
  1453. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1454. kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
  1455. AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
  1456. AsanUnregisterImageGlobals =
  1457. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1458. kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
  1459. AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
  1460. AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
  1461. M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
  1462. IntptrTy, IntptrTy, IntptrTy));
  1463. AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
  1464. AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
  1465. M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
  1466. IntptrTy, IntptrTy, IntptrTy));
  1467. AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
  1468. }
  1469. // Put the metadata and the instrumented global in the same group. This ensures
  1470. // that the metadata is discarded if the instrumented global is discarded.
  1471. void AddressSanitizerModule::SetComdatForGlobalMetadata(
  1472. GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
  1473. Module &M = *G->getParent();
  1474. Comdat *C = G->getComdat();
  1475. if (!C) {
  1476. if (!G->hasName()) {
  1477. // If G is unnamed, it must be internal. Give it an artificial name
  1478. // so we can put it in a comdat.
  1479. assert(G->hasLocalLinkage());
  1480. G->setName(Twine(kAsanGenPrefix) + "_anon_global");
  1481. }
  1482. if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
  1483. std::string Name = G->getName();
  1484. Name += InternalSuffix;
  1485. C = M.getOrInsertComdat(Name);
  1486. } else {
  1487. C = M.getOrInsertComdat(G->getName());
  1488. }
  1489. // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
  1490. if (TargetTriple.isOSBinFormatCOFF())
  1491. C->setSelectionKind(Comdat::NoDuplicates);
  1492. G->setComdat(C);
  1493. }
  1494. assert(G->hasComdat());
  1495. Metadata->setComdat(G->getComdat());
  1496. }
  1497. // Create a separate metadata global and put it in the appropriate ASan
  1498. // global registration section.
  1499. GlobalVariable *
  1500. AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
  1501. StringRef OriginalName) {
  1502. auto Linkage = TargetTriple.isOSBinFormatMachO()
  1503. ? GlobalVariable::InternalLinkage
  1504. : GlobalVariable::PrivateLinkage;
  1505. GlobalVariable *Metadata = new GlobalVariable(
  1506. M, Initializer->getType(), false, Linkage, Initializer,
  1507. Twine("__asan_global_") + GlobalValue::getRealLinkageName(OriginalName));
  1508. Metadata->setSection(getGlobalMetadataSection());
  1509. return Metadata;
  1510. }
  1511. IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
  1512. AsanDtorFunction =
  1513. Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
  1514. GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
  1515. BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
  1516. return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
  1517. }
  1518. void AddressSanitizerModule::InstrumentGlobalsCOFF(
  1519. IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
  1520. ArrayRef<Constant *> MetadataInitializers) {
  1521. assert(ExtendedGlobals.size() == MetadataInitializers.size());
  1522. auto &DL = M.getDataLayout();
  1523. for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
  1524. Constant *Initializer = MetadataInitializers[i];
  1525. GlobalVariable *G = ExtendedGlobals[i];
  1526. GlobalVariable *Metadata =
  1527. CreateMetadataGlobal(M, Initializer, G->getName());
  1528. // The MSVC linker always inserts padding when linking incrementally. We
  1529. // cope with that by aligning each struct to its size, which must be a power
  1530. // of two.
  1531. unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
  1532. assert(isPowerOf2_32(SizeOfGlobalStruct) &&
  1533. "global metadata will not be padded appropriately");
  1534. Metadata->setAlignment(SizeOfGlobalStruct);
  1535. SetComdatForGlobalMetadata(G, Metadata, "");
  1536. }
  1537. }
  1538. void AddressSanitizerModule::InstrumentGlobalsELF(
  1539. IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
  1540. ArrayRef<Constant *> MetadataInitializers,
  1541. const std::string &UniqueModuleId) {
  1542. assert(ExtendedGlobals.size() == MetadataInitializers.size());
  1543. SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
  1544. for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
  1545. GlobalVariable *G = ExtendedGlobals[i];
  1546. GlobalVariable *Metadata =
  1547. CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
  1548. MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
  1549. Metadata->setMetadata(LLVMContext::MD_associated, MD);
  1550. MetadataGlobals[i] = Metadata;
  1551. SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
  1552. }
  1553. // Update llvm.compiler.used, adding the new metadata globals. This is
  1554. // needed so that during LTO these variables stay alive.
  1555. if (!MetadataGlobals.empty())
  1556. appendToCompilerUsed(M, MetadataGlobals);
  1557. // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
  1558. // to look up the loaded image that contains it. Second, we can store in it
  1559. // whether registration has already occurred, to prevent duplicate
  1560. // registration.
  1561. //
  1562. // Common linkage ensures that there is only one global per shared library.
  1563. GlobalVariable *RegisteredFlag = new GlobalVariable(
  1564. M, IntptrTy, false, GlobalVariable::CommonLinkage,
  1565. ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
  1566. RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
  1567. // Create start and stop symbols.
  1568. GlobalVariable *StartELFMetadata = new GlobalVariable(
  1569. M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
  1570. "__start_" + getGlobalMetadataSection());
  1571. StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
  1572. GlobalVariable *StopELFMetadata = new GlobalVariable(
  1573. M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
  1574. "__stop_" + getGlobalMetadataSection());
  1575. StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
  1576. // Create a call to register the globals with the runtime.
  1577. IRB.CreateCall(AsanRegisterElfGlobals,
  1578. {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
  1579. IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
  1580. IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
  1581. // We also need to unregister globals at the end, e.g., when a shared library
  1582. // gets closed.
  1583. IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
  1584. IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
  1585. {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
  1586. IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
  1587. IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
  1588. }
  1589. void AddressSanitizerModule::InstrumentGlobalsMachO(
  1590. IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
  1591. ArrayRef<Constant *> MetadataInitializers) {
  1592. assert(ExtendedGlobals.size() == MetadataInitializers.size());
  1593. // On recent Mach-O platforms, use a structure which binds the liveness of
  1594. // the global variable to the metadata struct. Keep the list of "Liveness" GV
  1595. // created to be added to llvm.compiler.used
  1596. StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
  1597. SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
  1598. for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
  1599. Constant *Initializer = MetadataInitializers[i];
  1600. GlobalVariable *G = ExtendedGlobals[i];
  1601. GlobalVariable *Metadata =
  1602. CreateMetadataGlobal(M, Initializer, G->getName());
  1603. // On recent Mach-O platforms, we emit the global metadata in a way that
  1604. // allows the linker to properly strip dead globals.
  1605. auto LivenessBinder =
  1606. ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
  1607. ConstantExpr::getPointerCast(Metadata, IntptrTy));
  1608. GlobalVariable *Liveness = new GlobalVariable(
  1609. M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
  1610. Twine("__asan_binder_") + G->getName());
  1611. Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
  1612. LivenessGlobals[i] = Liveness;
  1613. }
  1614. // Update llvm.compiler.used, adding the new liveness globals. This is
  1615. // needed so that during LTO these variables stay alive. The alternative
  1616. // would be to have the linker handling the LTO symbols, but libLTO
  1617. // current API does not expose access to the section for each symbol.
  1618. if (!LivenessGlobals.empty())
  1619. appendToCompilerUsed(M, LivenessGlobals);
  1620. // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
  1621. // to look up the loaded image that contains it. Second, we can store in it
  1622. // whether registration has already occurred, to prevent duplicate
  1623. // registration.
  1624. //
  1625. // common linkage ensures that there is only one global per shared library.
  1626. GlobalVariable *RegisteredFlag = new GlobalVariable(
  1627. M, IntptrTy, false, GlobalVariable::CommonLinkage,
  1628. ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
  1629. RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
  1630. IRB.CreateCall(AsanRegisterImageGlobals,
  1631. {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
  1632. // We also need to unregister globals at the end, e.g., when a shared library
  1633. // gets closed.
  1634. IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
  1635. IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
  1636. {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
  1637. }
  1638. void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
  1639. IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
  1640. ArrayRef<Constant *> MetadataInitializers) {
  1641. assert(ExtendedGlobals.size() == MetadataInitializers.size());
  1642. unsigned N = ExtendedGlobals.size();
  1643. assert(N > 0);
  1644. // On platforms that don't have a custom metadata section, we emit an array
  1645. // of global metadata structures.
  1646. ArrayType *ArrayOfGlobalStructTy =
  1647. ArrayType::get(MetadataInitializers[0]->getType(), N);
  1648. auto AllGlobals = new GlobalVariable(
  1649. M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
  1650. ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
  1651. IRB.CreateCall(AsanRegisterGlobals,
  1652. {IRB.CreatePointerCast(AllGlobals, IntptrTy),
  1653. ConstantInt::get(IntptrTy, N)});
  1654. // We also need to unregister globals at the end, e.g., when a shared library
  1655. // gets closed.
  1656. IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
  1657. IRB_Dtor.CreateCall(AsanUnregisterGlobals,
  1658. {IRB.CreatePointerCast(AllGlobals, IntptrTy),
  1659. ConstantInt::get(IntptrTy, N)});
  1660. }
  1661. // This function replaces all global variables with new variables that have
  1662. // trailing redzones. It also creates a function that poisons
  1663. // redzones and inserts this function into llvm.global_ctors.
  1664. // Sets *CtorComdat to true if the global registration code emitted into the
  1665. // asan constructor is comdat-compatible.
  1666. bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
  1667. *CtorComdat = false;
  1668. GlobalsMD.init(M);
  1669. SmallVector<GlobalVariable *, 16> GlobalsToChange;
  1670. for (auto &G : M.globals()) {
  1671. if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
  1672. }
  1673. size_t n = GlobalsToChange.size();
  1674. if (n == 0) {
  1675. *CtorComdat = true;
  1676. return false;
  1677. }
  1678. auto &DL = M.getDataLayout();
  1679. // A global is described by a structure
  1680. // size_t beg;
  1681. // size_t size;
  1682. // size_t size_with_redzone;
  1683. // const char *name;
  1684. // const char *module_name;
  1685. // size_t has_dynamic_init;
  1686. // void *source_location;
  1687. // size_t odr_indicator;
  1688. // We initialize an array of such structures and pass it to a run-time call.
  1689. StructType *GlobalStructTy =
  1690. StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
  1691. IntptrTy, IntptrTy, IntptrTy);
  1692. SmallVector<GlobalVariable *, 16> NewGlobals(n);
  1693. SmallVector<Constant *, 16> Initializers(n);
  1694. bool HasDynamicallyInitializedGlobals = false;
  1695. // We shouldn't merge same module names, as this string serves as unique
  1696. // module ID in runtime.
  1697. GlobalVariable *ModuleName = createPrivateGlobalForString(
  1698. M, M.getModuleIdentifier(), /*AllowMerging*/ false);
  1699. for (size_t i = 0; i < n; i++) {
  1700. static const uint64_t kMaxGlobalRedzone = 1 << 18;
  1701. GlobalVariable *G = GlobalsToChange[i];
  1702. auto MD = GlobalsMD.get(G);
  1703. StringRef NameForGlobal = G->getName();
  1704. // Create string holding the global name (use global name from metadata
  1705. // if it's available, otherwise just write the name of global variable).
  1706. GlobalVariable *Name = createPrivateGlobalForString(
  1707. M, MD.Name.empty() ? NameForGlobal : MD.Name,
  1708. /*AllowMerging*/ true);
  1709. Type *Ty = G->getValueType();
  1710. uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
  1711. uint64_t MinRZ = MinRedzoneSizeForGlobal();
  1712. // MinRZ <= RZ <= kMaxGlobalRedzone
  1713. // and trying to make RZ to be ~ 1/4 of SizeInBytes.
  1714. uint64_t RZ = std::max(
  1715. MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
  1716. uint64_t RightRedzoneSize = RZ;
  1717. // Round up to MinRZ
  1718. if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
  1719. assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
  1720. Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
  1721. StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
  1722. Constant *NewInitializer = ConstantStruct::get(
  1723. NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
  1724. // Create a new global variable with enough space for a redzone.
  1725. GlobalValue::LinkageTypes Linkage = G->getLinkage();
  1726. if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
  1727. Linkage = GlobalValue::InternalLinkage;
  1728. GlobalVariable *NewGlobal =
  1729. new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
  1730. "", G, G->getThreadLocalMode());
  1731. NewGlobal->copyAttributesFrom(G);
  1732. NewGlobal->setAlignment(MinRZ);
  1733. // Move null-terminated C strings to "__asan_cstring" section on Darwin.
  1734. if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
  1735. G->isConstant()) {
  1736. auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
  1737. if (Seq && Seq->isCString())
  1738. NewGlobal->setSection("__TEXT,__asan_cstring,regular");
  1739. }
  1740. // Transfer the debug info. The payload starts at offset zero so we can
  1741. // copy the debug info over as is.
  1742. SmallVector<DIGlobalVariableExpression *, 1> GVs;
  1743. G->getDebugInfo(GVs);
  1744. for (auto *GV : GVs)
  1745. NewGlobal->addDebugInfo(GV);
  1746. Value *Indices2[2];
  1747. Indices2[0] = IRB.getInt32(0);
  1748. Indices2[1] = IRB.getInt32(0);
  1749. G->replaceAllUsesWith(
  1750. ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
  1751. NewGlobal->takeName(G);
  1752. G->eraseFromParent();
  1753. NewGlobals[i] = NewGlobal;
  1754. Constant *SourceLoc;
  1755. if (!MD.SourceLoc.empty()) {
  1756. auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
  1757. SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
  1758. } else {
  1759. SourceLoc = ConstantInt::get(IntptrTy, 0);
  1760. }
  1761. Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
  1762. GlobalValue *InstrumentedGlobal = NewGlobal;
  1763. bool CanUsePrivateAliases =
  1764. TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
  1765. TargetTriple.isOSBinFormatWasm();
  1766. if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
  1767. // Create local alias for NewGlobal to avoid crash on ODR between
  1768. // instrumented and non-instrumented libraries.
  1769. auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
  1770. NameForGlobal + M.getName(), NewGlobal);
  1771. // With local aliases, we need to provide another externally visible
  1772. // symbol __odr_asan_XXX to detect ODR violation.
  1773. auto *ODRIndicatorSym =
  1774. new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
  1775. Constant::getNullValue(IRB.getInt8Ty()),
  1776. kODRGenPrefix + NameForGlobal, nullptr,
  1777. NewGlobal->getThreadLocalMode());
  1778. // Set meaningful attributes for indicator symbol.
  1779. ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
  1780. ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
  1781. ODRIndicatorSym->setAlignment(1);
  1782. ODRIndicator = ODRIndicatorSym;
  1783. InstrumentedGlobal = GA;
  1784. }
  1785. Constant *Initializer = ConstantStruct::get(
  1786. GlobalStructTy,
  1787. ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
  1788. ConstantInt::get(IntptrTy, SizeInBytes),
  1789. ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
  1790. ConstantExpr::getPointerCast(Name, IntptrTy),
  1791. ConstantExpr::getPointerCast(ModuleName, IntptrTy),
  1792. ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
  1793. ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
  1794. if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
  1795. DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
  1796. Initializers[i] = Initializer;
  1797. }
  1798. std::string ELFUniqueModuleId =
  1799. (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
  1800. : "";
  1801. if (!ELFUniqueModuleId.empty()) {
  1802. InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
  1803. *CtorComdat = true;
  1804. } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
  1805. InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
  1806. } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
  1807. InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
  1808. } else {
  1809. InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
  1810. }
  1811. // Create calls for poisoning before initializers run and unpoisoning after.
  1812. if (HasDynamicallyInitializedGlobals)
  1813. createInitializerPoisonCalls(M, ModuleName);
  1814. DEBUG(dbgs() << M);
  1815. return true;
  1816. }
  1817. bool AddressSanitizerModule::runOnModule(Module &M) {
  1818. C = &(M.getContext());
  1819. int LongSize = M.getDataLayout().getPointerSizeInBits();
  1820. IntptrTy = Type::getIntNTy(*C, LongSize);
  1821. TargetTriple = Triple(M.getTargetTriple());
  1822. Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
  1823. initializeCallbacks(M);
  1824. if (CompileKernel)
  1825. return false;
  1826. // Create a module constructor. A destructor is created lazily because not all
  1827. // platforms, and not all modules need it.
  1828. std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
  1829. M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
  1830. /*InitArgs=*/{}, kAsanVersionCheckName);
  1831. bool CtorComdat = true;
  1832. bool Changed = false;
  1833. // TODO(glider): temporarily disabled globals instrumentation for KASan.
  1834. if (ClGlobals) {
  1835. IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
  1836. Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
  1837. }
  1838. // Put the constructor and destructor in comdat if both
  1839. // (1) global instrumentation is not TU-specific
  1840. // (2) target is ELF.
  1841. if (ClWithComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
  1842. AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
  1843. appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
  1844. AsanCtorFunction);
  1845. if (AsanDtorFunction) {
  1846. AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
  1847. appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
  1848. AsanDtorFunction);
  1849. }
  1850. } else {
  1851. appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
  1852. if (AsanDtorFunction)
  1853. appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
  1854. }
  1855. return Changed;
  1856. }
  1857. void AddressSanitizer::initializeCallbacks(Module &M) {
  1858. IRBuilder<> IRB(*C);
  1859. // Create __asan_report* callbacks.
  1860. // IsWrite, TypeSize and Exp are encoded in the function name.
  1861. for (int Exp = 0; Exp < 2; Exp++) {
  1862. for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
  1863. const std::string TypeStr = AccessIsWrite ? "store" : "load";
  1864. const std::string ExpStr = Exp ? "exp_" : "";
  1865. const std::string SuffixStr = CompileKernel ? "N" : "_n";
  1866. const std::string EndingStr = Recover ? "_noabort" : "";
  1867. SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
  1868. SmallVector<Type *, 2> Args1{1, IntptrTy};
  1869. if (Exp) {
  1870. Type *ExpType = Type::getInt32Ty(*C);
  1871. Args2.push_back(ExpType);
  1872. Args1.push_back(ExpType);
  1873. }
  1874. AsanErrorCallbackSized[AccessIsWrite][Exp] =
  1875. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1876. kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
  1877. EndingStr,
  1878. FunctionType::get(IRB.getVoidTy(), Args2, false)));
  1879. AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
  1880. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1881. ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
  1882. FunctionType::get(IRB.getVoidTy(), Args2, false)));
  1883. for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
  1884. AccessSizeIndex++) {
  1885. const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
  1886. AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
  1887. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1888. kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
  1889. FunctionType::get(IRB.getVoidTy(), Args1, false)));
  1890. AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
  1891. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1892. ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
  1893. FunctionType::get(IRB.getVoidTy(), Args1, false)));
  1894. }
  1895. }
  1896. }
  1897. const std::string MemIntrinCallbackPrefix =
  1898. CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
  1899. AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1900. MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
  1901. IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
  1902. AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1903. MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
  1904. IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
  1905. AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1906. MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
  1907. IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
  1908. AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
  1909. M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
  1910. AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1911. kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
  1912. AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  1913. kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
  1914. // We insert an empty inline asm after __asan_report* to avoid callback merge.
  1915. EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
  1916. StringRef(""), StringRef(""),
  1917. /*hasSideEffects=*/true);
  1918. }
  1919. // virtual
  1920. bool AddressSanitizer::doInitialization(Module &M) {
  1921. // Initialize the private fields. No one has accessed them before.
  1922. GlobalsMD.init(M);
  1923. C = &(M.getContext());
  1924. LongSize = M.getDataLayout().getPointerSizeInBits();
  1925. IntptrTy = Type::getIntNTy(*C, LongSize);
  1926. TargetTriple = Triple(M.getTargetTriple());
  1927. Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
  1928. return true;
  1929. }
  1930. bool AddressSanitizer::doFinalization(Module &M) {
  1931. GlobalsMD.reset();
  1932. return false;
  1933. }
  1934. bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
  1935. // For each NSObject descendant having a +load method, this method is invoked
  1936. // by the ObjC runtime before any of the static constructors is called.
  1937. // Therefore we need to instrument such methods with a call to __asan_init
  1938. // at the beginning in order to initialize our runtime before any access to
  1939. // the shadow memory.
  1940. // We cannot just ignore these methods, because they may call other
  1941. // instrumented functions.
  1942. if (F.getName().find(" load]") != std::string::npos) {
  1943. Function *AsanInitFunction =
  1944. declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
  1945. IRBuilder<> IRB(&F.front(), F.front().begin());
  1946. IRB.CreateCall(AsanInitFunction, {});
  1947. return true;
  1948. }
  1949. return false;
  1950. }
  1951. void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
  1952. // Generate code only when dynamic addressing is needed.
  1953. if (Mapping.Offset != kDynamicShadowSentinel)
  1954. return;
  1955. IRBuilder<> IRB(&F.front().front());
  1956. Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
  1957. kAsanShadowMemoryDynamicAddress, IntptrTy);
  1958. LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
  1959. }
  1960. void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
  1961. // Find the one possible call to llvm.localescape and pre-mark allocas passed
  1962. // to it as uninteresting. This assumes we haven't started processing allocas
  1963. // yet. This check is done up front because iterating the use list in
  1964. // isInterestingAlloca would be algorithmically slower.
  1965. assert(ProcessedAllocas.empty() && "must process localescape before allocas");
  1966. // Try to get the declaration of llvm.localescape. If it's not in the module,
  1967. // we can exit early.
  1968. if (!F.getParent()->getFunction("llvm.localescape")) return;
  1969. // Look for a call to llvm.localescape call in the entry block. It can't be in
  1970. // any other block.
  1971. for (Instruction &I : F.getEntryBlock()) {
  1972. IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
  1973. if (II && II->getIntrinsicID() == Intrinsic::localescape) {
  1974. // We found a call. Mark all the allocas passed in as uninteresting.
  1975. for (Value *Arg : II->arg_operands()) {
  1976. AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
  1977. assert(AI && AI->isStaticAlloca() &&
  1978. "non-static alloca arg to localescape");
  1979. ProcessedAllocas[AI] = false;
  1980. }
  1981. break;
  1982. }
  1983. }
  1984. }
  1985. bool AddressSanitizer::runOnFunction(Function &F) {
  1986. if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
  1987. if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
  1988. if (F.getName().startswith("__asan_")) return false;
  1989. bool FunctionModified = false;
  1990. // If needed, insert __asan_init before checking for SanitizeAddress attr.
  1991. // This function needs to be called even if the function body is not
  1992. // instrumented.
  1993. if (maybeInsertAsanInitAtFunctionEntry(F))
  1994. FunctionModified = true;
  1995. // Leave if the function doesn't need instrumentation.
  1996. if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
  1997. DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
  1998. initializeCallbacks(*F.getParent());
  1999. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  2000. FunctionStateRAII CleanupObj(this);
  2001. maybeInsertDynamicShadowAtFunctionEntry(F);
  2002. // We can't instrument allocas used with llvm.localescape. Only static allocas
  2003. // can be passed to that intrinsic.
  2004. markEscapedLocalAllocas(F);
  2005. // We want to instrument every address only once per basic block (unless there
  2006. // are calls between uses).
  2007. SmallSet<Value *, 16> TempsToInstrument;
  2008. SmallVector<Instruction *, 16> ToInstrument;
  2009. SmallVector<Instruction *, 8> NoReturnCalls;
  2010. SmallVector<BasicBlock *, 16> AllBlocks;
  2011. SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
  2012. int NumAllocas = 0;
  2013. bool IsWrite;
  2014. unsigned Alignment;
  2015. uint64_t TypeSize;
  2016. const TargetLibraryInfo *TLI =
  2017. &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  2018. // Fill the set of memory operations to instrument.
  2019. for (auto &BB : F) {
  2020. AllBlocks.push_back(&BB);
  2021. TempsToInstrument.clear();
  2022. int NumInsnsPerBB = 0;
  2023. for (auto &Inst : BB) {
  2024. if (LooksLikeCodeInBug11395(&Inst)) return false;
  2025. Value *MaybeMask = nullptr;
  2026. if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
  2027. &Alignment, &MaybeMask)) {
  2028. if (ClOpt && ClOptSameTemp) {
  2029. // If we have a mask, skip instrumentation if we've already
  2030. // instrumented the full object. But don't add to TempsToInstrument
  2031. // because we might get another load/store with a different mask.
  2032. if (MaybeMask) {
  2033. if (TempsToInstrument.count(Addr))
  2034. continue; // We've seen this (whole) temp in the current BB.
  2035. } else {
  2036. if (!TempsToInstrument.insert(Addr).second)
  2037. continue; // We've seen this temp in the current BB.
  2038. }
  2039. }
  2040. } else if (ClInvalidPointerPairs &&
  2041. isInterestingPointerComparisonOrSubtraction(&Inst)) {
  2042. PointerComparisonsOrSubtracts.push_back(&Inst);
  2043. continue;
  2044. } else if (isa<MemIntrinsic>(Inst)) {
  2045. // ok, take it.
  2046. } else {
  2047. if (isa<AllocaInst>(Inst)) NumAllocas++;
  2048. CallSite CS(&Inst);
  2049. if (CS) {
  2050. // A call inside BB.
  2051. TempsToInstrument.clear();
  2052. if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
  2053. }
  2054. if (CallInst *CI = dyn_cast<CallInst>(&Inst))
  2055. maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
  2056. continue;
  2057. }
  2058. ToInstrument.push_back(&Inst);
  2059. NumInsnsPerBB++;
  2060. if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
  2061. }
  2062. }
  2063. bool UseCalls =
  2064. CompileKernel ||
  2065. (ClInstrumentationWithCallsThreshold >= 0 &&
  2066. ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
  2067. const DataLayout &DL = F.getParent()->getDataLayout();
  2068. ObjectSizeOpts ObjSizeOpts;
  2069. ObjSizeOpts.RoundToAlign = true;
  2070. ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
  2071. // Instrument.
  2072. int NumInstrumented = 0;
  2073. for (auto Inst : ToInstrument) {
  2074. if (ClDebugMin < 0 || ClDebugMax < 0 ||
  2075. (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
  2076. if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
  2077. instrumentMop(ObjSizeVis, Inst, UseCalls,
  2078. F.getParent()->getDataLayout());
  2079. else
  2080. instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
  2081. }
  2082. NumInstrumented++;
  2083. }
  2084. FunctionStackPoisoner FSP(F, *this);
  2085. bool ChangedStack = FSP.runOnFunction();
  2086. // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
  2087. // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
  2088. for (auto CI : NoReturnCalls) {
  2089. IRBuilder<> IRB(CI);
  2090. IRB.CreateCall(AsanHandleNoReturnFunc, {});
  2091. }
  2092. for (auto Inst : PointerComparisonsOrSubtracts) {
  2093. instrumentPointerComparisonOrSubtraction(Inst);
  2094. NumInstrumented++;
  2095. }
  2096. if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
  2097. FunctionModified = true;
  2098. DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
  2099. << F << "\n");
  2100. return FunctionModified;
  2101. }
  2102. // Workaround for bug 11395: we don't want to instrument stack in functions
  2103. // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
  2104. // FIXME: remove once the bug 11395 is fixed.
  2105. bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
  2106. if (LongSize != 32) return false;
  2107. CallInst *CI = dyn_cast<CallInst>(I);
  2108. if (!CI || !CI->isInlineAsm()) return false;
  2109. if (CI->getNumArgOperands() <= 5) return false;
  2110. // We have inline assembly with quite a few arguments.
  2111. return true;
  2112. }
  2113. void FunctionStackPoisoner::initializeCallbacks(Module &M) {
  2114. IRBuilder<> IRB(*C);
  2115. for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
  2116. std::string Suffix = itostr(i);
  2117. AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
  2118. M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
  2119. IntptrTy));
  2120. AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
  2121. M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
  2122. IRB.getVoidTy(), IntptrTy, IntptrTy));
  2123. }
  2124. if (ASan.UseAfterScope) {
  2125. AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
  2126. M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
  2127. IntptrTy, IntptrTy));
  2128. AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
  2129. M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
  2130. IntptrTy, IntptrTy));
  2131. }
  2132. for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
  2133. std::ostringstream Name;
  2134. Name << kAsanSetShadowPrefix;
  2135. Name << std::setw(2) << std::setfill('0') << std::hex << Val;
  2136. AsanSetShadowFunc[Val] =
  2137. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  2138. Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
  2139. }
  2140. AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  2141. kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
  2142. AsanAllocasUnpoisonFunc =
  2143. checkSanitizerInterfaceFunction(M.getOrInsertFunction(
  2144. kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
  2145. }
  2146. void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
  2147. ArrayRef<uint8_t> ShadowBytes,
  2148. size_t Begin, size_t End,
  2149. IRBuilder<> &IRB,
  2150. Value *ShadowBase) {
  2151. if (Begin >= End)
  2152. return;
  2153. const size_t LargestStoreSizeInBytes =
  2154. std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
  2155. const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
  2156. // Poison given range in shadow using larges store size with out leading and
  2157. // trailing zeros in ShadowMask. Zeros never change, so they need neither
  2158. // poisoning nor up-poisoning. Still we don't mind if some of them get into a
  2159. // middle of a store.
  2160. for (size_t i = Begin; i < End;) {
  2161. if (!ShadowMask[i]) {
  2162. assert(!ShadowBytes[i]);
  2163. ++i;
  2164. continue;
  2165. }
  2166. size_t StoreSizeInBytes = LargestStoreSizeInBytes;
  2167. // Fit store size into the range.
  2168. while (StoreSizeInBytes > End - i)
  2169. StoreSizeInBytes /= 2;
  2170. // Minimize store size by trimming trailing zeros.
  2171. for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
  2172. while (j <= StoreSizeInBytes / 2)
  2173. StoreSizeInBytes /= 2;
  2174. }
  2175. uint64_t Val = 0;
  2176. for (size_t j = 0; j < StoreSizeInBytes; j++) {
  2177. if (IsLittleEndian)
  2178. Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
  2179. else
  2180. Val = (Val << 8) | ShadowBytes[i + j];
  2181. }
  2182. Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
  2183. Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
  2184. IRB.CreateAlignedStore(
  2185. Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
  2186. i += StoreSizeInBytes;
  2187. }
  2188. }
  2189. void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
  2190. ArrayRef<uint8_t> ShadowBytes,
  2191. IRBuilder<> &IRB, Value *ShadowBase) {
  2192. copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
  2193. }
  2194. void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
  2195. ArrayRef<uint8_t> ShadowBytes,
  2196. size_t Begin, size_t End,
  2197. IRBuilder<> &IRB, Value *ShadowBase) {
  2198. assert(ShadowMask.size() == ShadowBytes.size());
  2199. size_t Done = Begin;
  2200. for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
  2201. if (!ShadowMask[i]) {
  2202. assert(!ShadowBytes[i]);
  2203. continue;
  2204. }
  2205. uint8_t Val = ShadowBytes[i];
  2206. if (!AsanSetShadowFunc[Val])
  2207. continue;
  2208. // Skip same values.
  2209. for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
  2210. }
  2211. if (j - i >= ClMaxInlinePoisoningSize) {
  2212. copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
  2213. IRB.CreateCall(AsanSetShadowFunc[Val],
  2214. {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
  2215. ConstantInt::get(IntptrTy, j - i)});
  2216. Done = j;
  2217. }
  2218. }
  2219. copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
  2220. }
  2221. // Fake stack allocator (asan_fake_stack.h) has 11 size classes
  2222. // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
  2223. static int StackMallocSizeClass(uint64_t LocalStackSize) {
  2224. assert(LocalStackSize <= kMaxStackMallocSize);
  2225. uint64_t MaxSize = kMinStackMallocSize;
  2226. for (int i = 0;; i++, MaxSize *= 2)
  2227. if (LocalStackSize <= MaxSize) return i;
  2228. llvm_unreachable("impossible LocalStackSize");
  2229. }
  2230. PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
  2231. Value *ValueIfTrue,
  2232. Instruction *ThenTerm,
  2233. Value *ValueIfFalse) {
  2234. PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
  2235. BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
  2236. PHI->addIncoming(ValueIfFalse, CondBlock);
  2237. BasicBlock *ThenBlock = ThenTerm->getParent();
  2238. PHI->addIncoming(ValueIfTrue, ThenBlock);
  2239. return PHI;
  2240. }
  2241. Value *FunctionStackPoisoner::createAllocaForLayout(
  2242. IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
  2243. AllocaInst *Alloca;
  2244. if (Dynamic) {
  2245. Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
  2246. ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
  2247. "MyAlloca");
  2248. } else {
  2249. Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
  2250. nullptr, "MyAlloca");
  2251. assert(Alloca->isStaticAlloca());
  2252. }
  2253. assert((ClRealignStack & (ClRealignStack - 1)) == 0);
  2254. size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
  2255. Alloca->setAlignment(FrameAlignment);
  2256. return IRB.CreatePointerCast(Alloca, IntptrTy);
  2257. }
  2258. void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
  2259. BasicBlock &FirstBB = *F.begin();
  2260. IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
  2261. DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
  2262. IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
  2263. DynamicAllocaLayout->setAlignment(32);
  2264. }
  2265. void FunctionStackPoisoner::processDynamicAllocas() {
  2266. if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
  2267. assert(DynamicAllocaPoisonCallVec.empty());
  2268. return;
  2269. }
  2270. // Insert poison calls for lifetime intrinsics for dynamic allocas.
  2271. for (const auto &APC : DynamicAllocaPoisonCallVec) {
  2272. assert(APC.InsBefore);
  2273. assert(APC.AI);
  2274. assert(ASan.isInterestingAlloca(*APC.AI));
  2275. assert(!APC.AI->isStaticAlloca());
  2276. IRBuilder<> IRB(APC.InsBefore);
  2277. poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
  2278. // Dynamic allocas will be unpoisoned unconditionally below in
  2279. // unpoisonDynamicAllocas.
  2280. // Flag that we need unpoison static allocas.
  2281. }
  2282. // Handle dynamic allocas.
  2283. createDynamicAllocasInitStorage();
  2284. for (auto &AI : DynamicAllocaVec)
  2285. handleDynamicAllocaCall(AI);
  2286. unpoisonDynamicAllocas();
  2287. }
  2288. void FunctionStackPoisoner::processStaticAllocas() {
  2289. if (AllocaVec.empty()) {
  2290. assert(StaticAllocaPoisonCallVec.empty());
  2291. return;
  2292. }
  2293. int StackMallocIdx = -1;
  2294. DebugLoc EntryDebugLocation;
  2295. if (auto SP = F.getSubprogram())
  2296. EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
  2297. Instruction *InsBefore = AllocaVec[0];
  2298. IRBuilder<> IRB(InsBefore);
  2299. IRB.SetCurrentDebugLocation(EntryDebugLocation);
  2300. // Make sure non-instrumented allocas stay in the entry block. Otherwise,
  2301. // debug info is broken, because only entry-block allocas are treated as
  2302. // regular stack slots.
  2303. auto InsBeforeB = InsBefore->getParent();
  2304. assert(InsBeforeB == &F.getEntryBlock());
  2305. for (auto *AI : StaticAllocasToMoveUp)
  2306. if (AI->getParent() == InsBeforeB)
  2307. AI->moveBefore(InsBefore);
  2308. // If we have a call to llvm.localescape, keep it in the entry block.
  2309. if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
  2310. SmallVector<ASanStackVariableDescription, 16> SVD;
  2311. SVD.reserve(AllocaVec.size());
  2312. for (AllocaInst *AI : AllocaVec) {
  2313. ASanStackVariableDescription D = {AI->getName().data(),
  2314. ASan.getAllocaSizeInBytes(*AI),
  2315. 0,
  2316. AI->getAlignment(),
  2317. AI,
  2318. 0,
  2319. 0};
  2320. SVD.push_back(D);
  2321. }
  2322. // Minimal header size (left redzone) is 4 pointers,
  2323. // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
  2324. size_t MinHeaderSize = ASan.LongSize / 2;
  2325. const ASanStackFrameLayout &L =
  2326. ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
  2327. // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
  2328. DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
  2329. for (auto &Desc : SVD)
  2330. AllocaToSVDMap[Desc.AI] = &Desc;
  2331. // Update SVD with information from lifetime intrinsics.
  2332. for (const auto &APC : StaticAllocaPoisonCallVec) {
  2333. assert(APC.InsBefore);
  2334. assert(APC.AI);
  2335. assert(ASan.isInterestingAlloca(*APC.AI));
  2336. assert(APC.AI->isStaticAlloca());
  2337. ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
  2338. Desc.LifetimeSize = Desc.Size;
  2339. if (const DILocation *FnLoc = EntryDebugLocation.get()) {
  2340. if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
  2341. if (LifetimeLoc->getFile() == FnLoc->getFile())
  2342. if (unsigned Line = LifetimeLoc->getLine())
  2343. Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
  2344. }
  2345. }
  2346. }
  2347. auto DescriptionString = ComputeASanStackFrameDescription(SVD);
  2348. DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
  2349. uint64_t LocalStackSize = L.FrameSize;
  2350. bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
  2351. LocalStackSize <= kMaxStackMallocSize;
  2352. bool DoDynamicAlloca = ClDynamicAllocaStack;
  2353. // Don't do dynamic alloca or stack malloc if:
  2354. // 1) There is inline asm: too often it makes assumptions on which registers
  2355. // are available.
  2356. // 2) There is a returns_twice call (typically setjmp), which is
  2357. // optimization-hostile, and doesn't play well with introduced indirect
  2358. // register-relative calculation of local variable addresses.
  2359. DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
  2360. DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
  2361. Value *StaticAlloca =
  2362. DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
  2363. Value *FakeStack;
  2364. Value *LocalStackBase;
  2365. if (DoStackMalloc) {
  2366. // void *FakeStack = __asan_option_detect_stack_use_after_return
  2367. // ? __asan_stack_malloc_N(LocalStackSize)
  2368. // : nullptr;
  2369. // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
  2370. Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
  2371. kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
  2372. Value *UseAfterReturnIsEnabled =
  2373. IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
  2374. Constant::getNullValue(IRB.getInt32Ty()));
  2375. Instruction *Term =
  2376. SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
  2377. IRBuilder<> IRBIf(Term);
  2378. IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
  2379. StackMallocIdx = StackMallocSizeClass(LocalStackSize);
  2380. assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
  2381. Value *FakeStackValue =
  2382. IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
  2383. ConstantInt::get(IntptrTy, LocalStackSize));
  2384. IRB.SetInsertPoint(InsBefore);
  2385. IRB.SetCurrentDebugLocation(EntryDebugLocation);
  2386. FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
  2387. ConstantInt::get(IntptrTy, 0));
  2388. Value *NoFakeStack =
  2389. IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
  2390. Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
  2391. IRBIf.SetInsertPoint(Term);
  2392. IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
  2393. Value *AllocaValue =
  2394. DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
  2395. IRB.SetInsertPoint(InsBefore);
  2396. IRB.SetCurrentDebugLocation(EntryDebugLocation);
  2397. LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
  2398. } else {
  2399. // void *FakeStack = nullptr;
  2400. // void *LocalStackBase = alloca(LocalStackSize);
  2401. FakeStack = ConstantInt::get(IntptrTy, 0);
  2402. LocalStackBase =
  2403. DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
  2404. }
  2405. // Replace Alloca instructions with base+offset.
  2406. for (const auto &Desc : SVD) {
  2407. AllocaInst *AI = Desc.AI;
  2408. Value *NewAllocaPtr = IRB.CreateIntToPtr(
  2409. IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
  2410. AI->getType());
  2411. replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
  2412. AI->replaceAllUsesWith(NewAllocaPtr);
  2413. }
  2414. // The left-most redzone has enough space for at least 4 pointers.
  2415. // Write the Magic value to redzone[0].
  2416. Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
  2417. IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
  2418. BasePlus0);
  2419. // Write the frame description constant to redzone[1].
  2420. Value *BasePlus1 = IRB.CreateIntToPtr(
  2421. IRB.CreateAdd(LocalStackBase,
  2422. ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
  2423. IntptrPtrTy);
  2424. GlobalVariable *StackDescriptionGlobal =
  2425. createPrivateGlobalForString(*F.getParent(), DescriptionString,
  2426. /*AllowMerging*/ true);
  2427. Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
  2428. IRB.CreateStore(Description, BasePlus1);
  2429. // Write the PC to redzone[2].
  2430. Value *BasePlus2 = IRB.CreateIntToPtr(
  2431. IRB.CreateAdd(LocalStackBase,
  2432. ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
  2433. IntptrPtrTy);
  2434. IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
  2435. const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
  2436. // Poison the stack red zones at the entry.
  2437. Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
  2438. // As mask we must use most poisoned case: red zones and after scope.
  2439. // As bytes we can use either the same or just red zones only.
  2440. copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
  2441. if (!StaticAllocaPoisonCallVec.empty()) {
  2442. const auto &ShadowInScope = GetShadowBytes(SVD, L);
  2443. // Poison static allocas near lifetime intrinsics.
  2444. for (const auto &APC : StaticAllocaPoisonCallVec) {
  2445. const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
  2446. assert(Desc.Offset % L.Granularity == 0);
  2447. size_t Begin = Desc.Offset / L.Granularity;
  2448. size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
  2449. IRBuilder<> IRB(APC.InsBefore);
  2450. copyToShadow(ShadowAfterScope,
  2451. APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
  2452. IRB, ShadowBase);
  2453. }
  2454. }
  2455. SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
  2456. SmallVector<uint8_t, 64> ShadowAfterReturn;
  2457. // (Un)poison the stack before all ret instructions.
  2458. for (auto Ret : RetVec) {
  2459. IRBuilder<> IRBRet(Ret);
  2460. // Mark the current frame as retired.
  2461. IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
  2462. BasePlus0);
  2463. if (DoStackMalloc) {
  2464. assert(StackMallocIdx >= 0);
  2465. // if FakeStack != 0 // LocalStackBase == FakeStack
  2466. // // In use-after-return mode, poison the whole stack frame.
  2467. // if StackMallocIdx <= 4
  2468. // // For small sizes inline the whole thing:
  2469. // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
  2470. // **SavedFlagPtr(FakeStack) = 0
  2471. // else
  2472. // __asan_stack_free_N(FakeStack, LocalStackSize)
  2473. // else
  2474. // <This is not a fake stack; unpoison the redzones>
  2475. Value *Cmp =
  2476. IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
  2477. TerminatorInst *ThenTerm, *ElseTerm;
  2478. SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
  2479. IRBuilder<> IRBPoison(ThenTerm);
  2480. if (StackMallocIdx <= 4) {
  2481. int ClassSize = kMinStackMallocSize << StackMallocIdx;
  2482. ShadowAfterReturn.resize(ClassSize / L.Granularity,
  2483. kAsanStackUseAfterReturnMagic);
  2484. copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
  2485. ShadowBase);
  2486. Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
  2487. FakeStack,
  2488. ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
  2489. Value *SavedFlagPtr = IRBPoison.CreateLoad(
  2490. IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
  2491. IRBPoison.CreateStore(
  2492. Constant::getNullValue(IRBPoison.getInt8Ty()),
  2493. IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
  2494. } else {
  2495. // For larger frames call __asan_stack_free_*.
  2496. IRBPoison.CreateCall(
  2497. AsanStackFreeFunc[StackMallocIdx],
  2498. {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
  2499. }
  2500. IRBuilder<> IRBElse(ElseTerm);
  2501. copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
  2502. } else {
  2503. copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
  2504. }
  2505. }
  2506. // We are done. Remove the old unused alloca instructions.
  2507. for (auto AI : AllocaVec) AI->eraseFromParent();
  2508. }
  2509. void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
  2510. IRBuilder<> &IRB, bool DoPoison) {
  2511. // For now just insert the call to ASan runtime.
  2512. Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
  2513. Value *SizeArg = ConstantInt::get(IntptrTy, Size);
  2514. IRB.CreateCall(
  2515. DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
  2516. {AddrArg, SizeArg});
  2517. }
  2518. // Handling llvm.lifetime intrinsics for a given %alloca:
  2519. // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
  2520. // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
  2521. // invalid accesses) and unpoison it for llvm.lifetime.start (the memory
  2522. // could be poisoned by previous llvm.lifetime.end instruction, as the
  2523. // variable may go in and out of scope several times, e.g. in loops).
  2524. // (3) if we poisoned at least one %alloca in a function,
  2525. // unpoison the whole stack frame at function exit.
  2526. AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
  2527. if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
  2528. // We're interested only in allocas we can handle.
  2529. return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
  2530. // See if we've already calculated (or started to calculate) alloca for a
  2531. // given value.
  2532. AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
  2533. if (I != AllocaForValue.end()) return I->second;
  2534. // Store 0 while we're calculating alloca for value V to avoid
  2535. // infinite recursion if the value references itself.
  2536. AllocaForValue[V] = nullptr;
  2537. AllocaInst *Res = nullptr;
  2538. if (CastInst *CI = dyn_cast<CastInst>(V))
  2539. Res = findAllocaForValue(CI->getOperand(0));
  2540. else if (PHINode *PN = dyn_cast<PHINode>(V)) {
  2541. for (Value *IncValue : PN->incoming_values()) {
  2542. // Allow self-referencing phi-nodes.
  2543. if (IncValue == PN) continue;
  2544. AllocaInst *IncValueAI = findAllocaForValue(IncValue);
  2545. // AI for incoming values should exist and should all be equal.
  2546. if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
  2547. return nullptr;
  2548. Res = IncValueAI;
  2549. }
  2550. } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
  2551. Res = findAllocaForValue(EP->getPointerOperand());
  2552. } else {
  2553. DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
  2554. }
  2555. if (Res) AllocaForValue[V] = Res;
  2556. return Res;
  2557. }
  2558. void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
  2559. IRBuilder<> IRB(AI);
  2560. const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
  2561. const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
  2562. Value *Zero = Constant::getNullValue(IntptrTy);
  2563. Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
  2564. Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
  2565. // Since we need to extend alloca with additional memory to locate
  2566. // redzones, and OldSize is number of allocated blocks with
  2567. // ElementSize size, get allocated memory size in bytes by
  2568. // OldSize * ElementSize.
  2569. const unsigned ElementSize =
  2570. F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
  2571. Value *OldSize =
  2572. IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
  2573. ConstantInt::get(IntptrTy, ElementSize));
  2574. // PartialSize = OldSize % 32
  2575. Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
  2576. // Misalign = kAllocaRzSize - PartialSize;
  2577. Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
  2578. // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
  2579. Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
  2580. Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
  2581. // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
  2582. // Align is added to locate left redzone, PartialPadding for possible
  2583. // partial redzone and kAllocaRzSize for right redzone respectively.
  2584. Value *AdditionalChunkSize = IRB.CreateAdd(
  2585. ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
  2586. Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
  2587. // Insert new alloca with new NewSize and Align params.
  2588. AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
  2589. NewAlloca->setAlignment(Align);
  2590. // NewAddress = Address + Align
  2591. Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
  2592. ConstantInt::get(IntptrTy, Align));
  2593. // Insert __asan_alloca_poison call for new created alloca.
  2594. IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
  2595. // Store the last alloca's address to DynamicAllocaLayout. We'll need this
  2596. // for unpoisoning stuff.
  2597. IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
  2598. Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
  2599. // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
  2600. AI->replaceAllUsesWith(NewAddressPtr);
  2601. // We are done. Erase old alloca from parent.
  2602. AI->eraseFromParent();
  2603. }
  2604. // isSafeAccess returns true if Addr is always inbounds with respect to its
  2605. // base object. For example, it is a field access or an array access with
  2606. // constant inbounds index.
  2607. bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
  2608. Value *Addr, uint64_t TypeSize) const {
  2609. SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
  2610. if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
  2611. uint64_t Size = SizeOffset.first.getZExtValue();
  2612. int64_t Offset = SizeOffset.second.getSExtValue();
  2613. // Three checks are required to ensure safety:
  2614. // . Offset >= 0 (since the offset is given from the base ptr)
  2615. // . Size >= Offset (unsigned)
  2616. // . Size - Offset >= NeededSize (unsigned)
  2617. return Offset >= 0 && Size >= uint64_t(Offset) &&
  2618. Size - uint64_t(Offset) >= TypeSize / 8;
  2619. }