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