LocalizationChecker.cpp 48 KB

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