LocalizationChecker.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. //=- LocalizationChecker.cpp -------------------------------------*- 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 defines a set of checks for localizability including:
  11. // 1) A checker that warns about uses of non-localized NSStrings passed to
  12. // UI methods expecting localized strings
  13. // 2) A syntactic checker that warns against the bad practice of
  14. // not including a comment in NSLocalizedString macros.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "ClangSACheckers.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/RecursiveASTVisitor.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/Lex/Lexer.h"
  24. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  25. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  26. #include "clang/StaticAnalyzer/Core/Checker.h"
  27. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  28. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  29. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  30. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  31. #include "llvm/Support/Unicode.h"
  32. using namespace clang;
  33. using namespace ento;
  34. namespace {
  35. struct LocalizedState {
  36. private:
  37. enum Kind { NonLocalized, Localized } K;
  38. LocalizedState(Kind InK) : K(InK) {}
  39. public:
  40. bool isLocalized() const { return K == Localized; }
  41. bool isNonLocalized() const { return K == NonLocalized; }
  42. static LocalizedState getLocalized() { return LocalizedState(Localized); }
  43. static LocalizedState getNonLocalized() {
  44. return LocalizedState(NonLocalized);
  45. }
  46. // Overload the == operator
  47. bool operator==(const LocalizedState &X) const { return K == X.K; }
  48. // LLVMs equivalent of a hash function
  49. void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
  50. };
  51. class NonLocalizedStringChecker
  52. : public Checker<check::PreCall, check::PostCall, check::PreObjCMessage,
  53. check::PostObjCMessage,
  54. check::PostStmt<ObjCStringLiteral>> {
  55. mutable std::unique_ptr<BugType> BT;
  56. // Methods that require a localized string
  57. mutable llvm::DenseMap<const IdentifierInfo *,
  58. llvm::DenseMap<Selector, uint8_t>> UIMethods;
  59. // Methods that return a localized string
  60. mutable llvm::SmallSet<std::pair<const IdentifierInfo *, Selector>, 12> LSM;
  61. // C Functions that return a localized string
  62. mutable llvm::SmallSet<const IdentifierInfo *, 5> LSF;
  63. void initUIMethods(ASTContext &Ctx) const;
  64. void initLocStringsMethods(ASTContext &Ctx) const;
  65. bool hasNonLocalizedState(SVal S, CheckerContext &C) const;
  66. bool hasLocalizedState(SVal S, CheckerContext &C) const;
  67. void setNonLocalizedState(SVal S, CheckerContext &C) const;
  68. void setLocalizedState(SVal S, CheckerContext &C) const;
  69. bool isAnnotatedAsReturningLocalized(const Decl *D) const;
  70. bool isAnnotatedAsTakingLocalized(const Decl *D) const;
  71. void reportLocalizationError(SVal S, const CallEvent &M, CheckerContext &C,
  72. int argumentNumber = 0) const;
  73. int getLocalizedArgumentForSelector(const IdentifierInfo *Receiver,
  74. Selector S) const;
  75. public:
  76. NonLocalizedStringChecker();
  77. // When this parameter is set to true, the checker assumes all
  78. // methods that return NSStrings are unlocalized. Thus, more false
  79. // positives will be reported.
  80. DefaultBool IsAggressive;
  81. void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
  82. void checkPostObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const;
  83. void checkPostStmt(const ObjCStringLiteral *SL, CheckerContext &C) const;
  84. void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
  85. void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
  86. };
  87. } // end anonymous namespace
  88. REGISTER_MAP_WITH_PROGRAMSTATE(LocalizedMemMap, const MemRegion *,
  89. LocalizedState)
  90. NonLocalizedStringChecker::NonLocalizedStringChecker() {
  91. BT.reset(new BugType(this, "Unlocalizable string",
  92. "Localizability Issue (Apple)"));
  93. }
  94. namespace {
  95. class NonLocalizedStringBRVisitor final
  96. : public BugReporterVisitorImpl<NonLocalizedStringBRVisitor> {
  97. const MemRegion *NonLocalizedString;
  98. bool Satisfied;
  99. public:
  100. NonLocalizedStringBRVisitor(const MemRegion *NonLocalizedString)
  101. : NonLocalizedString(NonLocalizedString), Satisfied(false) {
  102. assert(NonLocalizedString);
  103. }
  104. std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *Succ,
  105. const ExplodedNode *Pred,
  106. BugReporterContext &BRC,
  107. BugReport &BR) override;
  108. void Profile(llvm::FoldingSetNodeID &ID) const override {
  109. ID.Add(NonLocalizedString);
  110. }
  111. };
  112. } // End anonymous namespace.
  113. #define NEW_RECEIVER(receiver) \
  114. llvm::DenseMap<Selector, uint8_t> &receiver##M = \
  115. UIMethods.insert({&Ctx.Idents.get(#receiver), \
  116. llvm::DenseMap<Selector, uint8_t>()}) \
  117. .first->second;
  118. #define ADD_NULLARY_METHOD(receiver, method, argument) \
  119. receiver##M.insert( \
  120. {Ctx.Selectors.getNullarySelector(&Ctx.Idents.get(#method)), argument});
  121. #define ADD_UNARY_METHOD(receiver, method, argument) \
  122. receiver##M.insert( \
  123. {Ctx.Selectors.getUnarySelector(&Ctx.Idents.get(#method)), argument});
  124. #define ADD_METHOD(receiver, method_list, count, argument) \
  125. receiver##M.insert({Ctx.Selectors.getSelector(count, method_list), argument});
  126. /// Initializes a list of methods that require a localized string
  127. /// Format: {"ClassName", {{"selectorName:", LocStringArg#}, ...}, ...}
  128. void NonLocalizedStringChecker::initUIMethods(ASTContext &Ctx) const {
  129. if (!UIMethods.empty())
  130. return;
  131. // UI Methods
  132. NEW_RECEIVER(UISearchDisplayController)
  133. ADD_UNARY_METHOD(UISearchDisplayController, setSearchResultsTitle, 0)
  134. NEW_RECEIVER(UITabBarItem)
  135. IdentifierInfo *initWithTitleUITabBarItemTag[] = {
  136. &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("image"),
  137. &Ctx.Idents.get("tag")};
  138. ADD_METHOD(UITabBarItem, initWithTitleUITabBarItemTag, 3, 0)
  139. IdentifierInfo *initWithTitleUITabBarItemImage[] = {
  140. &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("image"),
  141. &Ctx.Idents.get("selectedImage")};
  142. ADD_METHOD(UITabBarItem, initWithTitleUITabBarItemImage, 3, 0)
  143. NEW_RECEIVER(NSDockTile)
  144. ADD_UNARY_METHOD(NSDockTile, setBadgeLabel, 0)
  145. NEW_RECEIVER(NSStatusItem)
  146. ADD_UNARY_METHOD(NSStatusItem, setTitle, 0)
  147. ADD_UNARY_METHOD(NSStatusItem, setToolTip, 0)
  148. NEW_RECEIVER(UITableViewRowAction)
  149. IdentifierInfo *rowActionWithStyleUITableViewRowAction[] = {
  150. &Ctx.Idents.get("rowActionWithStyle"), &Ctx.Idents.get("title"),
  151. &Ctx.Idents.get("handler")};
  152. ADD_METHOD(UITableViewRowAction, rowActionWithStyleUITableViewRowAction, 3, 1)
  153. ADD_UNARY_METHOD(UITableViewRowAction, setTitle, 0)
  154. NEW_RECEIVER(NSBox)
  155. ADD_UNARY_METHOD(NSBox, setTitle, 0)
  156. NEW_RECEIVER(NSButton)
  157. ADD_UNARY_METHOD(NSButton, setTitle, 0)
  158. ADD_UNARY_METHOD(NSButton, setAlternateTitle, 0)
  159. IdentifierInfo *radioButtonWithTitleNSButton[] = {
  160. &Ctx.Idents.get("radioButtonWithTitle"), &Ctx.Idents.get("target"),
  161. &Ctx.Idents.get("action")};
  162. ADD_METHOD(NSButton, radioButtonWithTitleNSButton, 3, 0)
  163. IdentifierInfo *buttonWithTitleNSButtonImage[] = {
  164. &Ctx.Idents.get("buttonWithTitle"), &Ctx.Idents.get("image"),
  165. &Ctx.Idents.get("target"), &Ctx.Idents.get("action")};
  166. ADD_METHOD(NSButton, buttonWithTitleNSButtonImage, 4, 0)
  167. IdentifierInfo *checkboxWithTitleNSButton[] = {
  168. &Ctx.Idents.get("checkboxWithTitle"), &Ctx.Idents.get("target"),
  169. &Ctx.Idents.get("action")};
  170. ADD_METHOD(NSButton, checkboxWithTitleNSButton, 3, 0)
  171. IdentifierInfo *buttonWithTitleNSButtonTarget[] = {
  172. &Ctx.Idents.get("buttonWithTitle"), &Ctx.Idents.get("target"),
  173. &Ctx.Idents.get("action")};
  174. ADD_METHOD(NSButton, buttonWithTitleNSButtonTarget, 3, 0)
  175. NEW_RECEIVER(NSSavePanel)
  176. ADD_UNARY_METHOD(NSSavePanel, setPrompt, 0)
  177. ADD_UNARY_METHOD(NSSavePanel, setTitle, 0)
  178. ADD_UNARY_METHOD(NSSavePanel, setNameFieldLabel, 0)
  179. ADD_UNARY_METHOD(NSSavePanel, setNameFieldStringValue, 0)
  180. ADD_UNARY_METHOD(NSSavePanel, setMessage, 0)
  181. NEW_RECEIVER(UIPrintInfo)
  182. ADD_UNARY_METHOD(UIPrintInfo, setJobName, 0)
  183. NEW_RECEIVER(NSTabViewItem)
  184. ADD_UNARY_METHOD(NSTabViewItem, setLabel, 0)
  185. ADD_UNARY_METHOD(NSTabViewItem, setToolTip, 0)
  186. NEW_RECEIVER(NSBrowser)
  187. IdentifierInfo *setTitleNSBrowser[] = {&Ctx.Idents.get("setTitle"),
  188. &Ctx.Idents.get("ofColumn")};
  189. ADD_METHOD(NSBrowser, setTitleNSBrowser, 2, 0)
  190. NEW_RECEIVER(UIAccessibilityElement)
  191. ADD_UNARY_METHOD(UIAccessibilityElement, setAccessibilityLabel, 0)
  192. ADD_UNARY_METHOD(UIAccessibilityElement, setAccessibilityHint, 0)
  193. ADD_UNARY_METHOD(UIAccessibilityElement, setAccessibilityValue, 0)
  194. NEW_RECEIVER(UIAlertAction)
  195. IdentifierInfo *actionWithTitleUIAlertAction[] = {
  196. &Ctx.Idents.get("actionWithTitle"), &Ctx.Idents.get("style"),
  197. &Ctx.Idents.get("handler")};
  198. ADD_METHOD(UIAlertAction, actionWithTitleUIAlertAction, 3, 0)
  199. NEW_RECEIVER(NSPopUpButton)
  200. ADD_UNARY_METHOD(NSPopUpButton, addItemWithTitle, 0)
  201. IdentifierInfo *insertItemWithTitleNSPopUpButton[] = {
  202. &Ctx.Idents.get("insertItemWithTitle"), &Ctx.Idents.get("atIndex")};
  203. ADD_METHOD(NSPopUpButton, insertItemWithTitleNSPopUpButton, 2, 0)
  204. ADD_UNARY_METHOD(NSPopUpButton, removeItemWithTitle, 0)
  205. ADD_UNARY_METHOD(NSPopUpButton, selectItemWithTitle, 0)
  206. ADD_UNARY_METHOD(NSPopUpButton, setTitle, 0)
  207. NEW_RECEIVER(NSTableViewRowAction)
  208. IdentifierInfo *rowActionWithStyleNSTableViewRowAction[] = {
  209. &Ctx.Idents.get("rowActionWithStyle"), &Ctx.Idents.get("title"),
  210. &Ctx.Idents.get("handler")};
  211. ADD_METHOD(NSTableViewRowAction, rowActionWithStyleNSTableViewRowAction, 3, 1)
  212. ADD_UNARY_METHOD(NSTableViewRowAction, setTitle, 0)
  213. NEW_RECEIVER(NSImage)
  214. ADD_UNARY_METHOD(NSImage, setAccessibilityDescription, 0)
  215. NEW_RECEIVER(NSUserActivity)
  216. ADD_UNARY_METHOD(NSUserActivity, setTitle, 0)
  217. NEW_RECEIVER(NSPathControlItem)
  218. ADD_UNARY_METHOD(NSPathControlItem, setTitle, 0)
  219. NEW_RECEIVER(NSCell)
  220. ADD_UNARY_METHOD(NSCell, initTextCell, 0)
  221. ADD_UNARY_METHOD(NSCell, setTitle, 0)
  222. ADD_UNARY_METHOD(NSCell, setStringValue, 0)
  223. NEW_RECEIVER(NSPathControl)
  224. ADD_UNARY_METHOD(NSPathControl, setPlaceholderString, 0)
  225. NEW_RECEIVER(UIAccessibility)
  226. ADD_UNARY_METHOD(UIAccessibility, setAccessibilityLabel, 0)
  227. ADD_UNARY_METHOD(UIAccessibility, setAccessibilityHint, 0)
  228. ADD_UNARY_METHOD(UIAccessibility, setAccessibilityValue, 0)
  229. NEW_RECEIVER(NSTableColumn)
  230. ADD_UNARY_METHOD(NSTableColumn, setTitle, 0)
  231. ADD_UNARY_METHOD(NSTableColumn, setHeaderToolTip, 0)
  232. NEW_RECEIVER(NSSegmentedControl)
  233. IdentifierInfo *setLabelNSSegmentedControl[] = {
  234. &Ctx.Idents.get("setLabel"), &Ctx.Idents.get("forSegment")};
  235. ADD_METHOD(NSSegmentedControl, setLabelNSSegmentedControl, 2, 0)
  236. IdentifierInfo *setToolTipNSSegmentedControl[] = {
  237. &Ctx.Idents.get("setToolTip"), &Ctx.Idents.get("forSegment")};
  238. ADD_METHOD(NSSegmentedControl, setToolTipNSSegmentedControl, 2, 0)
  239. NEW_RECEIVER(NSButtonCell)
  240. ADD_UNARY_METHOD(NSButtonCell, setTitle, 0)
  241. ADD_UNARY_METHOD(NSButtonCell, setAlternateTitle, 0)
  242. NEW_RECEIVER(NSDatePickerCell)
  243. ADD_UNARY_METHOD(NSDatePickerCell, initTextCell, 0)
  244. NEW_RECEIVER(NSSliderCell)
  245. ADD_UNARY_METHOD(NSSliderCell, setTitle, 0)
  246. NEW_RECEIVER(NSControl)
  247. ADD_UNARY_METHOD(NSControl, setStringValue, 0)
  248. NEW_RECEIVER(NSAccessibility)
  249. ADD_UNARY_METHOD(NSAccessibility, setAccessibilityValueDescription, 0)
  250. ADD_UNARY_METHOD(NSAccessibility, setAccessibilityLabel, 0)
  251. ADD_UNARY_METHOD(NSAccessibility, setAccessibilityTitle, 0)
  252. ADD_UNARY_METHOD(NSAccessibility, setAccessibilityPlaceholderValue, 0)
  253. ADD_UNARY_METHOD(NSAccessibility, setAccessibilityHelp, 0)
  254. NEW_RECEIVER(NSMatrix)
  255. IdentifierInfo *setToolTipNSMatrix[] = {&Ctx.Idents.get("setToolTip"),
  256. &Ctx.Idents.get("forCell")};
  257. ADD_METHOD(NSMatrix, setToolTipNSMatrix, 2, 0)
  258. NEW_RECEIVER(NSPrintPanel)
  259. ADD_UNARY_METHOD(NSPrintPanel, setDefaultButtonTitle, 0)
  260. NEW_RECEIVER(UILocalNotification)
  261. ADD_UNARY_METHOD(UILocalNotification, setAlertBody, 0)
  262. ADD_UNARY_METHOD(UILocalNotification, setAlertAction, 0)
  263. ADD_UNARY_METHOD(UILocalNotification, setAlertTitle, 0)
  264. NEW_RECEIVER(NSSlider)
  265. ADD_UNARY_METHOD(NSSlider, setTitle, 0)
  266. NEW_RECEIVER(UIMenuItem)
  267. IdentifierInfo *initWithTitleUIMenuItem[] = {&Ctx.Idents.get("initWithTitle"),
  268. &Ctx.Idents.get("action")};
  269. ADD_METHOD(UIMenuItem, initWithTitleUIMenuItem, 2, 0)
  270. ADD_UNARY_METHOD(UIMenuItem, setTitle, 0)
  271. NEW_RECEIVER(UIAlertController)
  272. IdentifierInfo *alertControllerWithTitleUIAlertController[] = {
  273. &Ctx.Idents.get("alertControllerWithTitle"), &Ctx.Idents.get("message"),
  274. &Ctx.Idents.get("preferredStyle")};
  275. ADD_METHOD(UIAlertController, alertControllerWithTitleUIAlertController, 3, 1)
  276. ADD_UNARY_METHOD(UIAlertController, setTitle, 0)
  277. ADD_UNARY_METHOD(UIAlertController, setMessage, 0)
  278. NEW_RECEIVER(UIApplicationShortcutItem)
  279. IdentifierInfo *initWithTypeUIApplicationShortcutItemIcon[] = {
  280. &Ctx.Idents.get("initWithType"), &Ctx.Idents.get("localizedTitle"),
  281. &Ctx.Idents.get("localizedSubtitle"), &Ctx.Idents.get("icon"),
  282. &Ctx.Idents.get("userInfo")};
  283. ADD_METHOD(UIApplicationShortcutItem,
  284. initWithTypeUIApplicationShortcutItemIcon, 5, 1)
  285. IdentifierInfo *initWithTypeUIApplicationShortcutItem[] = {
  286. &Ctx.Idents.get("initWithType"), &Ctx.Idents.get("localizedTitle")};
  287. ADD_METHOD(UIApplicationShortcutItem, initWithTypeUIApplicationShortcutItem,
  288. 2, 1)
  289. NEW_RECEIVER(UIActionSheet)
  290. IdentifierInfo *initWithTitleUIActionSheet[] = {
  291. &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("delegate"),
  292. &Ctx.Idents.get("cancelButtonTitle"),
  293. &Ctx.Idents.get("destructiveButtonTitle"),
  294. &Ctx.Idents.get("otherButtonTitles")};
  295. ADD_METHOD(UIActionSheet, initWithTitleUIActionSheet, 5, 0)
  296. ADD_UNARY_METHOD(UIActionSheet, addButtonWithTitle, 0)
  297. ADD_UNARY_METHOD(UIActionSheet, setTitle, 0)
  298. NEW_RECEIVER(UIAccessibilityCustomAction)
  299. IdentifierInfo *initWithNameUIAccessibilityCustomAction[] = {
  300. &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("target"),
  301. &Ctx.Idents.get("selector")};
  302. ADD_METHOD(UIAccessibilityCustomAction,
  303. initWithNameUIAccessibilityCustomAction, 3, 0)
  304. ADD_UNARY_METHOD(UIAccessibilityCustomAction, setName, 0)
  305. NEW_RECEIVER(UISearchBar)
  306. ADD_UNARY_METHOD(UISearchBar, setText, 0)
  307. ADD_UNARY_METHOD(UISearchBar, setPrompt, 0)
  308. ADD_UNARY_METHOD(UISearchBar, setPlaceholder, 0)
  309. NEW_RECEIVER(UIBarItem)
  310. ADD_UNARY_METHOD(UIBarItem, setTitle, 0)
  311. NEW_RECEIVER(UITextView)
  312. ADD_UNARY_METHOD(UITextView, setText, 0)
  313. NEW_RECEIVER(NSView)
  314. ADD_UNARY_METHOD(NSView, setToolTip, 0)
  315. NEW_RECEIVER(NSTextField)
  316. ADD_UNARY_METHOD(NSTextField, setPlaceholderString, 0)
  317. ADD_UNARY_METHOD(NSTextField, textFieldWithString, 0)
  318. ADD_UNARY_METHOD(NSTextField, wrappingLabelWithString, 0)
  319. ADD_UNARY_METHOD(NSTextField, labelWithString, 0)
  320. NEW_RECEIVER(NSAttributedString)
  321. ADD_UNARY_METHOD(NSAttributedString, initWithString, 0)
  322. IdentifierInfo *initWithStringNSAttributedString[] = {
  323. &Ctx.Idents.get("initWithString"), &Ctx.Idents.get("attributes")};
  324. ADD_METHOD(NSAttributedString, initWithStringNSAttributedString, 2, 0)
  325. NEW_RECEIVER(NSText)
  326. ADD_UNARY_METHOD(NSText, setString, 0)
  327. NEW_RECEIVER(UIKeyCommand)
  328. IdentifierInfo *keyCommandWithInputUIKeyCommand[] = {
  329. &Ctx.Idents.get("keyCommandWithInput"), &Ctx.Idents.get("modifierFlags"),
  330. &Ctx.Idents.get("action"), &Ctx.Idents.get("discoverabilityTitle")};
  331. ADD_METHOD(UIKeyCommand, keyCommandWithInputUIKeyCommand, 4, 3)
  332. ADD_UNARY_METHOD(UIKeyCommand, setDiscoverabilityTitle, 0)
  333. NEW_RECEIVER(UILabel)
  334. ADD_UNARY_METHOD(UILabel, setText, 0)
  335. NEW_RECEIVER(NSAlert)
  336. IdentifierInfo *alertWithMessageTextNSAlert[] = {
  337. &Ctx.Idents.get("alertWithMessageText"), &Ctx.Idents.get("defaultButton"),
  338. &Ctx.Idents.get("alternateButton"), &Ctx.Idents.get("otherButton"),
  339. &Ctx.Idents.get("informativeTextWithFormat")};
  340. ADD_METHOD(NSAlert, alertWithMessageTextNSAlert, 5, 0)
  341. ADD_UNARY_METHOD(NSAlert, addButtonWithTitle, 0)
  342. ADD_UNARY_METHOD(NSAlert, setMessageText, 0)
  343. ADD_UNARY_METHOD(NSAlert, setInformativeText, 0)
  344. ADD_UNARY_METHOD(NSAlert, setHelpAnchor, 0)
  345. NEW_RECEIVER(UIMutableApplicationShortcutItem)
  346. ADD_UNARY_METHOD(UIMutableApplicationShortcutItem, setLocalizedTitle, 0)
  347. ADD_UNARY_METHOD(UIMutableApplicationShortcutItem, setLocalizedSubtitle, 0)
  348. NEW_RECEIVER(UIButton)
  349. IdentifierInfo *setTitleUIButton[] = {&Ctx.Idents.get("setTitle"),
  350. &Ctx.Idents.get("forState")};
  351. ADD_METHOD(UIButton, setTitleUIButton, 2, 0)
  352. NEW_RECEIVER(NSWindow)
  353. ADD_UNARY_METHOD(NSWindow, setTitle, 0)
  354. IdentifierInfo *minFrameWidthWithTitleNSWindow[] = {
  355. &Ctx.Idents.get("minFrameWidthWithTitle"), &Ctx.Idents.get("styleMask")};
  356. ADD_METHOD(NSWindow, minFrameWidthWithTitleNSWindow, 2, 0)
  357. ADD_UNARY_METHOD(NSWindow, setMiniwindowTitle, 0)
  358. NEW_RECEIVER(NSPathCell)
  359. ADD_UNARY_METHOD(NSPathCell, setPlaceholderString, 0)
  360. NEW_RECEIVER(UIDocumentMenuViewController)
  361. IdentifierInfo *addOptionWithTitleUIDocumentMenuViewController[] = {
  362. &Ctx.Idents.get("addOptionWithTitle"), &Ctx.Idents.get("image"),
  363. &Ctx.Idents.get("order"), &Ctx.Idents.get("handler")};
  364. ADD_METHOD(UIDocumentMenuViewController,
  365. addOptionWithTitleUIDocumentMenuViewController, 4, 0)
  366. NEW_RECEIVER(UINavigationItem)
  367. ADD_UNARY_METHOD(UINavigationItem, initWithTitle, 0)
  368. ADD_UNARY_METHOD(UINavigationItem, setTitle, 0)
  369. ADD_UNARY_METHOD(UINavigationItem, setPrompt, 0)
  370. NEW_RECEIVER(UIAlertView)
  371. IdentifierInfo *initWithTitleUIAlertView[] = {
  372. &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("message"),
  373. &Ctx.Idents.get("delegate"), &Ctx.Idents.get("cancelButtonTitle"),
  374. &Ctx.Idents.get("otherButtonTitles")};
  375. ADD_METHOD(UIAlertView, initWithTitleUIAlertView, 5, 0)
  376. ADD_UNARY_METHOD(UIAlertView, addButtonWithTitle, 0)
  377. ADD_UNARY_METHOD(UIAlertView, setTitle, 0)
  378. ADD_UNARY_METHOD(UIAlertView, setMessage, 0)
  379. NEW_RECEIVER(NSFormCell)
  380. ADD_UNARY_METHOD(NSFormCell, initTextCell, 0)
  381. ADD_UNARY_METHOD(NSFormCell, setTitle, 0)
  382. ADD_UNARY_METHOD(NSFormCell, setPlaceholderString, 0)
  383. NEW_RECEIVER(NSUserNotification)
  384. ADD_UNARY_METHOD(NSUserNotification, setTitle, 0)
  385. ADD_UNARY_METHOD(NSUserNotification, setSubtitle, 0)
  386. ADD_UNARY_METHOD(NSUserNotification, setInformativeText, 0)
  387. ADD_UNARY_METHOD(NSUserNotification, setActionButtonTitle, 0)
  388. ADD_UNARY_METHOD(NSUserNotification, setOtherButtonTitle, 0)
  389. ADD_UNARY_METHOD(NSUserNotification, setResponsePlaceholder, 0)
  390. NEW_RECEIVER(NSToolbarItem)
  391. ADD_UNARY_METHOD(NSToolbarItem, setLabel, 0)
  392. ADD_UNARY_METHOD(NSToolbarItem, setPaletteLabel, 0)
  393. ADD_UNARY_METHOD(NSToolbarItem, setToolTip, 0)
  394. NEW_RECEIVER(NSProgress)
  395. ADD_UNARY_METHOD(NSProgress, setLocalizedDescription, 0)
  396. ADD_UNARY_METHOD(NSProgress, setLocalizedAdditionalDescription, 0)
  397. NEW_RECEIVER(NSSegmentedCell)
  398. IdentifierInfo *setLabelNSSegmentedCell[] = {&Ctx.Idents.get("setLabel"),
  399. &Ctx.Idents.get("forSegment")};
  400. ADD_METHOD(NSSegmentedCell, setLabelNSSegmentedCell, 2, 0)
  401. IdentifierInfo *setToolTipNSSegmentedCell[] = {&Ctx.Idents.get("setToolTip"),
  402. &Ctx.Idents.get("forSegment")};
  403. ADD_METHOD(NSSegmentedCell, setToolTipNSSegmentedCell, 2, 0)
  404. NEW_RECEIVER(NSUndoManager)
  405. ADD_UNARY_METHOD(NSUndoManager, setActionName, 0)
  406. ADD_UNARY_METHOD(NSUndoManager, undoMenuTitleForUndoActionName, 0)
  407. ADD_UNARY_METHOD(NSUndoManager, redoMenuTitleForUndoActionName, 0)
  408. NEW_RECEIVER(NSMenuItem)
  409. IdentifierInfo *initWithTitleNSMenuItem[] = {
  410. &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("action"),
  411. &Ctx.Idents.get("keyEquivalent")};
  412. ADD_METHOD(NSMenuItem, initWithTitleNSMenuItem, 3, 0)
  413. ADD_UNARY_METHOD(NSMenuItem, setTitle, 0)
  414. ADD_UNARY_METHOD(NSMenuItem, setToolTip, 0)
  415. NEW_RECEIVER(NSPopUpButtonCell)
  416. IdentifierInfo *initTextCellNSPopUpButtonCell[] = {
  417. &Ctx.Idents.get("initTextCell"), &Ctx.Idents.get("pullsDown")};
  418. ADD_METHOD(NSPopUpButtonCell, initTextCellNSPopUpButtonCell, 2, 0)
  419. ADD_UNARY_METHOD(NSPopUpButtonCell, addItemWithTitle, 0)
  420. IdentifierInfo *insertItemWithTitleNSPopUpButtonCell[] = {
  421. &Ctx.Idents.get("insertItemWithTitle"), &Ctx.Idents.get("atIndex")};
  422. ADD_METHOD(NSPopUpButtonCell, insertItemWithTitleNSPopUpButtonCell, 2, 0)
  423. ADD_UNARY_METHOD(NSPopUpButtonCell, removeItemWithTitle, 0)
  424. ADD_UNARY_METHOD(NSPopUpButtonCell, selectItemWithTitle, 0)
  425. ADD_UNARY_METHOD(NSPopUpButtonCell, setTitle, 0)
  426. NEW_RECEIVER(NSViewController)
  427. ADD_UNARY_METHOD(NSViewController, setTitle, 0)
  428. NEW_RECEIVER(NSMenu)
  429. ADD_UNARY_METHOD(NSMenu, initWithTitle, 0)
  430. IdentifierInfo *insertItemWithTitleNSMenu[] = {
  431. &Ctx.Idents.get("insertItemWithTitle"), &Ctx.Idents.get("action"),
  432. &Ctx.Idents.get("keyEquivalent"), &Ctx.Idents.get("atIndex")};
  433. ADD_METHOD(NSMenu, insertItemWithTitleNSMenu, 4, 0)
  434. IdentifierInfo *addItemWithTitleNSMenu[] = {
  435. &Ctx.Idents.get("addItemWithTitle"), &Ctx.Idents.get("action"),
  436. &Ctx.Idents.get("keyEquivalent")};
  437. ADD_METHOD(NSMenu, addItemWithTitleNSMenu, 3, 0)
  438. ADD_UNARY_METHOD(NSMenu, setTitle, 0)
  439. NEW_RECEIVER(UIMutableUserNotificationAction)
  440. ADD_UNARY_METHOD(UIMutableUserNotificationAction, setTitle, 0)
  441. NEW_RECEIVER(NSForm)
  442. ADD_UNARY_METHOD(NSForm, addEntry, 0)
  443. IdentifierInfo *insertEntryNSForm[] = {&Ctx.Idents.get("insertEntry"),
  444. &Ctx.Idents.get("atIndex")};
  445. ADD_METHOD(NSForm, insertEntryNSForm, 2, 0)
  446. NEW_RECEIVER(NSTextFieldCell)
  447. ADD_UNARY_METHOD(NSTextFieldCell, setPlaceholderString, 0)
  448. NEW_RECEIVER(NSUserNotificationAction)
  449. IdentifierInfo *actionWithIdentifierNSUserNotificationAction[] = {
  450. &Ctx.Idents.get("actionWithIdentifier"), &Ctx.Idents.get("title")};
  451. ADD_METHOD(NSUserNotificationAction,
  452. actionWithIdentifierNSUserNotificationAction, 2, 1)
  453. NEW_RECEIVER(UITextField)
  454. ADD_UNARY_METHOD(UITextField, setText, 0)
  455. ADD_UNARY_METHOD(UITextField, setPlaceholder, 0)
  456. NEW_RECEIVER(UIBarButtonItem)
  457. IdentifierInfo *initWithTitleUIBarButtonItem[] = {
  458. &Ctx.Idents.get("initWithTitle"), &Ctx.Idents.get("style"),
  459. &Ctx.Idents.get("target"), &Ctx.Idents.get("action")};
  460. ADD_METHOD(UIBarButtonItem, initWithTitleUIBarButtonItem, 4, 0)
  461. NEW_RECEIVER(UIViewController)
  462. ADD_UNARY_METHOD(UIViewController, setTitle, 0)
  463. NEW_RECEIVER(UISegmentedControl)
  464. IdentifierInfo *insertSegmentWithTitleUISegmentedControl[] = {
  465. &Ctx.Idents.get("insertSegmentWithTitle"), &Ctx.Idents.get("atIndex"),
  466. &Ctx.Idents.get("animated")};
  467. ADD_METHOD(UISegmentedControl, insertSegmentWithTitleUISegmentedControl, 3, 0)
  468. IdentifierInfo *setTitleUISegmentedControl[] = {
  469. &Ctx.Idents.get("setTitle"), &Ctx.Idents.get("forSegmentAtIndex")};
  470. ADD_METHOD(UISegmentedControl, setTitleUISegmentedControl, 2, 0)
  471. NEW_RECEIVER(NSAccessibilityCustomRotorItemResult)
  472. IdentifierInfo
  473. *initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult[] = {
  474. &Ctx.Idents.get("initWithItemLoadingToken"),
  475. &Ctx.Idents.get("customLabel")};
  476. ADD_METHOD(NSAccessibilityCustomRotorItemResult,
  477. initWithItemLoadingTokenNSAccessibilityCustomRotorItemResult, 2, 1)
  478. ADD_UNARY_METHOD(NSAccessibilityCustomRotorItemResult, setCustomLabel, 0)
  479. NEW_RECEIVER(UIContextualAction)
  480. IdentifierInfo *contextualActionWithStyleUIContextualAction[] = {
  481. &Ctx.Idents.get("contextualActionWithStyle"), &Ctx.Idents.get("title"),
  482. &Ctx.Idents.get("handler")};
  483. ADD_METHOD(UIContextualAction, contextualActionWithStyleUIContextualAction, 3,
  484. 1)
  485. ADD_UNARY_METHOD(UIContextualAction, setTitle, 0)
  486. NEW_RECEIVER(NSAccessibilityCustomRotor)
  487. IdentifierInfo *initWithLabelNSAccessibilityCustomRotor[] = {
  488. &Ctx.Idents.get("initWithLabel"), &Ctx.Idents.get("itemSearchDelegate")};
  489. ADD_METHOD(NSAccessibilityCustomRotor,
  490. initWithLabelNSAccessibilityCustomRotor, 2, 0)
  491. ADD_UNARY_METHOD(NSAccessibilityCustomRotor, setLabel, 0)
  492. NEW_RECEIVER(NSWindowTab)
  493. ADD_UNARY_METHOD(NSWindowTab, setTitle, 0)
  494. ADD_UNARY_METHOD(NSWindowTab, setToolTip, 0)
  495. NEW_RECEIVER(NSAccessibilityCustomAction)
  496. IdentifierInfo *initWithNameNSAccessibilityCustomAction[] = {
  497. &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("handler")};
  498. ADD_METHOD(NSAccessibilityCustomAction,
  499. initWithNameNSAccessibilityCustomAction, 2, 0)
  500. IdentifierInfo *initWithNameTargetNSAccessibilityCustomAction[] = {
  501. &Ctx.Idents.get("initWithName"), &Ctx.Idents.get("target"),
  502. &Ctx.Idents.get("selector")};
  503. ADD_METHOD(NSAccessibilityCustomAction,
  504. initWithNameTargetNSAccessibilityCustomAction, 3, 0)
  505. ADD_UNARY_METHOD(NSAccessibilityCustomAction, setName, 0)
  506. }
  507. #define LSF_INSERT(function_name) LSF.insert(&Ctx.Idents.get(function_name));
  508. #define LSM_INSERT_NULLARY(receiver, method_name) \
  509. LSM.insert({&Ctx.Idents.get(receiver), Ctx.Selectors.getNullarySelector( \
  510. &Ctx.Idents.get(method_name))});
  511. #define LSM_INSERT_UNARY(receiver, method_name) \
  512. LSM.insert({&Ctx.Idents.get(receiver), \
  513. Ctx.Selectors.getUnarySelector(&Ctx.Idents.get(method_name))});
  514. #define LSM_INSERT_SELECTOR(receiver, method_list, arguments) \
  515. LSM.insert({&Ctx.Idents.get(receiver), \
  516. Ctx.Selectors.getSelector(arguments, method_list)});
  517. /// Initializes a list of methods and C functions that return a localized string
  518. void NonLocalizedStringChecker::initLocStringsMethods(ASTContext &Ctx) const {
  519. if (!LSM.empty())
  520. return;
  521. IdentifierInfo *LocalizedStringMacro[] = {
  522. &Ctx.Idents.get("localizedStringForKey"), &Ctx.Idents.get("value"),
  523. &Ctx.Idents.get("table")};
  524. LSM_INSERT_SELECTOR("NSBundle", LocalizedStringMacro, 3)
  525. LSM_INSERT_UNARY("NSDateFormatter", "stringFromDate")
  526. IdentifierInfo *LocalizedStringFromDate[] = {
  527. &Ctx.Idents.get("localizedStringFromDate"), &Ctx.Idents.get("dateStyle"),
  528. &Ctx.Idents.get("timeStyle")};
  529. LSM_INSERT_SELECTOR("NSDateFormatter", LocalizedStringFromDate, 3)
  530. LSM_INSERT_UNARY("NSNumberFormatter", "stringFromNumber")
  531. LSM_INSERT_NULLARY("UITextField", "text")
  532. LSM_INSERT_NULLARY("UITextView", "text")
  533. LSM_INSERT_NULLARY("UILabel", "text")
  534. LSF_INSERT("CFDateFormatterCreateStringWithDate");
  535. LSF_INSERT("CFDateFormatterCreateStringWithAbsoluteTime");
  536. LSF_INSERT("CFNumberFormatterCreateStringWithNumber");
  537. }
  538. /// Checks to see if the method / function declaration includes
  539. /// __attribute__((annotate("returns_localized_nsstring")))
  540. bool NonLocalizedStringChecker::isAnnotatedAsReturningLocalized(
  541. const Decl *D) const {
  542. if (!D)
  543. return false;
  544. return std::any_of(
  545. D->specific_attr_begin<AnnotateAttr>(),
  546. D->specific_attr_end<AnnotateAttr>(), [](const AnnotateAttr *Ann) {
  547. return Ann->getAnnotation() == "returns_localized_nsstring";
  548. });
  549. }
  550. /// Checks to see if the method / function declaration includes
  551. /// __attribute__((annotate("takes_localized_nsstring")))
  552. bool NonLocalizedStringChecker::isAnnotatedAsTakingLocalized(
  553. const Decl *D) const {
  554. if (!D)
  555. return false;
  556. return std::any_of(
  557. D->specific_attr_begin<AnnotateAttr>(),
  558. D->specific_attr_end<AnnotateAttr>(), [](const AnnotateAttr *Ann) {
  559. return Ann->getAnnotation() == "takes_localized_nsstring";
  560. });
  561. }
  562. /// Returns true if the given SVal is marked as Localized in the program state
  563. bool NonLocalizedStringChecker::hasLocalizedState(SVal S,
  564. CheckerContext &C) const {
  565. const MemRegion *mt = S.getAsRegion();
  566. if (mt) {
  567. const LocalizedState *LS = C.getState()->get<LocalizedMemMap>(mt);
  568. if (LS && LS->isLocalized())
  569. return true;
  570. }
  571. return false;
  572. }
  573. /// Returns true if the given SVal is marked as NonLocalized in the program
  574. /// state
  575. bool NonLocalizedStringChecker::hasNonLocalizedState(SVal S,
  576. CheckerContext &C) const {
  577. const MemRegion *mt = S.getAsRegion();
  578. if (mt) {
  579. const LocalizedState *LS = C.getState()->get<LocalizedMemMap>(mt);
  580. if (LS && LS->isNonLocalized())
  581. return true;
  582. }
  583. return false;
  584. }
  585. /// Marks the given SVal as Localized in the program state
  586. void NonLocalizedStringChecker::setLocalizedState(const SVal S,
  587. CheckerContext &C) const {
  588. const MemRegion *mt = S.getAsRegion();
  589. if (mt) {
  590. ProgramStateRef State =
  591. C.getState()->set<LocalizedMemMap>(mt, LocalizedState::getLocalized());
  592. C.addTransition(State);
  593. }
  594. }
  595. /// Marks the given SVal as NonLocalized in the program state
  596. void NonLocalizedStringChecker::setNonLocalizedState(const SVal S,
  597. CheckerContext &C) const {
  598. const MemRegion *mt = S.getAsRegion();
  599. if (mt) {
  600. ProgramStateRef State = C.getState()->set<LocalizedMemMap>(
  601. mt, LocalizedState::getNonLocalized());
  602. C.addTransition(State);
  603. }
  604. }
  605. static bool isDebuggingName(std::string name) {
  606. return StringRef(name).lower().find("debug") != StringRef::npos;
  607. }
  608. /// Returns true when, heuristically, the analyzer may be analyzing debugging
  609. /// code. We use this to suppress localization diagnostics in un-localized user
  610. /// interfaces that are only used for debugging and are therefore not user
  611. /// facing.
  612. static bool isDebuggingContext(CheckerContext &C) {
  613. const Decl *D = C.getCurrentAnalysisDeclContext()->getDecl();
  614. if (!D)
  615. return false;
  616. if (auto *ND = dyn_cast<NamedDecl>(D)) {
  617. if (isDebuggingName(ND->getNameAsString()))
  618. return true;
  619. }
  620. const DeclContext *DC = D->getDeclContext();
  621. if (auto *CD = dyn_cast<ObjCContainerDecl>(DC)) {
  622. if (isDebuggingName(CD->getNameAsString()))
  623. return true;
  624. }
  625. return false;
  626. }
  627. /// Reports a localization error for the passed in method call and SVal
  628. void NonLocalizedStringChecker::reportLocalizationError(
  629. SVal S, const CallEvent &M, CheckerContext &C, int argumentNumber) const {
  630. // Don't warn about localization errors in classes and methods that
  631. // may be debug code.
  632. if (isDebuggingContext(C))
  633. return;
  634. ExplodedNode *ErrNode = C.getPredecessor();
  635. static CheckerProgramPointTag Tag("NonLocalizedStringChecker",
  636. "UnlocalizedString");
  637. ErrNode = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
  638. if (!ErrNode)
  639. return;
  640. // Generate the bug report.
  641. std::unique_ptr<BugReport> R(new BugReport(
  642. *BT, "User-facing text should use localized string macro", ErrNode));
  643. if (argumentNumber) {
  644. R->addRange(M.getArgExpr(argumentNumber - 1)->getSourceRange());
  645. } else {
  646. R->addRange(M.getSourceRange());
  647. }
  648. R->markInteresting(S);
  649. const MemRegion *StringRegion = S.getAsRegion();
  650. if (StringRegion)
  651. R->addVisitor(llvm::make_unique<NonLocalizedStringBRVisitor>(StringRegion));
  652. C.emitReport(std::move(R));
  653. }
  654. /// Returns the argument number requiring localized string if it exists
  655. /// otherwise, returns -1
  656. int NonLocalizedStringChecker::getLocalizedArgumentForSelector(
  657. const IdentifierInfo *Receiver, Selector S) const {
  658. auto method = UIMethods.find(Receiver);
  659. if (method == UIMethods.end())
  660. return -1;
  661. auto argumentIterator = method->getSecond().find(S);
  662. if (argumentIterator == method->getSecond().end())
  663. return -1;
  664. int argumentNumber = argumentIterator->getSecond();
  665. return argumentNumber;
  666. }
  667. /// Check if the string being passed in has NonLocalized state
  668. void NonLocalizedStringChecker::checkPreObjCMessage(const ObjCMethodCall &msg,
  669. CheckerContext &C) const {
  670. initUIMethods(C.getASTContext());
  671. const ObjCInterfaceDecl *OD = msg.getReceiverInterface();
  672. if (!OD)
  673. return;
  674. const IdentifierInfo *odInfo = OD->getIdentifier();
  675. Selector S = msg.getSelector();
  676. std::string SelectorString = S.getAsString();
  677. StringRef SelectorName = SelectorString;
  678. assert(!SelectorName.empty());
  679. if (odInfo->isStr("NSString")) {
  680. // Handle the case where the receiver is an NSString
  681. // These special NSString methods draw to the screen
  682. if (!(SelectorName.startswith("drawAtPoint") ||
  683. SelectorName.startswith("drawInRect") ||
  684. SelectorName.startswith("drawWithRect")))
  685. return;
  686. SVal svTitle = msg.getReceiverSVal();
  687. bool isNonLocalized = hasNonLocalizedState(svTitle, C);
  688. if (isNonLocalized) {
  689. reportLocalizationError(svTitle, msg, C);
  690. }
  691. }
  692. int argumentNumber = getLocalizedArgumentForSelector(odInfo, S);
  693. // Go up each hierarchy of superclasses and their protocols
  694. while (argumentNumber < 0 && OD->getSuperClass() != nullptr) {
  695. for (const auto *P : OD->all_referenced_protocols()) {
  696. argumentNumber = getLocalizedArgumentForSelector(P->getIdentifier(), S);
  697. if (argumentNumber >= 0)
  698. break;
  699. }
  700. if (argumentNumber < 0) {
  701. OD = OD->getSuperClass();
  702. argumentNumber = getLocalizedArgumentForSelector(OD->getIdentifier(), S);
  703. }
  704. }
  705. if (argumentNumber < 0) { // There was no match in UIMethods
  706. if (const Decl *D = msg.getDecl()) {
  707. if (const ObjCMethodDecl *OMD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
  708. auto formals = OMD->parameters();
  709. for (unsigned i = 0, ei = formals.size(); i != ei; ++i) {
  710. if (isAnnotatedAsTakingLocalized(formals[i])) {
  711. argumentNumber = i;
  712. break;
  713. }
  714. }
  715. }
  716. }
  717. }
  718. if (argumentNumber < 0) // Still no match
  719. return;
  720. SVal svTitle = msg.getArgSVal(argumentNumber);
  721. if (const ObjCStringRegion *SR =
  722. dyn_cast_or_null<ObjCStringRegion>(svTitle.getAsRegion())) {
  723. StringRef stringValue =
  724. SR->getObjCStringLiteral()->getString()->getString();
  725. if ((stringValue.trim().size() == 0 && stringValue.size() > 0) ||
  726. stringValue.empty())
  727. return;
  728. if (!IsAggressive && llvm::sys::unicode::columnWidthUTF8(stringValue) < 2)
  729. return;
  730. }
  731. bool isNonLocalized = hasNonLocalizedState(svTitle, C);
  732. if (isNonLocalized) {
  733. reportLocalizationError(svTitle, msg, C, argumentNumber + 1);
  734. }
  735. }
  736. void NonLocalizedStringChecker::checkPreCall(const CallEvent &Call,
  737. CheckerContext &C) const {
  738. const Decl *D = Call.getDecl();
  739. if (D && isa<FunctionDecl>(D)) {
  740. const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
  741. auto formals = FD->parameters();
  742. for (unsigned i = 0,
  743. ei = std::min(unsigned(formals.size()), Call.getNumArgs());
  744. i != ei; ++i) {
  745. if (isAnnotatedAsTakingLocalized(formals[i])) {
  746. auto actual = Call.getArgSVal(i);
  747. if (hasNonLocalizedState(actual, C)) {
  748. reportLocalizationError(actual, Call, C, i + 1);
  749. }
  750. }
  751. }
  752. }
  753. }
  754. static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
  755. const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
  756. if (!PT)
  757. return false;
  758. ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
  759. if (!Cls)
  760. return false;
  761. IdentifierInfo *ClsName = Cls->getIdentifier();
  762. // FIXME: Should we walk the chain of classes?
  763. return ClsName == &Ctx.Idents.get("NSString") ||
  764. ClsName == &Ctx.Idents.get("NSMutableString");
  765. }
  766. /// Marks a string being returned by any call as localized
  767. /// if it is in LocStringFunctions (LSF) or the function is annotated.
  768. /// Otherwise, we mark it as NonLocalized (Aggressive) or
  769. /// NonLocalized only if it is not backed by a SymRegion (Non-Aggressive),
  770. /// basically leaving only string literals as NonLocalized.
  771. void NonLocalizedStringChecker::checkPostCall(const CallEvent &Call,
  772. CheckerContext &C) const {
  773. initLocStringsMethods(C.getASTContext());
  774. if (!Call.getOriginExpr())
  775. return;
  776. // Anything that takes in a localized NSString as an argument
  777. // and returns an NSString will be assumed to be returning a
  778. // localized NSString. (Counter: Incorrectly combining two LocalizedStrings)
  779. const QualType RT = Call.getResultType();
  780. if (isNSStringType(RT, C.getASTContext())) {
  781. for (unsigned i = 0; i < Call.getNumArgs(); ++i) {
  782. SVal argValue = Call.getArgSVal(i);
  783. if (hasLocalizedState(argValue, C)) {
  784. SVal sv = Call.getReturnValue();
  785. setLocalizedState(sv, C);
  786. return;
  787. }
  788. }
  789. }
  790. const Decl *D = Call.getDecl();
  791. if (!D)
  792. return;
  793. const IdentifierInfo *Identifier = Call.getCalleeIdentifier();
  794. SVal sv = Call.getReturnValue();
  795. if (isAnnotatedAsReturningLocalized(D) || LSF.count(Identifier) != 0) {
  796. setLocalizedState(sv, C);
  797. } else if (isNSStringType(RT, C.getASTContext()) &&
  798. !hasLocalizedState(sv, C)) {
  799. if (IsAggressive) {
  800. setNonLocalizedState(sv, C);
  801. } else {
  802. const SymbolicRegion *SymReg =
  803. dyn_cast_or_null<SymbolicRegion>(sv.getAsRegion());
  804. if (!SymReg)
  805. setNonLocalizedState(sv, C);
  806. }
  807. }
  808. }
  809. /// Marks a string being returned by an ObjC method as localized
  810. /// if it is in LocStringMethods or the method is annotated
  811. void NonLocalizedStringChecker::checkPostObjCMessage(const ObjCMethodCall &msg,
  812. CheckerContext &C) const {
  813. initLocStringsMethods(C.getASTContext());
  814. if (!msg.isInstanceMessage())
  815. return;
  816. const ObjCInterfaceDecl *OD = msg.getReceiverInterface();
  817. if (!OD)
  818. return;
  819. const IdentifierInfo *odInfo = OD->getIdentifier();
  820. Selector S = msg.getSelector();
  821. std::string SelectorName = S.getAsString();
  822. std::pair<const IdentifierInfo *, Selector> MethodDescription = {odInfo, S};
  823. if (LSM.count(MethodDescription) ||
  824. isAnnotatedAsReturningLocalized(msg.getDecl())) {
  825. SVal sv = msg.getReturnValue();
  826. setLocalizedState(sv, C);
  827. }
  828. }
  829. /// Marks all empty string literals as localized
  830. void NonLocalizedStringChecker::checkPostStmt(const ObjCStringLiteral *SL,
  831. CheckerContext &C) const {
  832. SVal sv = C.getSVal(SL);
  833. setNonLocalizedState(sv, C);
  834. }
  835. std::shared_ptr<PathDiagnosticPiece>
  836. NonLocalizedStringBRVisitor::VisitNode(const ExplodedNode *Succ,
  837. const ExplodedNode *Pred,
  838. BugReporterContext &BRC, BugReport &BR) {
  839. if (Satisfied)
  840. return nullptr;
  841. Optional<StmtPoint> Point = Succ->getLocation().getAs<StmtPoint>();
  842. if (!Point.hasValue())
  843. return nullptr;
  844. auto *LiteralExpr = dyn_cast<ObjCStringLiteral>(Point->getStmt());
  845. if (!LiteralExpr)
  846. return nullptr;
  847. SVal LiteralSVal = Succ->getSVal(LiteralExpr);
  848. if (LiteralSVal.getAsRegion() != NonLocalizedString)
  849. return nullptr;
  850. Satisfied = true;
  851. PathDiagnosticLocation L =
  852. PathDiagnosticLocation::create(*Point, BRC.getSourceManager());
  853. if (!L.isValid() || !L.asLocation().isValid())
  854. return nullptr;
  855. auto Piece = std::make_shared<PathDiagnosticEventPiece>(
  856. L, "Non-localized string literal here");
  857. Piece->addRange(LiteralExpr->getSourceRange());
  858. return std::move(Piece);
  859. }
  860. namespace {
  861. class EmptyLocalizationContextChecker
  862. : public Checker<check::ASTDecl<ObjCImplementationDecl>> {
  863. // A helper class, which walks the AST
  864. class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
  865. const ObjCMethodDecl *MD;
  866. BugReporter &BR;
  867. AnalysisManager &Mgr;
  868. const CheckerBase *Checker;
  869. LocationOrAnalysisDeclContext DCtx;
  870. public:
  871. MethodCrawler(const ObjCMethodDecl *InMD, BugReporter &InBR,
  872. const CheckerBase *Checker, AnalysisManager &InMgr,
  873. AnalysisDeclContext *InDCtx)
  874. : MD(InMD), BR(InBR), Mgr(InMgr), Checker(Checker), DCtx(InDCtx) {}
  875. void VisitStmt(const Stmt *S) { VisitChildren(S); }
  876. void VisitObjCMessageExpr(const ObjCMessageExpr *ME);
  877. void reportEmptyContextError(const ObjCMessageExpr *M) const;
  878. void VisitChildren(const Stmt *S) {
  879. for (const Stmt *Child : S->children()) {
  880. if (Child)
  881. this->Visit(Child);
  882. }
  883. }
  884. };
  885. public:
  886. void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager &Mgr,
  887. BugReporter &BR) const;
  888. };
  889. } // end anonymous namespace
  890. void EmptyLocalizationContextChecker::checkASTDecl(
  891. const ObjCImplementationDecl *D, AnalysisManager &Mgr,
  892. BugReporter &BR) const {
  893. for (const ObjCMethodDecl *M : D->methods()) {
  894. AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
  895. const Stmt *Body = M->getBody();
  896. assert(Body);
  897. MethodCrawler MC(M->getCanonicalDecl(), BR, this, Mgr, DCtx);
  898. MC.VisitStmt(Body);
  899. }
  900. }
  901. /// This check attempts to match these macros, assuming they are defined as
  902. /// follows:
  903. ///
  904. /// #define NSLocalizedString(key, comment) \
  905. /// [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]
  906. /// #define NSLocalizedStringFromTable(key, tbl, comment) \
  907. /// [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)]
  908. /// #define NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment) \
  909. /// [bundle localizedStringForKey:(key) value:@"" table:(tbl)]
  910. /// #define NSLocalizedStringWithDefaultValue(key, tbl, bundle, val, comment)
  911. ///
  912. /// We cannot use the path sensitive check because the macro argument we are
  913. /// checking for (comment) is not used and thus not present in the AST,
  914. /// so we use Lexer on the original macro call and retrieve the value of
  915. /// the comment. If it's empty or nil, we raise a warning.
  916. void EmptyLocalizationContextChecker::MethodCrawler::VisitObjCMessageExpr(
  917. const ObjCMessageExpr *ME) {
  918. // FIXME: We may be able to use PPCallbacks to check for empy context
  919. // comments as part of preprocessing and avoid this re-lexing hack.
  920. const ObjCInterfaceDecl *OD = ME->getReceiverInterface();
  921. if (!OD)
  922. return;
  923. const IdentifierInfo *odInfo = OD->getIdentifier();
  924. if (!(odInfo->isStr("NSBundle") &&
  925. ME->getSelector().getAsString() ==
  926. "localizedStringForKey:value:table:")) {
  927. return;
  928. }
  929. SourceRange R = ME->getSourceRange();
  930. if (!R.getBegin().isMacroID())
  931. return;
  932. // getImmediateMacroCallerLoc gets the location of the immediate macro
  933. // caller, one level up the stack toward the initial macro typed into the
  934. // source, so SL should point to the NSLocalizedString macro.
  935. SourceLocation SL =
  936. Mgr.getSourceManager().getImmediateMacroCallerLoc(R.getBegin());
  937. std::pair<FileID, unsigned> SLInfo =
  938. Mgr.getSourceManager().getDecomposedLoc(SL);
  939. SrcMgr::SLocEntry SE = Mgr.getSourceManager().getSLocEntry(SLInfo.first);
  940. // If NSLocalizedString macro is wrapped in another macro, we need to
  941. // unwrap the expansion until we get to the NSLocalizedStringMacro.
  942. while (SE.isExpansion()) {
  943. SL = SE.getExpansion().getSpellingLoc();
  944. SLInfo = Mgr.getSourceManager().getDecomposedLoc(SL);
  945. SE = Mgr.getSourceManager().getSLocEntry(SLInfo.first);
  946. }
  947. bool Invalid = false;
  948. llvm::MemoryBuffer *BF =
  949. Mgr.getSourceManager().getBuffer(SLInfo.first, SL, &Invalid);
  950. if (Invalid)
  951. return;
  952. Lexer TheLexer(SL, LangOptions(), BF->getBufferStart(),
  953. BF->getBufferStart() + SLInfo.second, BF->getBufferEnd());
  954. Token I;
  955. Token Result; // This will hold the token just before the last ')'
  956. int p_count = 0; // This is for parenthesis matching
  957. while (!TheLexer.LexFromRawLexer(I)) {
  958. if (I.getKind() == tok::l_paren)
  959. ++p_count;
  960. if (I.getKind() == tok::r_paren) {
  961. if (p_count == 1)
  962. break;
  963. --p_count;
  964. }
  965. Result = I;
  966. }
  967. if (isAnyIdentifier(Result.getKind())) {
  968. if (Result.getRawIdentifier().equals("nil")) {
  969. reportEmptyContextError(ME);
  970. return;
  971. }
  972. }
  973. if (!isStringLiteral(Result.getKind()))
  974. return;
  975. StringRef Comment =
  976. StringRef(Result.getLiteralData(), Result.getLength()).trim('"');
  977. if ((Comment.trim().size() == 0 && Comment.size() > 0) || // Is Whitespace
  978. Comment.empty()) {
  979. reportEmptyContextError(ME);
  980. }
  981. }
  982. void EmptyLocalizationContextChecker::MethodCrawler::reportEmptyContextError(
  983. const ObjCMessageExpr *ME) const {
  984. // Generate the bug report.
  985. BR.EmitBasicReport(MD, Checker, "Context Missing",
  986. "Localizability Issue (Apple)",
  987. "Localized string macro should include a non-empty "
  988. "comment for translators",
  989. PathDiagnosticLocation(ME, BR.getSourceManager(), DCtx));
  990. }
  991. namespace {
  992. class PluralMisuseChecker : public Checker<check::ASTCodeBody> {
  993. // A helper class, which walks the AST
  994. class MethodCrawler : public RecursiveASTVisitor<MethodCrawler> {
  995. BugReporter &BR;
  996. const CheckerBase *Checker;
  997. AnalysisDeclContext *AC;
  998. // This functions like a stack. We push on any IfStmt or
  999. // ConditionalOperator that matches the condition
  1000. // and pop it off when we leave that statement
  1001. llvm::SmallVector<const clang::Stmt *, 8> MatchingStatements;
  1002. // This is true when we are the direct-child of a
  1003. // matching statement
  1004. bool InMatchingStatement = false;
  1005. public:
  1006. explicit MethodCrawler(BugReporter &InBR, const CheckerBase *Checker,
  1007. AnalysisDeclContext *InAC)
  1008. : BR(InBR), Checker(Checker), AC(InAC) {}
  1009. bool VisitIfStmt(const IfStmt *I);
  1010. bool EndVisitIfStmt(IfStmt *I);
  1011. bool TraverseIfStmt(IfStmt *x);
  1012. bool VisitConditionalOperator(const ConditionalOperator *C);
  1013. bool TraverseConditionalOperator(ConditionalOperator *C);
  1014. bool VisitCallExpr(const CallExpr *CE);
  1015. bool VisitObjCMessageExpr(const ObjCMessageExpr *ME);
  1016. private:
  1017. void reportPluralMisuseError(const Stmt *S) const;
  1018. bool isCheckingPlurality(const Expr *E) const;
  1019. };
  1020. public:
  1021. void checkASTCodeBody(const Decl *D, AnalysisManager &Mgr,
  1022. BugReporter &BR) const {
  1023. MethodCrawler Visitor(BR, this, Mgr.getAnalysisDeclContext(D));
  1024. Visitor.TraverseDecl(const_cast<Decl *>(D));
  1025. }
  1026. };
  1027. } // end anonymous namespace
  1028. // Checks the condition of the IfStmt and returns true if one
  1029. // of the following heuristics are met:
  1030. // 1) The conidtion is a variable with "singular" or "plural" in the name
  1031. // 2) The condition is a binary operator with 1 or 2 on the right-hand side
  1032. bool PluralMisuseChecker::MethodCrawler::isCheckingPlurality(
  1033. const Expr *Condition) const {
  1034. const BinaryOperator *BO = nullptr;
  1035. // Accounts for when a VarDecl represents a BinaryOperator
  1036. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Condition)) {
  1037. if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
  1038. const Expr *InitExpr = VD->getInit();
  1039. if (InitExpr) {
  1040. if (const BinaryOperator *B =
  1041. dyn_cast<BinaryOperator>(InitExpr->IgnoreParenImpCasts())) {
  1042. BO = B;
  1043. }
  1044. }
  1045. if (VD->getName().lower().find("plural") != StringRef::npos ||
  1046. VD->getName().lower().find("singular") != StringRef::npos) {
  1047. return true;
  1048. }
  1049. }
  1050. } else if (const BinaryOperator *B = dyn_cast<BinaryOperator>(Condition)) {
  1051. BO = B;
  1052. }
  1053. if (BO == nullptr)
  1054. return false;
  1055. if (IntegerLiteral *IL = dyn_cast_or_null<IntegerLiteral>(
  1056. BO->getRHS()->IgnoreParenImpCasts())) {
  1057. llvm::APInt Value = IL->getValue();
  1058. if (Value == 1 || Value == 2) {
  1059. return true;
  1060. }
  1061. }
  1062. return false;
  1063. }
  1064. // A CallExpr with "LOC" in its identifier that takes in a string literal
  1065. // has been shown to almost always be a function that returns a localized
  1066. // string. Raise a diagnostic when this is in a statement that matches
  1067. // the condition.
  1068. bool PluralMisuseChecker::MethodCrawler::VisitCallExpr(const CallExpr *CE) {
  1069. if (InMatchingStatement) {
  1070. if (const FunctionDecl *FD = CE->getDirectCallee()) {
  1071. std::string NormalizedName =
  1072. StringRef(FD->getNameInfo().getAsString()).lower();
  1073. if (NormalizedName.find("loc") != std::string::npos) {
  1074. for (const Expr *Arg : CE->arguments()) {
  1075. if (isa<ObjCStringLiteral>(Arg))
  1076. reportPluralMisuseError(CE);
  1077. }
  1078. }
  1079. }
  1080. }
  1081. return true;
  1082. }
  1083. // The other case is for NSLocalizedString which also returns
  1084. // a localized string. It's a macro for the ObjCMessageExpr
  1085. // [NSBundle localizedStringForKey:value:table:] Raise a
  1086. // diagnostic when this is in a statement that matches
  1087. // the condition.
  1088. bool PluralMisuseChecker::MethodCrawler::VisitObjCMessageExpr(
  1089. const ObjCMessageExpr *ME) {
  1090. const ObjCInterfaceDecl *OD = ME->getReceiverInterface();
  1091. if (!OD)
  1092. return true;
  1093. const IdentifierInfo *odInfo = OD->getIdentifier();
  1094. if (odInfo->isStr("NSBundle") &&
  1095. ME->getSelector().getAsString() == "localizedStringForKey:value:table:") {
  1096. if (InMatchingStatement) {
  1097. reportPluralMisuseError(ME);
  1098. }
  1099. }
  1100. return true;
  1101. }
  1102. /// Override TraverseIfStmt so we know when we are done traversing an IfStmt
  1103. bool PluralMisuseChecker::MethodCrawler::TraverseIfStmt(IfStmt *I) {
  1104. RecursiveASTVisitor<MethodCrawler>::TraverseIfStmt(I);
  1105. return EndVisitIfStmt(I);
  1106. }
  1107. // EndVisit callbacks are not provided by the RecursiveASTVisitor
  1108. // so we override TraverseIfStmt and make a call to EndVisitIfStmt
  1109. // after traversing the IfStmt
  1110. bool PluralMisuseChecker::MethodCrawler::EndVisitIfStmt(IfStmt *I) {
  1111. MatchingStatements.pop_back();
  1112. if (!MatchingStatements.empty()) {
  1113. if (MatchingStatements.back() != nullptr) {
  1114. InMatchingStatement = true;
  1115. return true;
  1116. }
  1117. }
  1118. InMatchingStatement = false;
  1119. return true;
  1120. }
  1121. bool PluralMisuseChecker::MethodCrawler::VisitIfStmt(const IfStmt *I) {
  1122. const Expr *Condition = I->getCond()->IgnoreParenImpCasts();
  1123. if (isCheckingPlurality(Condition)) {
  1124. MatchingStatements.push_back(I);
  1125. InMatchingStatement = true;
  1126. } else {
  1127. MatchingStatements.push_back(nullptr);
  1128. InMatchingStatement = false;
  1129. }
  1130. return true;
  1131. }
  1132. // Preliminary support for conditional operators.
  1133. bool PluralMisuseChecker::MethodCrawler::TraverseConditionalOperator(
  1134. ConditionalOperator *C) {
  1135. RecursiveASTVisitor<MethodCrawler>::TraverseConditionalOperator(C);
  1136. MatchingStatements.pop_back();
  1137. if (!MatchingStatements.empty()) {
  1138. if (MatchingStatements.back() != nullptr)
  1139. InMatchingStatement = true;
  1140. else
  1141. InMatchingStatement = false;
  1142. } else {
  1143. InMatchingStatement = false;
  1144. }
  1145. return true;
  1146. }
  1147. bool PluralMisuseChecker::MethodCrawler::VisitConditionalOperator(
  1148. const ConditionalOperator *C) {
  1149. const Expr *Condition = C->getCond()->IgnoreParenImpCasts();
  1150. if (isCheckingPlurality(Condition)) {
  1151. MatchingStatements.push_back(C);
  1152. InMatchingStatement = true;
  1153. } else {
  1154. MatchingStatements.push_back(nullptr);
  1155. InMatchingStatement = false;
  1156. }
  1157. return true;
  1158. }
  1159. void PluralMisuseChecker::MethodCrawler::reportPluralMisuseError(
  1160. const Stmt *S) const {
  1161. // Generate the bug report.
  1162. BR.EmitBasicReport(AC->getDecl(), Checker, "Plural Misuse",
  1163. "Localizability Issue (Apple)",
  1164. "Plural cases are not supported accross all languages. "
  1165. "Use a .stringsdict file instead",
  1166. PathDiagnosticLocation(S, BR.getSourceManager(), AC));
  1167. }
  1168. //===----------------------------------------------------------------------===//
  1169. // Checker registration.
  1170. //===----------------------------------------------------------------------===//
  1171. void ento::registerNonLocalizedStringChecker(CheckerManager &mgr) {
  1172. NonLocalizedStringChecker *checker =
  1173. mgr.registerChecker<NonLocalizedStringChecker>();
  1174. checker->IsAggressive =
  1175. mgr.getAnalyzerOptions().getBooleanOption("AggressiveReport", false);
  1176. }
  1177. void ento::registerEmptyLocalizationContextChecker(CheckerManager &mgr) {
  1178. mgr.registerChecker<EmptyLocalizationContextChecker>();
  1179. }
  1180. void ento::registerPluralMisuseChecker(CheckerManager &mgr) {
  1181. mgr.registerChecker<PluralMisuseChecker>();
  1182. }