LocalizationChecker.cpp 52 KB

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