PRESUBMIT.py 309 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819
  1. # Copyright 2012 The Chromium Authors
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Top-level presubmit script for Chromium.
  5. See https://www.chromium.org/developers/how-tos/depottools/presubmit-scripts/
  6. for more details about the presubmit API built into depot_tools.
  7. """
  8. from typing import Callable
  9. from typing import Optional
  10. from typing import Sequence
  11. from typing import Tuple
  12. from dataclasses import dataclass
  13. PRESUBMIT_VERSION = '2.0.0'
  14. _EXCLUDED_PATHS = (
  15. # Generated file
  16. (r"chrome/android/webapk/shell_apk/src/org/chromium"
  17. r"/webapk/lib/runtime_library/IWebApkApi.java"),
  18. # File needs to write to stdout to emulate a tool it's replacing.
  19. r"chrome/updater/mac/keystone/ksadmin.mm",
  20. # Generated file.
  21. (r"^components/variations/proto/devtools/"
  22. r"client_variations.js"),
  23. # These are video files, not typescript.
  24. r"^media/test/data/.*.ts",
  25. r"^native_client_sdksrc/build_tools/make_rules.py",
  26. r"^native_client_sdk/src/build_tools/make_simple.py",
  27. r"^native_client_sdk/src/tools/.*.mk",
  28. r"^net/tools/spdyshark/.*",
  29. r"^skia/.*",
  30. r"^third_party/blink/.*",
  31. r"^third_party/breakpad/.*",
  32. # sqlite is an imported third party dependency.
  33. r"^third_party/sqlite/.*",
  34. r"^v8/.*",
  35. r".*MakeFile$",
  36. r".+_autogen\.h$",
  37. r".+_pb2(_grpc)?\.py$",
  38. r".+/pnacl_shim\.c$",
  39. r"^gpu/config/.*_list_json\.cc$",
  40. r"tools/md_browser/.*\.css$",
  41. # Test pages for Maps telemetry tests.
  42. r"tools/perf/page_sets/maps_perf_test.*",
  43. # Test pages for WebRTC telemetry tests.
  44. r"tools/perf/page_sets/webrtc_cases.*",
  45. # Test file compared with generated output.
  46. r"tools/polymer/tests/html_to_wrapper/.*.html.ts$",
  47. # Third-party dependency frozen at a fixed version.
  48. r"chrome/test/data/webui/chromeos/chai_v4.js$",
  49. )
  50. _EXCLUDED_SET_NO_PARENT_PATHS = (
  51. # It's for historical reasons that blink isn't a top level directory, where
  52. # it would be allowed to have "set noparent" to avoid top level owners
  53. # accidentally +1ing changes.
  54. 'third_party/blink/OWNERS',
  55. )
  56. # Fragment of a regular expression that matches C++ and Objective-C++
  57. # implementation files.
  58. _IMPLEMENTATION_EXTENSIONS = r'\.(cc|cpp|cxx|mm)$'
  59. # Fragment of a regular expression that matches C++ and Objective-C++
  60. # header files.
  61. _HEADER_EXTENSIONS = r'\.(h|hpp|hxx)$'
  62. # Paths with sources that don't use //base.
  63. _NON_BASE_DEPENDENT_PATHS = (
  64. r"^chrome/browser/browser_switcher/bho/",
  65. r"^tools/win/",
  66. )
  67. # Regular expression that matches code only used for test binaries
  68. # (best effort).
  69. _TEST_CODE_EXCLUDED_PATHS = (
  70. r'.*/(fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS,
  71. # Test support files, like:
  72. # foo_test_support.cc
  73. # bar_test_util_linux.cc (suffix)
  74. # baz_test_base.cc
  75. r'.+_test_(base|support|util)(_[a-z]+)?%s' % _IMPLEMENTATION_EXTENSIONS,
  76. # Test suite files, like:
  77. # foo_browsertest.cc
  78. # bar_unittest_mac.cc (suffix)
  79. # baz_unittests.cc (plural)
  80. r'.+_(api|browser|eg|int|perf|pixel|unit|ui)?test(s)?(_[a-z]+)?%s' %
  81. _IMPLEMENTATION_EXTENSIONS,
  82. r'.+_(fuzz|fuzzer)(_[a-z]+)?%s' % _IMPLEMENTATION_EXTENSIONS,
  83. r'.+sync_service_impl_harness%s' % _IMPLEMENTATION_EXTENSIONS,
  84. r'.*/(test|tool(s)?)/.*',
  85. # content_shell is used for running content_browsertests.
  86. r'content/shell/.*',
  87. # Web test harness.
  88. r'content/web_test/.*',
  89. # Non-production example code.
  90. r'mojo/examples/.*',
  91. # Launcher for running iOS tests on the simulator.
  92. r'testing/iossim/iossim\.mm$',
  93. # EarlGrey app side code for tests.
  94. r'ios/.*_app_interface\.mm$',
  95. # Views Examples code
  96. r'ui/views/examples/.*',
  97. # Chromium Codelab
  98. r'codelabs/*'
  99. )
  100. _THIRD_PARTY_EXCEPT_BLINK = 'third_party/(?!blink/)'
  101. _TEST_ONLY_WARNING = (
  102. 'You might be calling functions intended only for testing from\n'
  103. 'production code. If you are doing this from inside another method\n'
  104. 'named as *ForTesting(), then consider exposing things to have tests\n'
  105. 'make that same call directly.\n'
  106. 'If that is not possible, you may put a comment on the same line with\n'
  107. ' // IN-TEST \n'
  108. 'to tell the PRESUBMIT script that the code is inside a *ForTesting()\n'
  109. 'method and can be ignored. Do not do this inside production code.\n'
  110. 'The android-binary-size trybot will block if the method exists in the\n'
  111. 'release apk.\n'
  112. 'Note: this warning might be a false positive (crbug.com/1196548).')
  113. @dataclass
  114. class BanRule:
  115. # String pattern. If the pattern begins with a slash, the pattern will be
  116. # treated as a regular expression instead.
  117. pattern: str
  118. # Explanation as a sequence of strings. Each string in the sequence will be
  119. # printed on its own line.
  120. explanation: Tuple[str, ...]
  121. # Whether or not to treat this ban as a fatal error. If unspecified,
  122. # defaults to true.
  123. treat_as_error: Optional[bool] = None
  124. # Paths that should be excluded from the ban check. Each string is a regular
  125. # expression that will be matched against the path of the file being checked
  126. # relative to the root of the source tree.
  127. excluded_paths: Optional[Sequence[str]] = None
  128. _BANNED_JAVA_IMPORTS : Sequence[BanRule] = (
  129. BanRule(
  130. 'import java.net.URI;',
  131. (
  132. 'Use org.chromium.url.GURL instead of java.net.URI, where possible.',
  133. ),
  134. excluded_paths=(
  135. (r'net/android/javatests/src/org/chromium/net/'
  136. 'AndroidProxySelectorTest\.java'),
  137. r'components/cronet/',
  138. r'third_party/robolectric/local/',
  139. ),
  140. ),
  141. BanRule(
  142. 'import android.annotation.TargetApi;',
  143. (
  144. 'Do not use TargetApi, use @androidx.annotation.RequiresApi instead. '
  145. 'RequiresApi ensures that any calls are guarded by the appropriate '
  146. 'SDK_INT check. See https://crbug.com/1116486.',
  147. ),
  148. ),
  149. BanRule(
  150. 'import androidx.test.rule.ActivityTestRule;',
  151. (
  152. 'Do not use ActivityTestRule, use '
  153. 'org.chromium.base.test.BaseActivityTestRule instead.',
  154. ),
  155. excluded_paths=(
  156. 'components/cronet/',
  157. ),
  158. ),
  159. BanRule(
  160. 'import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;',
  161. (
  162. 'Do not use VectorDrawableCompat, use getResources().getDrawable() to '
  163. 'avoid extra indirections. Please also add trace event as the call '
  164. 'might take more than 20 ms to complete.',
  165. ),
  166. ),
  167. )
  168. _BANNED_JAVA_FUNCTIONS : Sequence[BanRule] = (
  169. BanRule(
  170. 'StrictMode.allowThreadDiskReads()',
  171. (
  172. 'Prefer using StrictModeContext.allowDiskReads() to using StrictMode '
  173. 'directly.',
  174. ),
  175. False,
  176. ),
  177. BanRule(
  178. 'StrictMode.allowThreadDiskWrites()',
  179. (
  180. 'Prefer using StrictModeContext.allowDiskWrites() to using StrictMode '
  181. 'directly.',
  182. ),
  183. False,
  184. ),
  185. BanRule(
  186. '.waitForIdleSync()',
  187. (
  188. 'Do not use waitForIdleSync as it masks underlying issues. There is '
  189. 'almost always something else you should wait on instead.',
  190. ),
  191. False,
  192. ),
  193. BanRule(
  194. r'/(?<!\bsuper\.)(?<!\bIntent )\bregisterReceiver\(',
  195. (
  196. 'Do not call android.content.Context.registerReceiver (or an override) '
  197. 'directly. Use one of the wrapper methods defined in '
  198. 'org.chromium.base.ContextUtils, such as '
  199. 'registerProtectedBroadcastReceiver, '
  200. 'registerExportedBroadcastReceiver, or '
  201. 'registerNonExportedBroadcastReceiver. See their documentation for '
  202. 'which one to use.',
  203. ),
  204. True,
  205. excluded_paths=(
  206. r'.*Test[^a-z]',
  207. r'third_party/',
  208. 'base/android/java/src/org/chromium/base/ContextUtils.java',
  209. 'chromecast/browser/android/apk/src/org/chromium/chromecast/shell/BroadcastReceiverScope.java',
  210. ),
  211. ),
  212. BanRule(
  213. r'/(?:extends|new)\s*(?:android.util.)?Property<[A-Za-z.]+,\s*(?:Integer|Float)>',
  214. (
  215. 'Do not use Property<..., Integer|Float>, but use FloatProperty or '
  216. 'IntProperty because it will avoid unnecessary autoboxing of '
  217. 'primitives.',
  218. ),
  219. ),
  220. BanRule(
  221. 'requestLayout()',
  222. (
  223. 'Layouts can be expensive. Prefer using ViewUtils.requestLayout(), '
  224. 'which emits a trace event with additional information to help with '
  225. 'scroll jank investigations. See http://crbug.com/1354176.',
  226. ),
  227. False,
  228. excluded_paths=(
  229. 'ui/android/java/src/org/chromium/ui/base/ViewUtils.java',
  230. ),
  231. ),
  232. BanRule(
  233. 'ProfileManager.getLastUsedRegularProfile()',
  234. (
  235. 'Prefer passing in the Profile reference instead of relying on the '
  236. 'static getLastUsedRegularProfile() call. Only top level entry points '
  237. '(e.g. Activities) should call this method. Otherwise, the Profile '
  238. 'should either be passed in explicitly or retreived from an existing '
  239. 'entity with a reference to the Profile (e.g. WebContents).',
  240. ),
  241. False,
  242. excluded_paths=(
  243. r'.*Test[A-Z]?.*\.java',
  244. ),
  245. ),
  246. BanRule(
  247. r'/(ResourcesCompat|getResources\(\))\.getDrawable\(\)',
  248. (
  249. 'getDrawable() can be expensive. If you have a lot of calls to '
  250. 'GetDrawable() or your code may introduce janks, please put your calls '
  251. 'inside a trace().',
  252. ),
  253. False,
  254. excluded_paths=(
  255. r'.*Test[A-Z]?.*\.java',
  256. ),
  257. ),
  258. BanRule(
  259. r'/RecordHistogram\.getHistogram(ValueCount|TotalCount|Samples)ForTesting\(',
  260. (
  261. 'Raw histogram counts are easy to misuse; for example they don\'t reset '
  262. 'between batched tests. Use HistogramWatcher to check histogram records '
  263. 'instead.',
  264. ),
  265. False,
  266. excluded_paths=(
  267. 'base/android/javatests/src/org/chromium/base/metrics/RecordHistogramTest.java',
  268. 'base/test/android/javatests/src/org/chromium/base/test/util/HistogramWatcher.java',
  269. ),
  270. ),
  271. )
  272. _BANNED_JAVASCRIPT_FUNCTIONS : Sequence [BanRule] = (
  273. BanRule(
  274. r'/\bchrome\.send\b',
  275. (
  276. 'The use of chrome.send is disallowed in Chrome (context: https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/security/handling-messages-from-web-content.md).',
  277. 'Please use mojo instead for new webuis. https://docs.google.com/document/d/1RF-GSUoveYa37eoyZ9EhwMtaIwoW7Z88pIgNZ9YzQi4/edit#heading=h.gkk22wgk6wff',
  278. ),
  279. True,
  280. (
  281. r'^(?!ash\/webui).+',
  282. # TODO(crbug.com/1385601): pre-existing violations still need to be
  283. # cleaned up.
  284. 'ash/webui/common/resources/cr.m.js',
  285. 'ash/webui/common/resources/multidevice_setup/multidevice_setup_browser_proxy.js',
  286. 'ash/webui/common/resources/quick_unlock/lock_screen_constants.ts',
  287. 'ash/webui/common/resources/smb_shares/smb_browser_proxy.js',
  288. 'ash/webui/connectivity_diagnostics/resources/connectivity_diagnostics.ts',
  289. 'ash/webui/diagnostics_ui/resources/diagnostics_browser_proxy.ts',
  290. 'ash/webui/multidevice_debug/resources/logs.js',
  291. 'ash/webui/multidevice_debug/resources/webui.js',
  292. 'ash/webui/projector_app/resources/annotator/trusted/annotator_browser_proxy.js',
  293. 'ash/webui/projector_app/resources/app/trusted/projector_browser_proxy.js',
  294. # TODO(b/301634378): Remove violation exception once Scanning App
  295. # migrated off usage of `chrome.send`.
  296. 'ash/webui/scanning/resources/scanning_browser_proxy.ts',
  297. ),
  298. ),
  299. )
  300. _BANNED_OBJC_FUNCTIONS : Sequence[BanRule] = (
  301. BanRule(
  302. 'addTrackingRect:',
  303. (
  304. 'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
  305. 'prohibited. Please use CrTrackingArea instead.',
  306. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  307. ),
  308. False,
  309. ),
  310. BanRule(
  311. r'/NSTrackingArea\W',
  312. (
  313. 'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
  314. 'instead.',
  315. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  316. ),
  317. False,
  318. ),
  319. BanRule(
  320. 'convertPointFromBase:',
  321. (
  322. 'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
  323. 'Please use |convertPoint:(point) fromView:nil| instead.',
  324. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  325. ),
  326. True,
  327. ),
  328. BanRule(
  329. 'convertPointToBase:',
  330. (
  331. 'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
  332. 'Please use |convertPoint:(point) toView:nil| instead.',
  333. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  334. ),
  335. True,
  336. ),
  337. BanRule(
  338. 'convertRectFromBase:',
  339. (
  340. 'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
  341. 'Please use |convertRect:(point) fromView:nil| instead.',
  342. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  343. ),
  344. True,
  345. ),
  346. BanRule(
  347. 'convertRectToBase:',
  348. (
  349. 'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
  350. 'Please use |convertRect:(point) toView:nil| instead.',
  351. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  352. ),
  353. True,
  354. ),
  355. BanRule(
  356. 'convertSizeFromBase:',
  357. (
  358. 'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
  359. 'Please use |convertSize:(point) fromView:nil| instead.',
  360. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  361. ),
  362. True,
  363. ),
  364. BanRule(
  365. 'convertSizeToBase:',
  366. (
  367. 'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
  368. 'Please use |convertSize:(point) toView:nil| instead.',
  369. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  370. ),
  371. True,
  372. ),
  373. BanRule(
  374. r"/\s+UTF8String\s*]",
  375. (
  376. 'The use of -[NSString UTF8String] is dangerous as it can return null',
  377. 'even if |canBeConvertedToEncoding:NSUTF8StringEncoding| returns YES.',
  378. 'Please use |SysNSStringToUTF8| instead.',
  379. ),
  380. True,
  381. excluded_paths = (
  382. '^third_party/ocmock/OCMock/',
  383. ),
  384. ),
  385. BanRule(
  386. r'__unsafe_unretained',
  387. (
  388. 'The use of __unsafe_unretained is almost certainly wrong, unless',
  389. 'when interacting with NSFastEnumeration or NSInvocation.',
  390. 'Please use __weak in files build with ARC, nothing otherwise.',
  391. ),
  392. False,
  393. ),
  394. BanRule(
  395. 'freeWhenDone:NO',
  396. (
  397. 'The use of "freeWhenDone:NO" with the NoCopy creation of ',
  398. 'Foundation types is prohibited.',
  399. ),
  400. True,
  401. ),
  402. BanRule(
  403. 'This file requires ARC support.',
  404. (
  405. 'ARC compilation is default in Chromium; do not add boilerplate to ',
  406. 'files that require ARC.',
  407. ),
  408. True,
  409. ),
  410. )
  411. _BANNED_IOS_OBJC_FUNCTIONS = (
  412. BanRule(
  413. r'/\bTEST[(]',
  414. (
  415. 'TEST() macro should not be used in Objective-C++ code as it does not ',
  416. 'drain the autorelease pool at the end of the test. Use TEST_F() ',
  417. 'macro instead with a fixture inheriting from PlatformTest (or a ',
  418. 'typedef).'
  419. ),
  420. True,
  421. ),
  422. BanRule(
  423. r'/\btesting::Test\b',
  424. (
  425. 'testing::Test should not be used in Objective-C++ code as it does ',
  426. 'not drain the autorelease pool at the end of the test. Use ',
  427. 'PlatformTest instead.'
  428. ),
  429. True,
  430. ),
  431. BanRule(
  432. ' systemImageNamed:',
  433. (
  434. '+[UIImage systemImageNamed:] should not be used to create symbols.',
  435. 'Instead use a wrapper defined in:',
  436. 'ios/chrome/browser/shared/ui/symbols/symbol_helpers.h'
  437. ),
  438. True,
  439. excluded_paths=(
  440. 'ios/chrome/browser/shared/ui/symbols/symbol_helpers.mm',
  441. 'ios/chrome/common',
  442. # App extensions have restricted dependencies and thus can't use the
  443. # wrappers.
  444. '^ios/chrome/\w+_extension/',
  445. ),
  446. ),
  447. BanRule(
  448. r'public (RefCounted)?BrowserStateKeyedServiceFactory',
  449. (
  450. 'KeyedService factories in //ios/chrome/browser should inherit from',
  451. '(Refcounted)?ProfileKeyedServieFactoryIOS, not directory from',
  452. '(Refcounted)?BrowserStateKeyedServiceFactory.'
  453. ),
  454. treat_as_error=True,
  455. excluded_paths=(
  456. 'ios/components',
  457. 'ios/web_view',
  458. ),
  459. ),
  460. )
  461. _BANNED_IOS_EGTEST_FUNCTIONS : Sequence[BanRule] = (
  462. BanRule(
  463. r'/\bEXPECT_OCMOCK_VERIFY\b',
  464. (
  465. 'EXPECT_OCMOCK_VERIFY should not be used in EarlGrey tests because ',
  466. 'it is meant for GTests. Use [mock verify] instead.'
  467. ),
  468. True,
  469. ),
  470. )
  471. _BANNED_CPP_FUNCTIONS: Sequence[BanRule] = (
  472. BanRule(
  473. '%#0',
  474. (
  475. 'Zero-padded values that use "#" to add prefixes don\'t exhibit ',
  476. 'consistent behavior, since the prefix is not prepended for zero ',
  477. 'values. Use "0x%0..." instead.',
  478. ),
  479. False,
  480. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  481. ),
  482. BanRule(
  483. r'/\busing namespace ',
  484. (
  485. 'Using directives ("using namespace x") are banned by the Google Style',
  486. 'Guide ( http://google.github.io/styleguide/cppguide.html#Namespaces ).',
  487. 'Explicitly qualify symbols or use using declarations ("using x::foo").',
  488. ),
  489. True,
  490. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  491. ),
  492. # Make sure that gtest's FRIEND_TEST() macro is not used; the
  493. # FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
  494. # used instead since that allows for FLAKY_ and DISABLED_ prefixes.
  495. BanRule(
  496. 'FRIEND_TEST(',
  497. (
  498. 'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
  499. 'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
  500. ),
  501. False,
  502. excluded_paths=(
  503. "base/gtest_prod_util.h",
  504. "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/gtest_prod_util.h",
  505. ),
  506. ),
  507. BanRule(
  508. 'setMatrixClip',
  509. (
  510. 'Overriding setMatrixClip() is prohibited; ',
  511. 'the base function is deprecated. ',
  512. ),
  513. True,
  514. (),
  515. ),
  516. BanRule(
  517. 'SkRefPtr',
  518. ('The use of SkRefPtr is prohibited. ', 'Please use sk_sp<> instead.'),
  519. True,
  520. (),
  521. ),
  522. BanRule(
  523. 'SkAutoRef',
  524. ('The indirect use of SkRefPtr via SkAutoRef is prohibited. ',
  525. 'Please use sk_sp<> instead.'),
  526. True,
  527. (),
  528. ),
  529. BanRule(
  530. 'SkAutoTUnref',
  531. ('The use of SkAutoTUnref is dangerous because it implicitly ',
  532. 'converts to a raw pointer. Please use sk_sp<> instead.'),
  533. True,
  534. (),
  535. ),
  536. BanRule(
  537. 'SkAutoUnref',
  538. ('The indirect use of SkAutoTUnref through SkAutoUnref is dangerous ',
  539. 'because it implicitly converts to a raw pointer. ',
  540. 'Please use sk_sp<> instead.'),
  541. True,
  542. (),
  543. ),
  544. BanRule(
  545. r'/HANDLE_EINTR\(.*close',
  546. ('HANDLE_EINTR(close) is invalid. If close fails with EINTR, the file',
  547. 'descriptor will be closed, and it is incorrect to retry the close.',
  548. 'Either call close directly and ignore its return value, or wrap close',
  549. 'in IGNORE_EINTR to use its return value. See http://crbug.com/269623'
  550. ),
  551. True,
  552. (),
  553. ),
  554. BanRule(
  555. r'/IGNORE_EINTR\((?!.*close)',
  556. (
  557. 'IGNORE_EINTR is only valid when wrapping close. To wrap other system',
  558. 'calls, use HANDLE_EINTR. See http://crbug.com/269623',
  559. ),
  560. True,
  561. (
  562. # Files that #define IGNORE_EINTR.
  563. r'^base/posix/eintr_wrapper\.h$',
  564. r'^ppapi/tests/test_broker\.cc$',
  565. ),
  566. ),
  567. BanRule(
  568. r'/v8::Extension\(',
  569. (
  570. 'Do not introduce new v8::Extensions into the code base, use',
  571. 'gin::Wrappable instead. See http://crbug.com/334679',
  572. ),
  573. True,
  574. (r'extensions/renderer/safe_builtins\.*', ),
  575. ),
  576. BanRule(
  577. '#pragma comment(lib,',
  578. ('Specify libraries to link with in build files and not in the source.',
  579. ),
  580. True,
  581. (
  582. r'^base/third_party/symbolize/.*',
  583. r'^third_party/abseil-cpp/.*',
  584. ),
  585. ),
  586. BanRule(
  587. r'/base::SequenceChecker\b',
  588. ('Consider using SEQUENCE_CHECKER macros instead of the class directly.',
  589. ),
  590. False,
  591. (),
  592. ),
  593. BanRule(
  594. r'/base::ThreadChecker\b',
  595. ('Consider using THREAD_CHECKER macros instead of the class directly.',
  596. ),
  597. False,
  598. (),
  599. ),
  600. BanRule(
  601. r'/\b(?!(Sequenced|SingleThread))\w*TaskRunner::(GetCurrentDefault|CurrentDefaultHandle)',
  602. (
  603. 'It is not allowed to call these methods from the subclasses ',
  604. 'of Sequenced or SingleThread task runners.',
  605. ),
  606. True,
  607. (),
  608. ),
  609. BanRule(
  610. r'/(Time(|Delta|Ticks)|ThreadTicks)::FromInternalValue|ToInternalValue',
  611. (
  612. 'base::TimeXXX::FromInternalValue() and ToInternalValue() are',
  613. 'deprecated (http://crbug.com/634507). Please avoid converting away',
  614. 'from the Time types in Chromium code, especially if any math is',
  615. 'being done on time values. For interfacing with platform/library',
  616. 'APIs, use base::Time::(From,To)DeltaSinceWindowsEpoch() or',
  617. 'base::{TimeDelta::In}Microseconds(), or one of the other type',
  618. 'converter methods instead. For faking TimeXXX values (for unit',
  619. 'testing only), use TimeXXX() + Microseconds(N). For',
  620. 'other use cases, please contact base/time/OWNERS.',
  621. ),
  622. False,
  623. excluded_paths=(
  624. "base/time/time.h",
  625. "base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/time/time.h",
  626. ),
  627. ),
  628. BanRule(
  629. 'CallJavascriptFunctionUnsafe',
  630. (
  631. "Don't use CallJavascriptFunctionUnsafe() in new code. Instead, use",
  632. 'AllowJavascript(), OnJavascriptAllowed()/OnJavascriptDisallowed(),',
  633. 'and CallJavascriptFunction(). See https://goo.gl/qivavq.',
  634. ),
  635. False,
  636. (
  637. r'^content/browser/webui/web_ui_impl\.(cc|h)$',
  638. r'^content/public/browser/web_ui\.h$',
  639. r'^content/public/test/test_web_ui\.(cc|h)$',
  640. ),
  641. ),
  642. BanRule(
  643. 'leveldb::DB::Open',
  644. (
  645. 'Instead of leveldb::DB::Open() use leveldb_env::OpenDB() from',
  646. 'third_party/leveldatabase/env_chromium.h. It exposes databases to',
  647. "Chrome's tracing, making their memory usage visible.",
  648. ),
  649. True,
  650. (r'^third_party/leveldatabase/.*\.(cc|h)$', ),
  651. ),
  652. BanRule(
  653. 'leveldb::NewMemEnv',
  654. (
  655. 'Instead of leveldb::NewMemEnv() use leveldb_chrome::NewMemEnv() from',
  656. 'third_party/leveldatabase/leveldb_chrome.h. It exposes environments',
  657. "to Chrome's tracing, making their memory usage visible.",
  658. ),
  659. True,
  660. (r'^third_party/leveldatabase/.*\.(cc|h)$', ),
  661. ),
  662. BanRule(
  663. 'base::ScopedMockTimeMessageLoopTaskRunner',
  664. (
  665. 'ScopedMockTimeMessageLoopTaskRunner is deprecated. Prefer',
  666. 'TaskEnvironment::TimeSource::MOCK_TIME. There are still a',
  667. 'few cases that may require a ScopedMockTimeMessageLoopTaskRunner',
  668. '(i.e. mocking the main MessageLoopForUI in browser_tests), but check',
  669. 'with gab@ first if you think you need it)',
  670. ),
  671. False,
  672. (),
  673. ),
  674. BanRule(
  675. '\bstd::aligned_(storage|union)\b',
  676. (
  677. 'std::aligned_storage and std::aligned_union are deprecated in',
  678. 'C++23. Use an aligned char array instead.'
  679. ),
  680. True,
  681. (),
  682. ),
  683. BanRule(
  684. 'std::regex',
  685. (
  686. 'Using std::regex adds unnecessary binary size to Chrome. Please use',
  687. 're2::RE2 instead (crbug.com/755321)',
  688. ),
  689. True,
  690. [
  691. # Abseil's benchmarks never linked into chrome.
  692. 'third_party/abseil-cpp/.*_benchmark.cc',
  693. ],
  694. ),
  695. BanRule(
  696. r'/\bstd::sto(i|l|ul|ll|ull)\b',
  697. (
  698. 'std::sto{i,l,ul,ll,ull}() use exceptions to communicate results. ',
  699. 'Use base::StringTo[U]Int[64]() instead.',
  700. ),
  701. True,
  702. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  703. ),
  704. BanRule(
  705. r'/\bstd::sto(f|d|ld)\b',
  706. (
  707. 'std::sto{f,d,ld}() use exceptions to communicate results. ',
  708. 'For locale-independent values, e.g. reading numbers from disk',
  709. 'profiles, use base::StringToDouble().',
  710. 'For user-visible values, parse using ICU.',
  711. ),
  712. True,
  713. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  714. ),
  715. BanRule(
  716. r'/\bstd::to_string\b',
  717. (
  718. 'std::to_string() is locale dependent and slower than alternatives.',
  719. 'For locale-independent strings, e.g. writing numbers to disk',
  720. 'profiles, use base::NumberToString().',
  721. 'For user-visible strings, use base::FormatNumber() and',
  722. 'the related functions in base/i18n/number_formatting.h.',
  723. ),
  724. True,
  725. [
  726. # TODO(crbug.com/335672557): Please do not add to this list. Existing
  727. # uses should removed.
  728. "third_party/blink/renderer/core/css/parser/css_proto_converter.cc",
  729. "third_party/blink/renderer/core/editing/ime/edit_context.cc",
  730. "third_party/blink/renderer/platform/graphics/bitmap_image_test.cc",
  731. _THIRD_PARTY_EXCEPT_BLINK
  732. ],
  733. ),
  734. BanRule(
  735. r'/#include <(cctype|ctype\.h|cwctype|wctype.h)>',
  736. (
  737. '<cctype>/<ctype.h>/<cwctype>/<wctype.h> are banned. Use',
  738. '"third_party/abseil-cpp/absl/strings/ascii.h" instead.',
  739. ),
  740. True,
  741. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  742. ),
  743. BanRule(
  744. r'/\bstd::shared_ptr\b',
  745. ('std::shared_ptr is banned. Use scoped_refptr instead.', ),
  746. True,
  747. [
  748. # Needed for interop with third-party library.
  749. '^third_party/blink/renderer/core/typed_arrays/array_buffer/' +
  750. 'array_buffer_contents\.(cc|h)',
  751. '^third_party/blink/renderer/core/typed_arrays/dom_array_buffer\.cc',
  752. '^third_party/blink/renderer/bindings/core/v8/' +
  753. 'v8_wasm_response_extensions.cc',
  754. '^gin/array_buffer\.(cc|h)',
  755. '^gin/per_isolate_data\.(cc|h)',
  756. '^chrome/services/sharing/nearby/',
  757. # Needed for interop with third-party library libunwindstack.
  758. '^base/profiler/libunwindstack_unwinder_android\.(cc|h)',
  759. '^base/profiler/native_unwinder_android_memory_regions_map_impl.(cc|h)',
  760. # Needed for interop with third-party boringssl cert verifier
  761. '^third_party/boringssl/',
  762. '^net/cert/',
  763. '^net/tools/cert_verify_tool/',
  764. '^services/cert_verifier/',
  765. '^components/certificate_transparency/',
  766. '^components/media_router/common/providers/cast/certificate/',
  767. # gRPC provides some C++ libraries that use std::shared_ptr<>.
  768. '^chromeos/ash/services/libassistant/grpc/',
  769. '^chromecast/cast_core/grpc',
  770. '^chromecast/cast_core/runtime/browser',
  771. '^ios/chrome/test/earl_grey/chrome_egtest_plugin_client\.(mm|h)',
  772. # Fuchsia provides C++ libraries that use std::shared_ptr<>.
  773. '^base/fuchsia/.*\.(cc|h)',
  774. '.*fuchsia.*test\.(cc|h)',
  775. # Clang plugins have different build config.
  776. '^tools/clang/plugins/',
  777. _THIRD_PARTY_EXCEPT_BLINK
  778. ], # Not an error in third_party folders.
  779. ),
  780. BanRule(
  781. r'/\bstd::weak_ptr\b',
  782. ('std::weak_ptr is banned. Use base::WeakPtr instead.', ),
  783. True,
  784. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  785. ),
  786. BanRule(
  787. r'/\blong long\b',
  788. ('long long is banned. Use [u]int64_t instead.', ),
  789. False, # Only a warning since it is already used.
  790. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  791. ),
  792. BanRule(
  793. r'/\b(absl|std)::any\b',
  794. (
  795. '{absl,std}::any are banned due to incompatibility with the component ',
  796. 'build.',
  797. ),
  798. True,
  799. # Not an error in third party folders, though it probably should be :)
  800. [_THIRD_PARTY_EXCEPT_BLINK],
  801. ),
  802. BanRule(
  803. r'/\bstd::bind\b',
  804. (
  805. 'std::bind() is banned because of lifetime risks. Use ',
  806. 'base::Bind{Once,Repeating}() instead.',
  807. ),
  808. True,
  809. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  810. ),
  811. BanRule(
  812. (r'/\bstd::(?:'
  813. r'linear_congruential_engine|mersenne_twister_engine|'
  814. r'subtract_with_carry_engine|discard_block_engine|'
  815. r'independent_bits_engine|shuffle_order_engine|'
  816. r'minstd_rand0?|mt19937(_64)?|ranlux(24|48)(_base)?|knuth_b|'
  817. r'default_random_engine|'
  818. r'random_device|'
  819. r'seed_seq'
  820. r')\b'),
  821. (
  822. 'STL random number engines and generators are banned. Use the ',
  823. 'helpers in base/rand_util.h instead, e.g. base::RandBytes() or ',
  824. 'base::RandomBitGenerator.'
  825. '',
  826. 'Please reach out to cxx@chromium.org if the base APIs are ',
  827. 'insufficient for your needs.',
  828. ),
  829. True,
  830. [
  831. # Not an error in third_party folders.
  832. _THIRD_PARTY_EXCEPT_BLINK,
  833. # Various tools which build outside of Chrome.
  834. r'testing/libfuzzer',
  835. r'testing/perf/confidence',
  836. r'tools/android/io_benchmark/',
  837. # Fuzzers are allowed to use standard library random number generators
  838. # since fuzzing speed + reproducibility is important.
  839. r'tools/ipc_fuzzer/',
  840. r'.+_fuzzer\.cc$',
  841. r'.+_fuzzertest\.cc$',
  842. # TODO(https://crbug.com/1380528): These are all unsanctioned uses of
  843. # the standard library's random number generators, and should be
  844. # migrated to the //base equivalent.
  845. r'ash/ambient/model/ambient_topic_queue\.cc',
  846. r'base/allocator/partition_allocator/src/partition_alloc/partition_alloc_unittest\.cc',
  847. r'base/test/launcher/test_launcher\.cc',
  848. r'cc/metrics/video_playback_roughness_reporter_unittest\.cc',
  849. r'chrome/browser/apps/app_service/metrics/website_metrics\.cc',
  850. r'chrome/browser/ash/power/auto_screen_brightness/monotone_cubic_spline_unittest\.cc',
  851. r'chrome/browser/ash/printing/zeroconf_printer_detector_unittest\.cc',
  852. r'chrome/browser/nearby_sharing/contacts/nearby_share_contact_manager_impl_unittest\.cc',
  853. r'chrome/browser/nearby_sharing/contacts/nearby_share_contacts_sorter_unittest\.cc',
  854. r'chrome/browser/privacy_budget/mesa_distribution_unittest\.cc',
  855. r'chrome/browser/web_applications/test/web_app_test_utils\.cc',
  856. r'chrome/browser/web_applications/test/web_app_test_utils\.cc',
  857. r'chrome/browser/win/conflicts/module_blocklist_cache_util_unittest\.cc',
  858. r'chromeos/ash/components/memory/userspace_swap/swap_storage_unittest\.cc',
  859. r'chromeos/ash/components/memory/userspace_swap/userspace_swap\.cc',
  860. r'components/metrics/metrics_state_manager\.cc',
  861. r'components/omnibox/browser/history_quick_provider_performance_unittest\.cc',
  862. r'components/zucchini/disassembler_elf_unittest\.cc',
  863. r'content/browser/webid/federated_auth_request_impl\.cc',
  864. r'content/browser/webid/federated_auth_request_impl\.cc',
  865. r'media/cast/test/utility/udp_proxy\.h',
  866. r'sql/recover_module/module_unittest\.cc',
  867. r'components/search_engines/template_url_prepopulate_data.cc',
  868. # Do not add new entries to this list. If you have a use case which is
  869. # not satisfied by the current APIs (i.e. you need an explicitly-seeded
  870. # sequence, or stability of some sort is required), please contact
  871. # cxx@chromium.org.
  872. ],
  873. ),
  874. BanRule(
  875. r'/\b(absl,std)::bind_front\b',
  876. ('{absl,std}::bind_front() are banned. Use base::Bind{Once,Repeating}() '
  877. 'instead.', ),
  878. True,
  879. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  880. ),
  881. BanRule(
  882. r'/\bABSL_FLAG\b',
  883. ('ABSL_FLAG is banned. Use base::CommandLine instead.', ),
  884. True,
  885. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  886. ),
  887. BanRule(
  888. r'/\babsl::c_',
  889. (
  890. 'Abseil container utilities are banned. Use std::ranges:: instead.',
  891. ),
  892. True,
  893. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  894. ),
  895. BanRule(
  896. r'/\babsl::FixedArray\b',
  897. ('absl::FixedArray is banned. Use base::FixedArray instead.', ),
  898. True,
  899. [
  900. # base::FixedArray provides canonical access.
  901. r'^base/types/fixed_array.h',
  902. # Not an error in third_party folders.
  903. _THIRD_PARTY_EXCEPT_BLINK,
  904. ],
  905. ),
  906. BanRule(
  907. r'/\babsl::FunctionRef\b',
  908. ('absl::FunctionRef is banned. Use base::FunctionRef instead.', ),
  909. True,
  910. [
  911. # base::Bind{Once,Repeating} references absl::FunctionRef to disallow
  912. # interoperability.
  913. r'^base/functional/bind_internal\.h',
  914. # base::FunctionRef is implemented on top of absl::FunctionRef.
  915. r'^base/functional/function_ref.*\..+',
  916. # Not an error in third_party folders.
  917. _THIRD_PARTY_EXCEPT_BLINK,
  918. ],
  919. ),
  920. BanRule(
  921. r'/\babsl::(Insecure)?BitGen\b',
  922. ('absl random number generators are banned. Use the helpers in '
  923. 'base/rand_util.h instead, e.g. base::RandBytes() or ',
  924. 'base::RandomBitGenerator.'),
  925. True,
  926. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  927. ),
  928. BanRule(
  929. pattern=
  930. r'/\babsl::(optional|nullopt|make_optional)\b',
  931. explanation=('absl::optional is banned. Use std::optional instead.', ),
  932. treat_as_error=True,
  933. excluded_paths=[
  934. _THIRD_PARTY_EXCEPT_BLINK,
  935. ]),
  936. BanRule(
  937. r'/(\babsl::Span\b|#include <span>|\bstd::span\b)',
  938. (
  939. 'absl::Span and std::span are banned. Use base::span instead.',
  940. ),
  941. True,
  942. [
  943. # Included for conversions between base and std.
  944. r'base/containers/span.h',
  945. # Test base::span<> compatibility against std::span<>.
  946. r'base/containers/span_unittest.cc',
  947. # //base/numerics can't use base or absl. So it uses std.
  948. r'base/numerics/.*'
  949. # Needed to use QUICHE API.
  950. r'android_webview/browser/ip_protection/.*',
  951. r'chrome/browser/ip_protection/.*',
  952. r'components/ip_protection/.*',
  953. r'net/third_party/quiche/overrides/quiche_platform_impl/quiche_stack_trace_impl\.*',
  954. r'services/network/web_transport\.cc',
  955. # Not an error in third_party folders.
  956. _THIRD_PARTY_EXCEPT_BLINK,
  957. ],
  958. ),
  959. BanRule(
  960. r'/\babsl::StatusOr\b',
  961. ('absl::StatusOr is banned. Use base::expected instead.', ),
  962. True,
  963. [
  964. # Needed to use liburlpattern API.
  965. r'components/url_pattern/.*',
  966. r'services/network/shared_dictionary/simple_url_pattern_matcher\.cc',
  967. r'third_party/blink/renderer/core/url_pattern/.*',
  968. r'third_party/blink/renderer/modules/manifest/manifest_parser\.cc',
  969. # Needed to use QUICHE API.
  970. r'android_webview/browser/ip_protection/.*',
  971. r'chrome/browser/ip_protection/.*',
  972. r'components/ip_protection/.*',
  973. # Needed to use MediaPipe API.
  974. r'components/media_effects/.*\.cc',
  975. # Not an error in third_party folders.
  976. _THIRD_PARTY_EXCEPT_BLINK
  977. ],
  978. ),
  979. BanRule(
  980. r'/\babsl::(StrSplit|StrJoin|StrCat|StrAppend|Substitute|StrContains)\b',
  981. ('Abseil string utilities are banned. Use base/strings instead.', ),
  982. True,
  983. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  984. ),
  985. BanRule(
  986. r'/\babsl::(Mutex|CondVar|Notification|Barrier|BlockingCounter)\b',
  987. (
  988. 'Abseil synchronization primitives are banned. Use',
  989. 'base/synchronization instead.',
  990. ),
  991. True,
  992. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  993. ),
  994. BanRule(
  995. r'/\babsl::(Duration|Time|TimeZone|CivilDay)\b',
  996. ('Abseil\'s time library is banned. Use base/time instead.', ),
  997. True,
  998. [
  999. # Needed to use QUICHE API.
  1000. r'android_webview/browser/ip_protection/.*',
  1001. r'chrome/browser/ip_protection/.*',
  1002. r'components/ip_protection/.*',
  1003. # Needed to integrate with //third_party/nearby
  1004. r'components/cross_device/nearby/system_clock.cc',
  1005. _THIRD_PARTY_EXCEPT_BLINK # Not an error in third_party folders.
  1006. ],
  1007. ),
  1008. BanRule(
  1009. r'/#include <chrono>',
  1010. ('<chrono> is banned. Use base/time instead.', ),
  1011. True,
  1012. [
  1013. # Not an error in third_party folders:
  1014. _THIRD_PARTY_EXCEPT_BLINK,
  1015. # This uses openscreen API depending on std::chrono.
  1016. "components/openscreen_platform/task_runner.cc",
  1017. ]),
  1018. BanRule(
  1019. r'/#include <exception>',
  1020. ('Exceptions are banned and disabled in Chromium.', ),
  1021. True,
  1022. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  1023. ),
  1024. BanRule(
  1025. r'/\bstd::function\b',
  1026. ('std::function is banned. Use base::{Once,Repeating}Callback instead.',
  1027. ),
  1028. True,
  1029. [
  1030. # Has tests that template trait helpers don't unintentionally match
  1031. # std::function.
  1032. r'base/functional/callback_helpers_unittest\.cc',
  1033. # Required to implement interfaces from the third-party perfetto
  1034. # library.
  1035. r'base/tracing/perfetto_task_runner\.cc',
  1036. r'base/tracing/perfetto_task_runner\.h',
  1037. # Needed for interop with the third-party nearby library type
  1038. # location::nearby::connections::ResultCallback.
  1039. 'chrome/services/sharing/nearby/nearby_connections_conversions\.cc'
  1040. # Needed for interop with the internal libassistant library.
  1041. 'chromeos/ash/services/libassistant/callback_utils\.h',
  1042. # Needed for interop with Fuchsia fidl APIs.
  1043. 'fuchsia_web/webengine/browser/context_impl_browsertest\.cc',
  1044. 'fuchsia_web/webengine/browser/cookie_manager_impl_unittest\.cc',
  1045. 'fuchsia_web/webengine/browser/media_player_impl_unittest\.cc',
  1046. # Required to interop with interfaces from the third-party ChromeML
  1047. # library API.
  1048. 'services/on_device_model/ml/chrome_ml_api\.h',
  1049. 'services/on_device_model/ml/on_device_model_executor\.cc',
  1050. 'services/on_device_model/ml/on_device_model_executor\.h',
  1051. # Required to interop with interfaces from the third-party perfetto
  1052. # library.
  1053. 'components/tracing/common/etw_consumer_win_unittest\.cc',
  1054. 'services/tracing/public/cpp/perfetto/custom_event_recorder\.cc',
  1055. 'services/tracing/public/cpp/perfetto/perfetto_traced_process\.cc',
  1056. 'services/tracing/public/cpp/perfetto/perfetto_traced_process\.h',
  1057. 'services/tracing/public/cpp/perfetto/perfetto_tracing_backend\.cc',
  1058. 'services/tracing/public/cpp/perfetto/producer_client\.cc',
  1059. 'services/tracing/public/cpp/perfetto/producer_client\.h',
  1060. 'services/tracing/public/cpp/perfetto/producer_test_utils\.cc',
  1061. 'services/tracing/public/cpp/perfetto/producer_test_utils\.h',
  1062. # Required for interop with the third-party webrtc library.
  1063. 'third_party/blink/renderer/modules/peerconnection/mock_peer_connection_impl\.cc',
  1064. 'third_party/blink/renderer/modules/peerconnection/mock_peer_connection_impl\.h',
  1065. # TODO(https://crbug.com/1364577): Various uses that should be
  1066. # migrated to something else.
  1067. # Should use base::OnceCallback or base::RepeatingCallback.
  1068. 'base/allocator/dispatcher/initializer_unittest\.cc',
  1069. 'chrome/browser/ash/accessibility/speech_monitor\.cc',
  1070. 'chrome/browser/ash/accessibility/speech_monitor\.h',
  1071. 'chrome/browser/ash/login/ash_hud_login_browsertest\.cc',
  1072. 'chromecast/base/observer_unittest\.cc',
  1073. 'chromecast/browser/cast_web_view\.h',
  1074. 'chromecast/public/cast_media_shlib\.h',
  1075. 'device/bluetooth/floss/exported_callback_manager\.h',
  1076. 'device/bluetooth/floss/floss_dbus_client\.h',
  1077. 'device/fido/cable/v2_handshake_unittest\.cc',
  1078. 'device/fido/pin\.cc',
  1079. 'services/tracing/perfetto/test_utils\.h',
  1080. # Should use base::FunctionRef.
  1081. 'chrome/browser/media/webrtc/test_stats_dictionary\.cc',
  1082. 'chrome/browser/media/webrtc/test_stats_dictionary\.h',
  1083. 'chromeos/ash/services/libassistant/device_settings_controller\.cc',
  1084. 'components/browser_ui/client_certificate/android/ssl_client_certificate_request\.cc',
  1085. 'components/gwp_asan/client/sampling_malloc_shims_unittest\.cc',
  1086. 'content/browser/font_unique_name_lookup/font_unique_name_lookup_unittest\.cc',
  1087. # Does not need std::function at all.
  1088. 'components/omnibox/browser/autocomplete_result\.cc',
  1089. 'device/fido/win/webauthn_api\.cc',
  1090. 'media/audio/alsa/alsa_util\.cc',
  1091. 'media/remoting/stream_provider\.h',
  1092. 'sql/vfs_wrapper\.cc',
  1093. # TODO(https://crbug.com/1364585): Remove usage and exception list
  1094. # entries.
  1095. 'extensions/renderer/api/automation/automation_internal_custom_bindings\.cc',
  1096. 'extensions/renderer/api/automation/automation_internal_custom_bindings\.h',
  1097. # TODO(https://crbug.com/1364579): Remove usage and exception list
  1098. # entry.
  1099. 'ui/views/controls/focus_ring\.h',
  1100. # Various pre-existing uses in //tools that is low-priority to fix.
  1101. 'tools/binary_size/libsupersize/viewer/caspian/diff\.cc',
  1102. 'tools/binary_size/libsupersize/viewer/caspian/model\.cc',
  1103. 'tools/binary_size/libsupersize/viewer/caspian/model\.h',
  1104. 'tools/binary_size/libsupersize/viewer/caspian/tree_builder\.h',
  1105. 'tools/clang/base_bind_rewriters/BaseBindRewriters\.cpp',
  1106. # Not an error in third_party folders.
  1107. _THIRD_PARTY_EXCEPT_BLINK
  1108. ],
  1109. ),
  1110. BanRule(
  1111. r'/#include <X11/',
  1112. ('Do not use Xlib. Use xproto (from //ui/gfx/x:xproto) instead.', ),
  1113. True,
  1114. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  1115. ),
  1116. BanRule(
  1117. r'/\bstd::ratio\b',
  1118. ('std::ratio is banned by the Google Style Guide.', ),
  1119. True,
  1120. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  1121. ),
  1122. BanRule(
  1123. r'/\bstd::aligned_alloc\b',
  1124. (
  1125. 'std::aligned_alloc() is not yet allowed (crbug.com/1412818). Use ',
  1126. 'base::AlignedAlloc() instead.',
  1127. ),
  1128. True,
  1129. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1130. ),
  1131. BanRule(
  1132. r'/#include <(barrier|latch|semaphore|stop_token)>',
  1133. ('The thread support library is banned. Use base/synchronization '
  1134. 'instead.', ),
  1135. True,
  1136. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1137. ),
  1138. BanRule(
  1139. r'/\bstd::execution::(par|seq)\b',
  1140. ('std::execution::(par|seq) is banned; they do not fit into '
  1141. ' Chrome\'s threading model, and libc++ doesn\'t have full '
  1142. 'support.', ),
  1143. True,
  1144. [_THIRD_PARTY_EXCEPT_BLINK],
  1145. ),
  1146. BanRule(
  1147. r'/\bstd::bit_cast\b',
  1148. ('std::bit_cast is banned; use base::bit_cast instead for values and '
  1149. 'standard C++ casting when pointers are involved.', ),
  1150. True,
  1151. [
  1152. # Don't warn in third_party folders.
  1153. _THIRD_PARTY_EXCEPT_BLINK,
  1154. # //base/numerics can't use base or absl.
  1155. r'base/numerics/.*'
  1156. ],
  1157. ),
  1158. BanRule(
  1159. r'/\bstd::(c8rtomb|mbrtoc8)\b',
  1160. ('std::c8rtomb() and std::mbrtoc8() are banned.', ),
  1161. True,
  1162. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1163. ),
  1164. BanRule(
  1165. r'/\bchar8_t|std::u8string\b',
  1166. (
  1167. 'char8_t and std::u8string are not yet allowed. Can you use [unsigned]',
  1168. ' char and std::string instead?',
  1169. ),
  1170. True,
  1171. [
  1172. # The demangler does not use this type but needs to know about it.
  1173. 'base/third_party/symbolize/demangle\.cc',
  1174. # Don't warn in third_party folders.
  1175. _THIRD_PARTY_EXCEPT_BLINK
  1176. ],
  1177. ),
  1178. BanRule(
  1179. r'/(\b(co_await|co_return|co_yield)\b|#include <coroutine>)',
  1180. ('Coroutines are not yet allowed (https://crbug.com/1403840).', ),
  1181. True,
  1182. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1183. ),
  1184. BanRule(
  1185. r'/^\s*(export\s|import\s+["<:\w]|module(;|\s+[:\w]))',
  1186. ('Modules are disallowed for now due to lack of toolchain support.', ),
  1187. True,
  1188. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1189. ),
  1190. BanRule(
  1191. r'/\[\[(\w*::)?no_unique_address\]\]',
  1192. (
  1193. '[[no_unique_address]] does not work as expected on Windows ',
  1194. '(https://crbug.com/1414621). Use NO_UNIQUE_ADDRESS instead.',
  1195. ),
  1196. True,
  1197. [
  1198. # NO_UNIQUE_ADDRESS / PA_NO_UNIQUE_ADDRESS provide canonical access.
  1199. r'^base/compiler_specific\.h',
  1200. r'^base/allocator/partition_allocator/src/partition_alloc/partition_alloc_base/compiler_specific\.h',
  1201. # Not an error in third_party folders.
  1202. _THIRD_PARTY_EXCEPT_BLINK,
  1203. ],
  1204. ),
  1205. BanRule(
  1206. r'/#include <format>',
  1207. ('<format> is not yet allowed. Use base::StringPrintf() instead.', ),
  1208. True,
  1209. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1210. ),
  1211. BanRule(
  1212. pattern='std::views',
  1213. explanation=(
  1214. 'Use of std::views is banned in Chrome. If you need this '
  1215. 'functionality, please contact cxx@chromium.org.',
  1216. ),
  1217. treat_as_error=True,
  1218. excluded_paths=[
  1219. # Don't warn in third_party folders.
  1220. _THIRD_PARTY_EXCEPT_BLINK
  1221. ],
  1222. ),
  1223. BanRule(
  1224. # Ban everything except specifically allowlisted constructs.
  1225. pattern=r'/std::ranges::(?!' + '|'.join((
  1226. # From https://en.cppreference.com/w/cpp/ranges:
  1227. # Range access
  1228. 'begin',
  1229. 'end',
  1230. 'cbegin',
  1231. 'cend',
  1232. 'rbegin',
  1233. 'rend',
  1234. 'crbegin',
  1235. 'crend',
  1236. 'size',
  1237. 'ssize',
  1238. 'empty',
  1239. 'data',
  1240. 'cdata',
  1241. # Range primitives
  1242. 'iterator_t',
  1243. 'const_iterator_t',
  1244. 'sentinel_t',
  1245. 'const_sentinel_t',
  1246. 'range_difference_t',
  1247. 'range_size_t',
  1248. 'range_value_t',
  1249. 'range_reference_t',
  1250. 'range_const_reference_t',
  1251. 'range_rvalue_reference_t',
  1252. 'range_common_reference_t',
  1253. # Dangling iterator handling
  1254. 'dangling',
  1255. 'borrowed_iterator_t',
  1256. # Banned: borrowed_subrange_t
  1257. # Range concepts
  1258. 'range',
  1259. 'borrowed_range',
  1260. 'sized_range',
  1261. 'view',
  1262. 'input_range',
  1263. 'output_range',
  1264. 'forward_range',
  1265. 'bidirectional_range',
  1266. 'random_access_range',
  1267. 'contiguous_range',
  1268. 'common_range',
  1269. 'viewable_range',
  1270. 'constant_range',
  1271. # Banned: Views
  1272. # Banned: Range factories
  1273. # Banned: Range adaptors
  1274. # Incidentally listed on
  1275. # https://en.cppreference.com/w/cpp/header/ranges:
  1276. 'enable_borrowed_range',
  1277. 'enable_view',
  1278. # From https://en.cppreference.com/w/cpp/algorithm/ranges:
  1279. # Constrained algorithms: non-modifying sequence operations
  1280. 'all_of',
  1281. 'any_of',
  1282. 'none_of',
  1283. 'for_each',
  1284. 'for_each_n',
  1285. 'count',
  1286. 'count_if',
  1287. 'mismatch',
  1288. 'equal',
  1289. 'lexicographical_compare',
  1290. 'find',
  1291. 'find_if',
  1292. 'find_if_not',
  1293. 'find_end',
  1294. 'find_first_of',
  1295. 'adjacent_find',
  1296. 'search',
  1297. 'search_n',
  1298. # Constrained algorithms: modifying sequence operations
  1299. 'copy',
  1300. 'copy_if',
  1301. 'copy_n',
  1302. 'copy_backward',
  1303. 'move',
  1304. 'move_backward',
  1305. 'fill',
  1306. 'fill_n',
  1307. 'transform',
  1308. 'generate',
  1309. 'generate_n',
  1310. 'remove',
  1311. 'remove_if',
  1312. 'remove_copy',
  1313. 'remove_copy_if',
  1314. 'replace',
  1315. 'replace_if',
  1316. 'replace_copy',
  1317. 'replace_copy_if',
  1318. 'swap_ranges',
  1319. 'reverse',
  1320. 'reverse_copy',
  1321. 'rotate',
  1322. 'rotate_copy',
  1323. 'shuffle',
  1324. 'sample',
  1325. 'unique',
  1326. 'unique_copy',
  1327. # Constrained algorithms: partitioning operations
  1328. 'is_partitioned',
  1329. 'partition',
  1330. 'partition_copy',
  1331. 'stable_partition',
  1332. 'partition_point',
  1333. # Constrained algorithms: sorting operations
  1334. 'is_sorted',
  1335. 'is_sorted_until',
  1336. 'sort',
  1337. 'partial_sort',
  1338. 'partial_sort_copy',
  1339. 'stable_sort',
  1340. 'nth_element',
  1341. # Constrained algorithms: binary search operations (on sorted ranges)
  1342. 'lower_bound',
  1343. 'upper_bound',
  1344. 'binary_search',
  1345. 'equal_range',
  1346. # Constrained algorithms: set operations (on sorted ranges)
  1347. 'merge',
  1348. 'inplace_merge',
  1349. 'includes',
  1350. 'set_difference',
  1351. 'set_intersection',
  1352. 'set_symmetric_difference',
  1353. 'set_union',
  1354. # Constrained algorithms: heap operations
  1355. 'is_heap',
  1356. 'is_heap_until',
  1357. 'make_heap',
  1358. 'push_heap',
  1359. 'pop_heap',
  1360. 'sort_heap',
  1361. # Constrained algorithms: minimum/maximum operations
  1362. 'max',
  1363. 'max_element',
  1364. 'min',
  1365. 'min_element',
  1366. 'minmax',
  1367. 'minmax_element',
  1368. 'clamp',
  1369. # Constrained algorithms: permutation operations
  1370. 'is_permutation',
  1371. 'next_permutation',
  1372. 'prev_premutation',
  1373. # Constrained uninitialized memory algorithms
  1374. 'uninitialized_copy',
  1375. 'uninitialized_copy_n',
  1376. 'uninitialized_fill',
  1377. 'uninitialized_fill_n',
  1378. 'uninitialized_move',
  1379. 'uninitialized_move_n',
  1380. 'uninitialized_default_construct',
  1381. 'uninitialized_default_construct_n',
  1382. 'uninitialized_value_construct',
  1383. 'uninitialized_value_construct_n',
  1384. 'destroy',
  1385. 'destroy_n',
  1386. 'destroy_at',
  1387. 'construct_at',
  1388. # Return types
  1389. 'in_fun_result',
  1390. 'in_in_result',
  1391. 'in_out_result',
  1392. 'in_in_out_result',
  1393. 'in_out_out_result',
  1394. 'min_max_result',
  1395. 'in_found_result',
  1396. # From https://en.cppreference.com/w/cpp/header/functional
  1397. 'equal_to',
  1398. 'not_equal_to',
  1399. 'greater',
  1400. 'less',
  1401. 'greater_equal',
  1402. 'less_equal',
  1403. # From https://en.cppreference.com/w/cpp/iterator
  1404. 'advance',
  1405. 'distance',
  1406. 'next',
  1407. 'prev',
  1408. )) + r')\w+',
  1409. explanation=(
  1410. 'Use of range views and associated helpers is banned in Chrome. '
  1411. 'If you need this functionality, please contact cxx@chromium.org.',
  1412. ),
  1413. treat_as_error=True,
  1414. excluded_paths=[
  1415. # Don't warn in third_party folders.
  1416. _THIRD_PARTY_EXCEPT_BLINK
  1417. ],
  1418. ),
  1419. BanRule(
  1420. r'/#include <regex>',
  1421. ('<regex> is not allowed. Use third_party/re2 instead.',
  1422. ),
  1423. True,
  1424. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1425. ),
  1426. BanRule(
  1427. r'/#include <source_location>',
  1428. ('<source_location> is not yet allowed. Use base/location.h instead.',
  1429. ),
  1430. True,
  1431. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1432. ),
  1433. BanRule(
  1434. r'/\bstd::to_address\b',
  1435. (
  1436. 'std::to_address is banned because it is not guaranteed to be',
  1437. 'SFINAE-compatible. Use base::to_address from base/types/to_address.h',
  1438. 'instead.',
  1439. ),
  1440. True,
  1441. [
  1442. # Needed in base::to_address implementation.
  1443. r'base/types/to_address.h',
  1444. _THIRD_PARTY_EXCEPT_BLINK
  1445. ], # Not an error in third_party folders.
  1446. ),
  1447. BanRule(
  1448. r'/#include <syncstream>',
  1449. ('<syncstream> is banned.', ),
  1450. True,
  1451. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  1452. ),
  1453. BanRule(
  1454. r'/\bRunMessageLoop\b',
  1455. ('RunMessageLoop is deprecated, use RunLoop instead.', ),
  1456. False,
  1457. (),
  1458. ),
  1459. BanRule(
  1460. 'RunAllPendingInMessageLoop()',
  1461. (
  1462. "Prefer RunLoop over RunAllPendingInMessageLoop, please contact gab@",
  1463. "if you're convinced you need this.",
  1464. ),
  1465. False,
  1466. (),
  1467. ),
  1468. BanRule(
  1469. 'RunAllPendingInMessageLoop(BrowserThread',
  1470. (
  1471. 'RunAllPendingInMessageLoop is deprecated. Use RunLoop for',
  1472. 'BrowserThread::UI, BrowserTaskEnvironment::RunIOThreadUntilIdle',
  1473. 'for BrowserThread::IO, and prefer RunLoop::QuitClosure to observe',
  1474. 'async events instead of flushing threads.',
  1475. ),
  1476. False,
  1477. (),
  1478. ),
  1479. BanRule(
  1480. r'MessageLoopRunner',
  1481. ('MessageLoopRunner is deprecated, use RunLoop instead.', ),
  1482. False,
  1483. (),
  1484. ),
  1485. BanRule(
  1486. 'GetDeferredQuitTaskForRunLoop',
  1487. (
  1488. "GetDeferredQuitTaskForRunLoop shouldn't be needed, please contact",
  1489. "gab@ if you found a use case where this is the only solution.",
  1490. ),
  1491. False,
  1492. (),
  1493. ),
  1494. BanRule(
  1495. 'sqlite3_initialize(',
  1496. (
  1497. 'Instead of calling sqlite3_initialize(), depend on //sql, ',
  1498. '#include "sql/initialize.h" and use sql::EnsureSqliteInitialized().',
  1499. ),
  1500. True,
  1501. (
  1502. r'^sql/initialization\.(cc|h)$',
  1503. r'^third_party/sqlite/.*\.(c|cc|h)$',
  1504. ),
  1505. ),
  1506. BanRule(
  1507. 'CREATE VIEW',
  1508. (
  1509. 'SQL views are disabled in Chromium feature code',
  1510. 'https://chromium.googlesource.com/chromium/src/+/HEAD/sql#no-views',
  1511. ),
  1512. True,
  1513. (
  1514. _THIRD_PARTY_EXCEPT_BLINK,
  1515. # sql/ itself uses views when using memory-mapped IO.
  1516. r'^sql/.*',
  1517. # Various performance tools that do not build as part of Chrome.
  1518. r'^infra/.*',
  1519. r'^tools/perf.*',
  1520. r'.*perfetto.*',
  1521. ),
  1522. ),
  1523. BanRule(
  1524. 'CREATE VIRTUAL TABLE',
  1525. (
  1526. 'SQL virtual tables are disabled in Chromium feature code',
  1527. 'https://chromium.googlesource.com/chromium/src/+/HEAD/sql#no-virtual-tables',
  1528. ),
  1529. True,
  1530. (
  1531. _THIRD_PARTY_EXCEPT_BLINK,
  1532. # sql/ itself uses virtual tables in the recovery module and tests.
  1533. r'^sql/.*',
  1534. # TODO(https://crbug.com/695592): Remove once WebSQL is deprecated.
  1535. r'third_party/blink/web_tests/storage/websql/.*'
  1536. # Various performance tools that do not build as part of Chrome.
  1537. r'^tools/perf.*',
  1538. r'.*perfetto.*',
  1539. ),
  1540. ),
  1541. BanRule(
  1542. 'std::random_shuffle',
  1543. ('std::random_shuffle is deprecated in C++14, and removed in C++17. Use',
  1544. 'base::RandomShuffle instead.'),
  1545. True,
  1546. (),
  1547. ),
  1548. BanRule(
  1549. 'ios/web/public/test/http_server',
  1550. ('web::HTTPserver is deprecated use net::EmbeddedTestServer instead.',
  1551. ),
  1552. False,
  1553. (),
  1554. ),
  1555. BanRule(
  1556. 'GetAddressOf',
  1557. ('Improper use of Microsoft::WRL::ComPtr<T>::GetAddressOf() has been ',
  1558. 'implicated in a few leaks. ReleaseAndGetAddressOf() is safe but ',
  1559. 'operator& is generally recommended. So always use operator& instead. ',
  1560. 'See http://crbug.com/914910 for more conversion guidance.'),
  1561. True,
  1562. (),
  1563. ),
  1564. BanRule(
  1565. 'SHFileOperation',
  1566. ('SHFileOperation was deprecated in Windows Vista, and there are less ',
  1567. 'complex functions to achieve the same goals. Use IFileOperation for ',
  1568. 'any esoteric actions instead.'),
  1569. True,
  1570. (),
  1571. ),
  1572. BanRule(
  1573. 'StringFromGUID2',
  1574. ('StringFromGUID2 introduces an unnecessary dependency on ole32.dll.',
  1575. 'Use base::win::WStringFromGUID instead.'),
  1576. True,
  1577. (r'/base/win/win_util_unittest.cc', ),
  1578. ),
  1579. BanRule(
  1580. 'StringFromCLSID',
  1581. ('StringFromCLSID introduces an unnecessary dependency on ole32.dll.',
  1582. 'Use base::win::WStringFromGUID instead.'),
  1583. True,
  1584. (r'/base/win/win_util_unittest.cc', ),
  1585. ),
  1586. BanRule(
  1587. 'kCFAllocatorNull',
  1588. (
  1589. 'The use of kCFAllocatorNull with the NoCopy creation of ',
  1590. 'CoreFoundation types is prohibited.',
  1591. ),
  1592. True,
  1593. (),
  1594. ),
  1595. BanRule(
  1596. 'mojo::ConvertTo',
  1597. ('mojo::ConvertTo and TypeConverter are deprecated. Please consider',
  1598. 'StructTraits / UnionTraits / EnumTraits / ArrayTraits / MapTraits /',
  1599. 'StringTraits if you would like to convert between custom types and',
  1600. 'the wire format of mojom types.'),
  1601. False,
  1602. (
  1603. r'^fuchsia_web/webengine/browser/url_request_rewrite_rules_manager\.cc$',
  1604. r'^fuchsia_web/webengine/url_request_rewrite_type_converters\.cc$',
  1605. r'^third_party/blink/.*\.(cc|h)$',
  1606. r'^content/renderer/.*\.(cc|h)$',
  1607. ),
  1608. ),
  1609. BanRule(
  1610. 'GetInterfaceProvider',
  1611. ('InterfaceProvider is deprecated.',
  1612. 'Please use ExecutionContext::GetBrowserInterfaceBroker and overrides',
  1613. 'or Platform::GetBrowserInterfaceBroker.'),
  1614. False,
  1615. (),
  1616. ),
  1617. BanRule(
  1618. 'CComPtr',
  1619. ('New code should use Microsoft::WRL::ComPtr from wrl/client.h as a ',
  1620. 'replacement for CComPtr from ATL. See http://crbug.com/5027 for more ',
  1621. 'details.'),
  1622. False,
  1623. (),
  1624. ),
  1625. BanRule(
  1626. r'/\b(IFACE|STD)METHOD_?\(',
  1627. ('IFACEMETHOD() and STDMETHOD() make code harder to format and read.',
  1628. 'Instead, always use IFACEMETHODIMP in the declaration.'),
  1629. False,
  1630. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  1631. ),
  1632. BanRule(
  1633. 'set_owned_by_client',
  1634. ('set_owned_by_client is deprecated.',
  1635. 'views::View already owns the child views by default. This introduces ',
  1636. 'a competing ownership model which makes the code difficult to reason ',
  1637. 'about. See http://crbug.com/1044687 for more details.'),
  1638. False,
  1639. (),
  1640. ),
  1641. BanRule(
  1642. 'RemoveAllChildViewsWithoutDeleting',
  1643. ('RemoveAllChildViewsWithoutDeleting is deprecated.',
  1644. 'This method is deemed dangerous as, unless raw pointers are re-added,',
  1645. 'calls to this method introduce memory leaks.'),
  1646. False,
  1647. (),
  1648. ),
  1649. BanRule(
  1650. r'/\bTRACE_EVENT_ASYNC_',
  1651. (
  1652. 'Please use TRACE_EVENT_NESTABLE_ASYNC_.. macros instead',
  1653. 'of TRACE_EVENT_ASYNC_.. (crbug.com/1038710).',
  1654. ),
  1655. False,
  1656. (
  1657. r'^base/trace_event/.*',
  1658. r'^base/tracing/.*',
  1659. ),
  1660. ),
  1661. BanRule(
  1662. r'/\bbase::debug::DumpWithoutCrashingUnthrottled[(][)]',
  1663. (
  1664. 'base::debug::DumpWithoutCrashingUnthrottled() does not throttle',
  1665. 'dumps and may spam crash reports. Consider if the throttled',
  1666. 'variants suffice instead.',
  1667. ),
  1668. False,
  1669. (),
  1670. ),
  1671. BanRule(
  1672. 'RoInitialize',
  1673. ('Improper use of [base::win]::RoInitialize() has been implicated in a ',
  1674. 'few COM initialization leaks. Use base::win::ScopedWinrtInitializer ',
  1675. 'instead. See http://crbug.com/1197722 for more information.'),
  1676. True,
  1677. (
  1678. r'^base/win/scoped_winrt_initializer\.cc$',
  1679. r'^third_party/abseil-cpp/absl/.*',
  1680. ),
  1681. ),
  1682. BanRule(
  1683. r'base::Watchdog',
  1684. (
  1685. 'base::Watchdog is deprecated because it creates its own thread.',
  1686. 'Instead, manually start a timer on a SequencedTaskRunner.',
  1687. ),
  1688. False,
  1689. (),
  1690. ),
  1691. BanRule(
  1692. 'base::Passed',
  1693. ('Do not use base::Passed. It is a legacy helper for capturing ',
  1694. 'move-only types with base::BindRepeating, but invoking the ',
  1695. 'resulting RepeatingCallback moves the captured value out of ',
  1696. 'the callback storage, and subsequent invocations may pass the ',
  1697. 'value in a valid but undefined state. Prefer base::BindOnce().',
  1698. 'See http://crbug.com/1326449 for context.'),
  1699. False,
  1700. (
  1701. # False positive, but it is also fine to let bind internals reference
  1702. # base::Passed.
  1703. r'^base[\\/]functional[\\/]bind\.h',
  1704. r'^base[\\/]functional[\\/]bind_internal\.h',
  1705. ),
  1706. ),
  1707. BanRule(
  1708. r'base::Feature k',
  1709. ('Please use BASE_DECLARE_FEATURE() or BASE_FEATURE() instead of ',
  1710. 'directly declaring/defining features.'),
  1711. True,
  1712. [
  1713. # Implements BASE_DECLARE_FEATURE().
  1714. r'^base/feature_list\.h',
  1715. ],
  1716. ),
  1717. BanRule(
  1718. r'/\bchartorune\b',
  1719. ('chartorune is not memory-safe, unless you can guarantee the input ',
  1720. 'string is always null-terminated. Otherwise, please use charntorune ',
  1721. 'from libphonenumber instead.'),
  1722. True,
  1723. [
  1724. _THIRD_PARTY_EXCEPT_BLINK,
  1725. # Exceptions to this rule should have a fuzzer.
  1726. ],
  1727. ),
  1728. BanRule(
  1729. r'/\b#include "base/atomicops\.h"\b',
  1730. ('Do not use base::subtle atomics, but std::atomic, which are simpler '
  1731. 'to use, have better understood, clearer and richer semantics, and are '
  1732. 'harder to mis-use. See details in base/atomicops.h.', ),
  1733. False,
  1734. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  1735. ),
  1736. BanRule(r'CrossThreadPersistent<', (
  1737. 'Do not use blink::CrossThreadPersistent, but '
  1738. 'blink::CrossThreadHandle. It is harder to mis-use.', 'More info: '
  1739. 'https://docs.google.com/document/d/1GIT0ysdQ84sGhIo1r9EscF_fFt93lmNVM_q4vvHj2FQ/edit#heading=h.3e4d6y61tgs',
  1740. 'Please contact platform-architecture-dev@ before adding new instances.'
  1741. ), False, []),
  1742. BanRule(r'CrossThreadWeakPersistent<', (
  1743. 'Do not use blink::CrossThreadWeakPersistent, but '
  1744. 'blink::CrossThreadWeakHandle. It is harder to mis-use.', 'More info: '
  1745. 'https://docs.google.com/document/d/1GIT0ysdQ84sGhIo1r9EscF_fFt93lmNVM_q4vvHj2FQ/edit#heading=h.3e4d6y61tgs',
  1746. 'Please contact platform-architecture-dev@ before adding new instances.'
  1747. ), False, []),
  1748. BanRule(r'objc/objc.h', (
  1749. 'Do not include <objc/objc.h>. It defines away ARC lifetime '
  1750. 'annotations, and is thus dangerous.',
  1751. 'Please use the pimpl pattern; search for `ObjCStorage` for examples.',
  1752. 'For further reading on how to safely mix C++ and Obj-C, see',
  1753. 'https://chromium.googlesource.com/chromium/src/+/main/docs/mac/mixing_cpp_and_objc.md'
  1754. ), True, []),
  1755. BanRule(
  1756. r'/#include <filesystem>',
  1757. ('libc++ <filesystem> is banned per the Google C++ styleguide.', ),
  1758. True,
  1759. # This fuzzing framework is a standalone open source project and
  1760. # cannot rely on Chromium base.
  1761. (r'third_party/centipede'),
  1762. ),
  1763. BanRule(
  1764. r'TopDocument()',
  1765. ('TopDocument() does not work correctly with out-of-process iframes. '
  1766. 'Please do not introduce new uses.', ),
  1767. True,
  1768. (
  1769. # TODO(crbug.com/617677): Remove all remaining uses.
  1770. r'^third_party/blink/renderer/core/dom/document\.cc',
  1771. r'^third_party/blink/renderer/core/dom/document\.h',
  1772. r'^third_party/blink/renderer/core/dom/element\.cc',
  1773. r'^third_party/blink/renderer/core/exported/web_disallow_transition_scope_test\.cc',
  1774. r'^third_party/blink/renderer/core/exported/web_document_test\.cc',
  1775. r'^third_party/blink/renderer/core/html/html_anchor_element\.cc',
  1776. r'^third_party/blink/renderer/core/html/html_dialog_element\.cc',
  1777. r'^third_party/blink/renderer/core/html/html_element\.cc',
  1778. r'^third_party/blink/renderer/core/html/html_frame_owner_element\.cc',
  1779. r'^third_party/blink/renderer/core/html/media/video_wake_lock\.cc',
  1780. r'^third_party/blink/renderer/core/loader/anchor_element_interaction_tracker\.cc',
  1781. r'^third_party/blink/renderer/core/page/scrolling/root_scroller_controller\.cc',
  1782. r'^third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller\.cc',
  1783. r'^third_party/blink/renderer/core/page/scrolling/top_document_root_scroller_controller\.h',
  1784. r'^third_party/blink/renderer/core/script/classic_pending_script\.cc',
  1785. r'^third_party/blink/renderer/core/script/script_loader\.cc',
  1786. ),
  1787. ),
  1788. BanRule(
  1789. pattern=r'base::raw_ptr<',
  1790. explanation=('Do not use base::raw_ptr, use raw_ptr.', ),
  1791. treat_as_error=True,
  1792. excluded_paths=(
  1793. '^base/',
  1794. '^tools/',
  1795. ),
  1796. ),
  1797. BanRule(
  1798. pattern=r'base:raw_ref<',
  1799. explanation=('Do not use base::raw_ref, use raw_ref.', ),
  1800. treat_as_error=True,
  1801. excluded_paths=(
  1802. '^base/',
  1803. '^tools/',
  1804. ),
  1805. ),
  1806. BanRule(
  1807. pattern=r'/raw_ptr<[^;}]*\w{};',
  1808. explanation=(
  1809. 'Do not use {} for raw_ptr initialization, use = nullptr instead.',
  1810. ),
  1811. treat_as_error=True,
  1812. excluded_paths=(
  1813. '^base/',
  1814. '^tools/',
  1815. ),
  1816. ),
  1817. BanRule(
  1818. pattern=r'/#include "base/allocator/.*/raw_'
  1819. r'(ptr|ptr_cast|ptr_exclusion|ref).h"',
  1820. explanation=(
  1821. 'Please include the corresponding facade headers:',
  1822. '- #include "base/memory/raw_ptr.h"',
  1823. '- #include "base/memory/raw_ptr_cast.h"',
  1824. '- #include "base/memory/raw_ptr_exclusion.h"',
  1825. '- #include "base/memory/raw_ref.h"',
  1826. ),
  1827. treat_as_error=True,
  1828. excluded_paths=(
  1829. '^base/',
  1830. '^tools/',
  1831. ),
  1832. ),
  1833. BanRule(
  1834. pattern=r'ContentSettingsType::COOKIES',
  1835. explanation=
  1836. ('Do not use ContentSettingsType::COOKIES to check whether cookies are '
  1837. 'supported in the provided context. Instead rely on the '
  1838. 'content_settings::CookieSettings API. If you are using '
  1839. 'ContentSettingsType::COOKIES to check the user preference setting '
  1840. 'specifically, disregard this warning.', ),
  1841. treat_as_error=False,
  1842. excluded_paths=(
  1843. '^chrome/browser/ui/content_settings/',
  1844. '^components/content_settings/',
  1845. '^services/network/cookie_settings.cc',
  1846. '.*test.cc',
  1847. ),
  1848. ),
  1849. BanRule(
  1850. pattern=r'ContentSettingsType::TRACKING_PROTECTION',
  1851. explanation=
  1852. ('Do not directly use ContentSettingsType::TRACKING_PROTECTION to check '
  1853. 'for tracking protection exceptions. Instead rely on the '
  1854. 'privacy_sandbox::TrackingProtectionSettings API.', ),
  1855. treat_as_error=False,
  1856. excluded_paths=(
  1857. '^chrome/browser/ui/content_settings/',
  1858. '^components/content_settings/',
  1859. '^components/privacy_sandbox/tracking_protection_settings.cc',
  1860. '.*test.cc',
  1861. ),
  1862. ),
  1863. BanRule(
  1864. pattern=r'/\bg_signal_connect',
  1865. explanation=('Use ScopedGSignal instead of g_signal_connect*()', ),
  1866. treat_as_error=True,
  1867. excluded_paths=('^ui/base/glib/scoped_gsignal.h', ),
  1868. ),
  1869. BanRule(
  1870. pattern=r'features::kIsolatedWebApps',
  1871. explanation=(
  1872. 'Do not use `features::kIsolatedWebApps` directly to guard Isolated ',
  1873. 'Web App code. ',
  1874. 'Use `content::IsolatedWebAppsPolicy::AreIsolatedWebAppsEnabled()` in ',
  1875. 'the browser process or check the `kEnableIsolatedWebAppsInRenderer` ',
  1876. 'command line flag in the renderer process.',
  1877. ),
  1878. treat_as_error=True,
  1879. excluded_paths=_TEST_CODE_EXCLUDED_PATHS +
  1880. ('^chrome/browser/about_flags.cc',
  1881. '^chrome/browser/web_applications/isolated_web_apps/chrome_content_browser_client_isolated_web_apps_part.cc',
  1882. '^chrome/browser/ui/startup/bad_flags_prompt.cc',
  1883. '^content/shell/browser/shell_content_browser_client.cc')),
  1884. BanRule(
  1885. pattern=r'features::kIsolatedWebAppDevMode',
  1886. explanation=(
  1887. 'Do not use `features::kIsolatedWebAppDevMode` directly to guard code ',
  1888. 'related to Isolated Web App Developer Mode. ',
  1889. 'Use `web_app::IsIwaDevModeEnabled()` instead.',
  1890. ),
  1891. treat_as_error=True,
  1892. excluded_paths=_TEST_CODE_EXCLUDED_PATHS + (
  1893. '^chrome/browser/about_flags.cc',
  1894. '^chrome/browser/web_applications/isolated_web_apps/isolated_web_app_features.cc',
  1895. '^chrome/browser/ui/startup/bad_flags_prompt.cc',
  1896. )),
  1897. BanRule(
  1898. pattern=r'features::kIsolatedWebAppUnmanagedInstall',
  1899. explanation=(
  1900. 'Do not use `features::kIsolatedWebAppUnmanagedInstall` directly to ',
  1901. 'guard code related to unmanaged install flow for Isolated Web Apps. ',
  1902. 'Use `web_app::IsIwaUnmanagedInstallEnabled()` instead.',
  1903. ),
  1904. treat_as_error=True,
  1905. excluded_paths=_TEST_CODE_EXCLUDED_PATHS + (
  1906. '^chrome/browser/about_flags.cc',
  1907. '^chrome/browser/web_applications/isolated_web_apps/isolated_web_app_features.cc',
  1908. )),
  1909. BanRule(
  1910. pattern='/(CUIAutomation|AccessibleObjectFromWindow)',
  1911. explanation=
  1912. ('Direct usage of UIAutomation or IAccessible2 in client code is '
  1913. 'discouraged in Chromium, as it is not an assistive technology and '
  1914. 'should not rely on accessibility APIs directly. These APIs can '
  1915. 'introduce significant performance overhead. However, if you believe '
  1916. 'your use case warrants an exception, please discuss it with an '
  1917. 'accessibility owner before proceeding. For more information on the '
  1918. 'performance implications, see https://docs.google.com/document/d/1jN4itpCe_bDXF0BhFaYwv4xVLsCWkL9eULdzjmLzkuk/edit#heading=h.pwth3nbwdub0.',
  1919. ),
  1920. treat_as_error=False,
  1921. ),
  1922. BanRule(
  1923. pattern=r'/WIDGET_OWNS_NATIVE_WIDGET|'
  1924. r'NATIVE_WIDGET_OWNS_WIDGET',
  1925. explanation=
  1926. ('WIDGET_OWNS_NATIVE_WIDGET and NATIVE_WIDGET_OWNS_WIDGET are in the '
  1927. 'process of being deprecated. Consider using the new '
  1928. 'CLIENT_OWNS_WIDGET ownership model. Eventually, this will be the only '
  1929. 'available ownership model available and the associated enumeration'
  1930. 'will be removed.', ),
  1931. treat_as_error=False,
  1932. ),
  1933. BanRule(
  1934. pattern='ProfileManager::GetLastUsedProfile',
  1935. explanation=
  1936. ('Most code should already be scoped to a Profile. Pass in a Profile* '
  1937. 'or retreive from an existing entity with a reference to the Profile '
  1938. '(e.g. WebContents).', ),
  1939. treat_as_error=False,
  1940. ),
  1941. BanRule(
  1942. pattern=(r'/FindBrowserWithUiElementContext|'
  1943. r'FindBrowserWithTab|'
  1944. r'FindBrowserWithGroup|'
  1945. r'FindTabbedBrowser|'
  1946. r'FindAnyBrowser|'
  1947. r'FindBrowserWithProfile|'
  1948. r'FindLastActive|'
  1949. r'FindBrowserWithActiveWindow'),
  1950. explanation=
  1951. ('Most code should already be scoped to a Browser. Pass in a Browser* '
  1952. 'or retreive from an existing entity with a reference to the Browser.',
  1953. ),
  1954. treat_as_error=False,
  1955. ),
  1956. BanRule(
  1957. pattern='BrowserUserData',
  1958. explanation=
  1959. ('Do not use BrowserUserData to store state on a Browser instance. '
  1960. 'Instead use BrowserWindowFeatures. BrowserWindowFeatures is '
  1961. 'functionally identical but has two benefits: it does not force a '
  1962. 'dependency onto class Browser, and lifetime semantics are explicit '
  1963. 'rather than implicit. See BrowserUserData header file for more '
  1964. 'details.', ),
  1965. treat_as_error=False,
  1966. excluded_paths=(
  1967. # Exclude iOS as the iOS implementation of BrowserUserData is separate
  1968. # and still in use.
  1969. '^ios/',
  1970. ),
  1971. ),
  1972. BanRule(
  1973. pattern=r'UNSAFE_TODO(',
  1974. explanation=
  1975. ('Do not use UNSAFE_TODO() to write new unsafe code. Use only when '
  1976. 'removing a pre-existing file-wide allow_unsafe_buffers pragma, or '
  1977. 'when incrementally converting code off of unsafe interfaces',
  1978. ),
  1979. treat_as_error=False,
  1980. ),
  1981. BanRule(
  1982. pattern=r'UNSAFE_BUFFERS(',
  1983. explanation=
  1984. ('Try to avoid using UNSAFE_BUFFERS() if at all possible. Otherwise, '
  1985. 'be sure to justify in a // SAFETY comment why other options are not '
  1986. 'available, and why the code is safe.',
  1987. ),
  1988. treat_as_error=False,
  1989. ),
  1990. BanRule(
  1991. pattern='BrowserWithTestWindowTest',
  1992. explanation=
  1993. ('Do not use BrowserWithTestWindowTest. By instantiating an instance '
  1994. 'of class Browser, the test is no longer a unit test but is instead a '
  1995. 'browser test. The class BrowserWithTestWindowTest forces production '
  1996. 'logic to take on test-only conditionals, which is an anti-pattern. '
  1997. 'Features should be performing dependency injection rather than '
  1998. 'directly using class Browser. See '
  1999. 'docs/chrome_browser_design_principles.md for more details.',
  2000. ),
  2001. treat_as_error=False,
  2002. ),
  2003. BanRule(
  2004. pattern='TestWithBrowserView',
  2005. explanation=
  2006. ('Do not use TestWithBrowserView. See '
  2007. 'docs/chrome_browser_design_principles.md for details. If you want '
  2008. 'to write a test that has both a Browser and a BrowserView, create '
  2009. 'a browser_test. If you want to write a unit_test, your code must '
  2010. 'not reference Browser*.',
  2011. ),
  2012. treat_as_error=False,
  2013. ),
  2014. BanRule(
  2015. pattern='RunUntilIdle',
  2016. explanation=
  2017. ('Do not RunUntilIdle. If possible, explicitly quit the run loop using '
  2018. 'run_loop.Quit() or run_loop.QuitClosure() if completion can be '
  2019. 'observed using a lambda or callback. Otherwise, wait for the '
  2020. 'condition to be true via base::test::RunUntil().',
  2021. ),
  2022. treat_as_error=False,
  2023. ),
  2024. BanRule(
  2025. pattern=r'/\bstd::(literals|string_literals|string_view_literals)\b',
  2026. explanation = (
  2027. 'User-defined literals are banned by the Google C++ style guide. '
  2028. 'Exceptions are provided in Chrome for string and string_view '
  2029. 'literals that embed \\0.',
  2030. ),
  2031. treat_as_error=True,
  2032. excluded_paths=(
  2033. # Various tests or test helpers that embed NUL in strings or
  2034. # string_views.
  2035. r'^base/strings/string_util_unittest\.cc',
  2036. r'^base/strings/utf_string_conversions_unittest\.cc',
  2037. r'^chrome/browser/ash/crosapi/browser_data_back_migrator_unittest\.cc',
  2038. r'^chrome/browser/ash/crosapi/browser_data_migrator_util_unittest\.cc',
  2039. r'^chrome/browser/ash/crosapi/move_migrator_unittest\.cc',
  2040. r'^chromeos/ash/experiences/arc/session/serial_number_util_unittest\.cc',
  2041. r'^components/history/core/browser/visit_annotations_database\.cc',
  2042. r'^components/history/core/browser/visit_annotations_database_unittest\.cc',
  2043. r'^components/os_crypt/sync/os_crypt_unittest\.cc',
  2044. r'^components/password_manager/core/browser/credentials_cleaner_unittest\.cc',
  2045. r'^content/browser/file_system_access/file_system_access_file_writer_impl_unittest\.cc',
  2046. r'^net/cookies/parsed_cookie_unittest\.cc',
  2047. r'^third_party/blink/renderer/modules/webcodecs/test_helpers\.cc',
  2048. r'^third_party/blink/renderer/modules/websockets/websocket_channel_impl_test\.cc',
  2049. ),
  2050. ),
  2051. BanRule(
  2052. pattern='BUILDFLAG(GOOGLE_CHROME_BRANDING)',
  2053. explanation=
  2054. ('Code gated by GOOGLE_CHROME_BRANDING is effectively untested. This '
  2055. 'is typically wrong. Valid use cases are glue for private modules '
  2056. 'shipped alongside Chrome, and installation-related logic.',
  2057. ),
  2058. treat_as_error=False,
  2059. ),
  2060. BanRule(
  2061. pattern='defined(OFFICIAL_BUILD)',
  2062. explanation=
  2063. ('Code gated by OFFICIAL_BUILD is effectively untested. This '
  2064. 'is typically wrong. One valid use case is low-level code that '
  2065. 'handles subtleties related to high-levels of optimizations that come '
  2066. 'with OFFICIAL_BUILD.',
  2067. ),
  2068. treat_as_error=False,
  2069. ),
  2070. BanRule(
  2071. pattern='WebContentsDestroyed',
  2072. explanation=
  2073. ('Do not use this method. It is invoked half-way through the '
  2074. 'destructor of WebContentsImpl and using it often results in crashes '
  2075. 'or surprising behavior. Conceptually, this is only necessary by '
  2076. 'objects that depend on, but outlive the WebContents. These objects '
  2077. 'should instead coordinate with the owner of the WebContents which is '
  2078. 'responsible for destroying the WebContents.',
  2079. ),
  2080. treat_as_error=False,
  2081. ),
  2082. BanRule(
  2083. pattern=(r'/IS_CHROMEOS_ASH|'
  2084. r'IS_CHROMEOS_LACROS'),
  2085. explanation=
  2086. ('Lacros is deprecated. Please do not use IS_CHROMEOS_ASH and '
  2087. 'IS_CHROMEOS_LACROS anymore. Instead, remove the code section under '
  2088. 'IS_CHROMEOS_LACROS and use IS_CHROMEOS for ChromeOS-only code.',
  2089. ),
  2090. treat_as_error=False,
  2091. ),
  2092. BanRule(
  2093. pattern=(r'namespace {'),
  2094. explanation=
  2095. ('Anonymous namespaces are disallowed in C++ header files. See '
  2096. 'https://google.github.io/styleguide/cppguide.html#Internal_Linkage '
  2097. ' for details.',
  2098. ),
  2099. treat_as_error=False,
  2100. excluded_paths=[
  2101. _THIRD_PARTY_EXCEPT_BLINK, # Don't warn in third_party folders.
  2102. r'^(?!.*\.h$).*$', # Exclude all files except those that end in .h
  2103. ],
  2104. ),
  2105. )
  2106. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING = (
  2107. 'Used a predicate related to signin::ConsentLevel::kSync which will always '
  2108. 'return false in the future (crbug.com/40066949). Prefer using a predicate '
  2109. 'that also supports signin::ConsentLevel::kSignin when appropriate. It is '
  2110. 'safe to ignore this warning if you are just moving an existing call, or if '
  2111. 'you want special handling for users in the legacy state. In doubt, reach '
  2112. 'out to //components/sync/OWNERS.',
  2113. )
  2114. # C++ functions related to signin::ConsentLevel::kSync which are deprecated.
  2115. _DEPRECATED_SYNC_CONSENT_CPP_FUNCTIONS : Sequence[BanRule] = (
  2116. BanRule(
  2117. 'HasSyncConsent',
  2118. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2119. False,
  2120. ),
  2121. BanRule(
  2122. 'CanSyncFeatureStart',
  2123. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2124. False,
  2125. ),
  2126. BanRule(
  2127. 'IsSyncFeatureEnabled',
  2128. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2129. False,
  2130. ),
  2131. BanRule(
  2132. 'IsSyncFeatureActive',
  2133. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2134. False,
  2135. ),
  2136. )
  2137. # Java functions related to signin::ConsentLevel::kSync which are deprecated.
  2138. _DEPRECATED_SYNC_CONSENT_JAVA_FUNCTIONS : Sequence[BanRule] = (
  2139. BanRule(
  2140. 'hasSyncConsent',
  2141. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2142. False,
  2143. ),
  2144. BanRule(
  2145. 'canSyncFeatureStart',
  2146. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2147. False,
  2148. ),
  2149. BanRule(
  2150. 'isSyncFeatureEnabled',
  2151. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2152. False,
  2153. ),
  2154. BanRule(
  2155. 'isSyncFeatureActive',
  2156. _DEPRECATED_SYNC_CONSENT_FUNCTION_WARNING,
  2157. False,
  2158. ),
  2159. )
  2160. _BANNED_MOJOM_PATTERNS : Sequence[BanRule] = (
  2161. BanRule(
  2162. 'handle<shared_buffer>',
  2163. (
  2164. 'Please use one of the more specific shared memory types instead:',
  2165. ' mojo_base.mojom.ReadOnlySharedMemoryRegion',
  2166. ' mojo_base.mojom.WritableSharedMemoryRegion',
  2167. ' mojo_base.mojom.UnsafeSharedMemoryRegion',
  2168. ),
  2169. True,
  2170. ),
  2171. )
  2172. _IPC_ENUM_TRAITS_DEPRECATED = (
  2173. 'You are using IPC_ENUM_TRAITS() in your code. It has been deprecated.\n'
  2174. 'See http://www.chromium.org/Home/chromium-security/education/'
  2175. 'security-tips-for-ipc')
  2176. _LONG_PATH_ERROR = (
  2177. 'Some files included in this CL have file names that are too long (> 200'
  2178. ' characters). If committed, these files will cause issues on Windows. See'
  2179. ' https://crbug.com/612667 for more details.'
  2180. )
  2181. _JAVA_MULTIPLE_DEFINITION_EXCLUDED_PATHS = [
  2182. r".*/BuildHooksAndroidImpl\.java",
  2183. r".*/LicenseContentProvider\.java",
  2184. r".*/PlatformServiceBridgeImpl.java",
  2185. r".*chrome/android/feed/dummy/.*\.java",
  2186. ]
  2187. # List of image extensions that are used as resources in chromium.
  2188. _IMAGE_EXTENSIONS = ['.svg', '.png', '.webp']
  2189. # These paths contain test data and other known invalid JSON files.
  2190. _KNOWN_TEST_DATA_AND_INVALID_JSON_FILE_PATTERNS = [
  2191. r'test/data/',
  2192. r'testing/buildbot/',
  2193. r'^components/policy/resources/policy_templates\.json$',
  2194. r'^third_party/protobuf/',
  2195. r'^third_party/blink/perf_tests/speedometer.*/resources/todomvc/learn\.json',
  2196. r'^third_party/blink/renderer/devtools/protocol\.json$',
  2197. r'^third_party/blink/web_tests/external/wpt/',
  2198. r'^tools/perf/',
  2199. r'^tools/traceline/svgui/startup-release.json',
  2200. # vscode configuration files allow comments
  2201. r'^tools/vscode/',
  2202. ]
  2203. # These are not checked on the public chromium-presubmit trybot.
  2204. # Add files here that rely on .py files that exists only for target_os="android"
  2205. # checkouts.
  2206. _ANDROID_SPECIFIC_PYDEPS_FILES = [
  2207. 'chrome/android/features/create_stripped_java_factory.pydeps',
  2208. ]
  2209. _GENERIC_PYDEPS_FILES = [
  2210. 'android_webview/tools/run_cts.pydeps',
  2211. 'build/android/apk_operations.pydeps',
  2212. 'build/android/devil_chromium.pydeps',
  2213. 'build/android/gyp/aar.pydeps',
  2214. 'build/android/gyp/aidl.pydeps',
  2215. 'build/android/gyp/apkbuilder.pydeps',
  2216. 'build/android/gyp/assert_static_initializers.pydeps',
  2217. 'build/android/gyp/binary_baseline_profile.pydeps',
  2218. 'build/android/gyp/bytecode_rewriter.pydeps',
  2219. 'build/android/gyp/check_flag_expectations.pydeps',
  2220. 'build/android/gyp/check_for_missing_direct_deps.pydeps',
  2221. 'build/android/gyp/compile_java.pydeps',
  2222. 'build/android/gyp/compile_kt.pydeps',
  2223. 'build/android/gyp/compile_resources.pydeps',
  2224. 'build/android/gyp/copy_ex.pydeps',
  2225. 'build/android/gyp/create_apk_operations_script.pydeps',
  2226. 'build/android/gyp/create_app_bundle.pydeps',
  2227. 'build/android/gyp/create_app_bundle_apks.pydeps',
  2228. 'build/android/gyp/create_bundle_wrapper_script.pydeps',
  2229. 'build/android/gyp/create_java_binary_script.pydeps',
  2230. 'build/android/gyp/create_r_java.pydeps',
  2231. 'build/android/gyp/create_r_txt.pydeps',
  2232. 'build/android/gyp/create_size_info_files.pydeps',
  2233. 'build/android/gyp/create_stub_manifest.pydeps',
  2234. 'build/android/gyp/create_test_apk_wrapper_script.pydeps',
  2235. 'build/android/gyp/create_ui_locale_resources.pydeps',
  2236. 'build/android/gyp/dex.pydeps',
  2237. 'build/android/gyp/dist_aar.pydeps',
  2238. 'build/android/gyp/errorprone.pydeps',
  2239. 'build/android/gyp/filter_zip.pydeps',
  2240. 'build/android/gyp/flatc_java.pydeps',
  2241. 'build/android/gyp/gcc_preprocess.pydeps',
  2242. 'build/android/gyp/generate_linker_version_script.pydeps',
  2243. 'build/android/gyp/ijar.pydeps',
  2244. 'build/android/gyp/jacoco_instr.pydeps',
  2245. 'build/android/gyp/java_cpp_enum.pydeps',
  2246. 'build/android/gyp/java_cpp_features.pydeps',
  2247. 'build/android/gyp/java_cpp_strings.pydeps',
  2248. 'build/android/gyp/java_google_api_keys.pydeps',
  2249. 'build/android/gyp/jinja_template.pydeps',
  2250. 'build/android/gyp/lint.pydeps',
  2251. 'build/android/gyp/merge_manifest.pydeps',
  2252. 'build/android/gyp/optimize_resources.pydeps',
  2253. 'build/android/gyp/prepare_resources.pydeps',
  2254. 'build/android/gyp/process_native_prebuilt.pydeps',
  2255. 'build/android/gyp/proguard.pydeps',
  2256. 'build/android/gyp/rename_java_classes.pydeps',
  2257. 'build/android/gyp/system_image_apks.pydeps',
  2258. 'build/android/gyp/trace_event_bytecode_rewriter.pydeps',
  2259. 'build/android/gyp/tracereferences.pydeps',
  2260. 'build/android/gyp/turbine.pydeps',
  2261. 'build/android/gyp/unused_resources.pydeps',
  2262. 'build/android/gyp/validate_static_library_dex_references.pydeps',
  2263. 'build/android/gyp/write_build_config.pydeps',
  2264. 'build/android/gyp/write_native_libraries_java.pydeps',
  2265. 'build/android/gyp/zip.pydeps',
  2266. 'build/android/incremental_install/generate_android_manifest.pydeps',
  2267. 'build/android/incremental_install/write_installer_json.pydeps',
  2268. 'build/android/pylib/results/presentation/test_results_presentation.pydeps',
  2269. 'build/android/resource_sizes.pydeps',
  2270. 'build/android/test_runner.pydeps',
  2271. 'build/android/test_wrapper/logdog_wrapper.pydeps',
  2272. 'build/protoc_java.pydeps',
  2273. 'chrome/android/monochrome/scripts/monochrome_python_tests.pydeps',
  2274. 'chrome/test/chromedriver/log_replay/client_replay_unittest.pydeps',
  2275. 'chrome/test/chromedriver/test/run_py_tests.pydeps',
  2276. 'chromecast/resource_sizes/chromecast_resource_sizes.pydeps',
  2277. 'components/cronet/tools/check_combined_proguard_file.pydeps',
  2278. 'components/cronet/tools/generate_proguard_file.pydeps',
  2279. 'components/cronet/tools/jar_src.pydeps',
  2280. 'components/module_installer/android/module_desc_java.pydeps',
  2281. 'content/public/android/generate_child_service.pydeps',
  2282. 'fuchsia_web/av_testing/av_sync_tests.pydeps',
  2283. 'net/tools/testserver/testserver.pydeps',
  2284. 'testing/scripts/run_isolated_script_test.pydeps',
  2285. 'testing/merge_scripts/standard_isolated_script_merge.pydeps',
  2286. 'testing/merge_scripts/standard_gtest_merge.pydeps',
  2287. 'testing/merge_scripts/code_coverage/merge_results.pydeps',
  2288. 'testing/merge_scripts/code_coverage/merge_steps.pydeps',
  2289. 'third_party/android_platform/development/scripts/stack.pydeps',
  2290. 'third_party/blink/renderer/bindings/scripts/build_web_idl_database.pydeps',
  2291. 'third_party/blink/renderer/bindings/scripts/check_generated_file_list.pydeps',
  2292. 'third_party/blink/renderer/bindings/scripts/collect_idl_files.pydeps',
  2293. 'third_party/blink/renderer/bindings/scripts/generate_bindings.pydeps',
  2294. 'third_party/blink/renderer/bindings/scripts/generate_event_interface_names.pydeps',
  2295. 'third_party/blink/renderer/bindings/scripts/validate_web_idl.pydeps',
  2296. 'third_party/blink/tools/blinkpy/web_tests/merge_results.pydeps',
  2297. 'third_party/blink/tools/merge_web_test_results.pydeps',
  2298. 'tools/binary_size/sizes.pydeps',
  2299. 'tools/binary_size/supersize.pydeps',
  2300. 'tools/perf/process_perf_results.pydeps',
  2301. 'tools/pgo/generate_profile.pydeps',
  2302. ]
  2303. _ALL_PYDEPS_FILES = _ANDROID_SPECIFIC_PYDEPS_FILES + _GENERIC_PYDEPS_FILES
  2304. # Bypass the AUTHORS check for these accounts.
  2305. _KNOWN_ROBOTS = set(
  2306. ) | set('%s@appspot.gserviceaccount.com' % s for s in ('findit-for-me', 'luci-bisection')
  2307. ) | set('%s@developer.gserviceaccount.com' % s for s in ('3su6n15k.default',)
  2308. ) | set('%s@chops-service-accounts.iam.gserviceaccount.com' % s
  2309. for s in ('bling-autoroll-builder', 'v8-ci-autoroll-builder',
  2310. 'wpt-autoroller', 'chrome-weblayer-builder',
  2311. 'lacros-version-skew-roller', 'skylab-test-cros-roller',
  2312. 'infra-try-recipes-tester', 'lacros-tracking-roller',
  2313. 'lacros-sdk-version-roller', 'chrome-automated-expectation',
  2314. 'chromium-automated-expectation', 'chrome-branch-day',
  2315. 'chromium-autosharder')
  2316. ) | set('%s@skia-public.iam.gserviceaccount.com' % s
  2317. for s in ('chromium-autoroll', 'chromium-release-autoroll')
  2318. ) | set('%s@skia-corp.google.com.iam.gserviceaccount.com' % s
  2319. for s in ('chromium-internal-autoroll',)
  2320. ) | set('%s@system.gserviceaccount.com' % s
  2321. for s in ('chrome-screen-ai-releaser',)
  2322. ) | set('%s@owners-cleanup-prod.google.com.iam.gserviceaccount.com' % s
  2323. for s in ('swarming-tasks',)
  2324. ) | set('%s@fuchsia-infra.iam.gserviceaccount.com' % s
  2325. for s in ('global-integration-try-builder',
  2326. 'global-integration-ci-builder')
  2327. ) | set('%s@prod.google.com' % s
  2328. for s in ('chops-security-borg',
  2329. 'chops-security-cronjobs-cpesuggest'))
  2330. _INVALID_GRD_FILE_LINE = [
  2331. (r'<file lang=.* path=.*', 'Path should come before lang in GRD files.')
  2332. ]
  2333. def _IsCPlusPlusFile(input_api, file_path):
  2334. """Returns True if this file contains C++-like code (and not Python,
  2335. Go, Java, MarkDown, ...)"""
  2336. ext = input_api.os_path.splitext(file_path)[1]
  2337. # This list is compatible with CppChecker.IsCppFile but we should
  2338. # consider adding ".c" to it. If we do that we can use this function
  2339. # at more places in the code.
  2340. return ext in (
  2341. '.h',
  2342. '.cc',
  2343. '.cpp',
  2344. '.m',
  2345. '.mm',
  2346. )
  2347. def _IsCPlusPlusHeaderFile(input_api, file_path):
  2348. return input_api.os_path.splitext(file_path)[1] == ".h"
  2349. def _IsJavaFile(input_api, file_path):
  2350. return input_api.os_path.splitext(file_path)[1] == ".java"
  2351. def _IsProtoFile(input_api, file_path):
  2352. return input_api.os_path.splitext(file_path)[1] == ".proto"
  2353. def _IsXmlOrGrdFile(input_api, file_path):
  2354. ext = input_api.os_path.splitext(file_path)[1]
  2355. return ext in ('.grd', '.xml')
  2356. def _IsMojomFile(input_api, file_path):
  2357. return input_api.os_path.splitext(file_path)[1] == ".mojom"
  2358. def CheckNoUpstreamDepsOnClank(input_api, output_api):
  2359. """Prevent additions of dependencies from the upstream repo on //clank."""
  2360. # clank can depend on clank
  2361. if input_api.change.RepositoryRoot().endswith('clank'):
  2362. return []
  2363. build_file_patterns = [
  2364. r'(.+/)?BUILD\.gn',
  2365. r'.+\.gni',
  2366. ]
  2367. excluded_files = [r'build[/\\]config[/\\]android[/\\]config\.gni']
  2368. bad_pattern = input_api.re.compile(r'^[^#]*//clank')
  2369. error_message = 'Disallowed import on //clank in an upstream build file:'
  2370. def FilterFile(affected_file):
  2371. return input_api.FilterSourceFile(affected_file,
  2372. files_to_check=build_file_patterns,
  2373. files_to_skip=excluded_files)
  2374. problems = []
  2375. for f in input_api.AffectedSourceFiles(FilterFile):
  2376. local_path = f.LocalPath()
  2377. for line_number, line in f.ChangedContents():
  2378. if (bad_pattern.search(line)):
  2379. problems.append('%s:%d\n %s' %
  2380. (local_path, line_number, line.strip()))
  2381. if problems:
  2382. return [output_api.PresubmitPromptOrNotify(error_message, problems)]
  2383. else:
  2384. return []
  2385. def CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
  2386. """Attempts to prevent use of functions intended only for testing in
  2387. non-testing code. For now this is just a best-effort implementation
  2388. that ignores header files and may have some false positives. A
  2389. better implementation would probably need a proper C++ parser.
  2390. """
  2391. # We only scan .cc files and the like, as the declaration of
  2392. # for-testing functions in header files are hard to distinguish from
  2393. # calls to such functions without a proper C++ parser.
  2394. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  2395. base_function_pattern = r'[ :]test::[^\s]+|ForTest(s|ing)?|for_test(s|ing)?'
  2396. inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' %
  2397. base_function_pattern)
  2398. comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
  2399. allowlist_pattern = input_api.re.compile(r'// IN-TEST$')
  2400. exclusion_pattern = input_api.re.compile(
  2401. r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' %
  2402. (base_function_pattern, base_function_pattern))
  2403. # Avoid a false positive in this case, where the method name, the ::, and
  2404. # the closing { are all on different lines due to line wrapping.
  2405. # HelperClassForTesting::
  2406. # HelperClassForTesting(
  2407. # args)
  2408. # : member(0) {}
  2409. method_defn_pattern = input_api.re.compile(r'[A-Za-z0-9_]+::$')
  2410. def FilterFile(affected_file):
  2411. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  2412. input_api.DEFAULT_FILES_TO_SKIP)
  2413. return input_api.FilterSourceFile(
  2414. affected_file,
  2415. files_to_check=file_inclusion_pattern,
  2416. files_to_skip=files_to_skip)
  2417. problems = []
  2418. for f in input_api.AffectedSourceFiles(FilterFile):
  2419. local_path = f.LocalPath()
  2420. in_method_defn = False
  2421. for line_number, line in f.ChangedContents():
  2422. if (inclusion_pattern.search(line)
  2423. and not comment_pattern.search(line)
  2424. and not exclusion_pattern.search(line)
  2425. and not allowlist_pattern.search(line)
  2426. and not in_method_defn):
  2427. problems.append('%s:%d\n %s' %
  2428. (local_path, line_number, line.strip()))
  2429. in_method_defn = method_defn_pattern.search(line)
  2430. if problems:
  2431. return [
  2432. output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)
  2433. ]
  2434. else:
  2435. return []
  2436. def CheckNoProductionCodeUsingTestOnlyFunctionsJava(input_api, output_api):
  2437. """This is a simplified version of
  2438. CheckNoProductionCodeUsingTestOnlyFunctions for Java files.
  2439. """
  2440. javadoc_start_re = input_api.re.compile(r'^\s*/\*\*')
  2441. javadoc_end_re = input_api.re.compile(r'^\s*\*/')
  2442. name_pattern = r'ForTest(s|ing)?'
  2443. # Describes an occurrence of "ForTest*" inside a // comment.
  2444. comment_re = input_api.re.compile(r'//.*%s' % name_pattern)
  2445. # Describes @VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
  2446. annotation_re = input_api.re.compile(r'@VisibleForTesting\(')
  2447. # Catch calls.
  2448. inclusion_re = input_api.re.compile(r'(%s)\s*\(' % name_pattern)
  2449. # Ignore definitions. (Comments are ignored separately.)
  2450. exclusion_re = input_api.re.compile(r'(%s)[^;]+\{' % name_pattern)
  2451. allowlist_re = input_api.re.compile(r'// IN-TEST$')
  2452. problems = []
  2453. sources = lambda x: input_api.FilterSourceFile(
  2454. x,
  2455. files_to_skip=(('(?i).*test', r'.*\/junit\/') + input_api.
  2456. DEFAULT_FILES_TO_SKIP),
  2457. files_to_check=[r'.*\.java$'])
  2458. for f in input_api.AffectedFiles(include_deletes=False,
  2459. file_filter=sources):
  2460. local_path = f.LocalPath()
  2461. is_inside_javadoc = False
  2462. for line_number, line in f.ChangedContents():
  2463. if is_inside_javadoc and javadoc_end_re.search(line):
  2464. is_inside_javadoc = False
  2465. if not is_inside_javadoc and javadoc_start_re.search(line):
  2466. is_inside_javadoc = True
  2467. if is_inside_javadoc:
  2468. continue
  2469. if (inclusion_re.search(line) and not comment_re.search(line)
  2470. and not annotation_re.search(line)
  2471. and not allowlist_re.search(line)
  2472. and not exclusion_re.search(line)):
  2473. problems.append('%s:%d\n %s' %
  2474. (local_path, line_number, line.strip()))
  2475. if problems:
  2476. return [
  2477. output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)
  2478. ]
  2479. else:
  2480. return []
  2481. def CheckNoIOStreamInHeaders(input_api, output_api):
  2482. """Checks to make sure no .h files include <iostream>."""
  2483. files = []
  2484. pattern = input_api.re.compile(r'^#include\s*<iostream>',
  2485. input_api.re.MULTILINE)
  2486. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  2487. if not f.LocalPath().endswith('.h'):
  2488. continue
  2489. contents = input_api.ReadFile(f)
  2490. if pattern.search(contents):
  2491. files.append(f)
  2492. if len(files):
  2493. return [
  2494. output_api.PresubmitError(
  2495. 'Do not #include <iostream> in header files, since it inserts static '
  2496. 'initialization into every file including the header. Instead, '
  2497. '#include <ostream>. See http://crbug.com/94794', files)
  2498. ]
  2499. return []
  2500. def CheckNoStrCatRedefines(input_api, output_api):
  2501. """Checks no windows headers with StrCat redefined are included directly."""
  2502. files = []
  2503. files_to_check = (r'.+%s' % _HEADER_EXTENSIONS,
  2504. r'.+%s' % _IMPLEMENTATION_EXTENSIONS)
  2505. files_to_skip = (input_api.DEFAULT_FILES_TO_SKIP +
  2506. _NON_BASE_DEPENDENT_PATHS)
  2507. sources_filter = lambda f: input_api.FilterSourceFile(
  2508. f, files_to_check=files_to_check, files_to_skip=files_to_skip)
  2509. pattern_deny = input_api.re.compile(
  2510. r'^#include\s*[<"](shlwapi|atlbase|propvarutil|sphelper).h[">]',
  2511. input_api.re.MULTILINE)
  2512. pattern_allow = input_api.re.compile(
  2513. r'^#include\s"base/win/windows_defines.inc"', input_api.re.MULTILINE)
  2514. for f in input_api.AffectedSourceFiles(sources_filter):
  2515. contents = input_api.ReadFile(f)
  2516. if pattern_deny.search(
  2517. contents) and not pattern_allow.search(contents):
  2518. files.append(f.LocalPath())
  2519. if len(files):
  2520. return [
  2521. output_api.PresubmitError(
  2522. 'Do not #include shlwapi.h, atlbase.h, propvarutil.h or sphelper.h '
  2523. 'directly since they pollute code with StrCat macro. Instead, '
  2524. 'include matching header from base/win. See http://crbug.com/856536',
  2525. files)
  2526. ]
  2527. return []
  2528. def _CheckNoUNIT_TESTInSourceFiles(input_api, f):
  2529. problems = []
  2530. unit_test_macro = input_api.re.compile(
  2531. '^\s*#.*(?:ifn?def\s+UNIT_TEST|defined\s*\(?\s*UNIT_TEST\s*\)?)(?:$|\s+)')
  2532. for line_num, line in f.ChangedContents():
  2533. if unit_test_macro.match(line):
  2534. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  2535. return problems
  2536. def CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
  2537. """Checks to make sure no source files use UNIT_TEST."""
  2538. problems = []
  2539. for f in input_api.AffectedFiles():
  2540. if (not f.LocalPath().endswith(('.cc', '.mm'))):
  2541. continue
  2542. problems.extend(
  2543. _CheckNoUNIT_TESTInSourceFiles(input_api, f))
  2544. if not problems:
  2545. return []
  2546. return [
  2547. output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
  2548. '\n'.join(problems))
  2549. ]
  2550. def CheckNoDISABLETypoInTests(input_api, output_api):
  2551. """Checks to prevent attempts to disable tests with DISABLE_ prefix.
  2552. This test warns if somebody tries to disable a test with the DISABLE_ prefix
  2553. instead of DISABLED_. To filter false positives, reports are only generated
  2554. if a corresponding MAYBE_ line exists.
  2555. """
  2556. problems = []
  2557. # The following two patterns are looked for in tandem - is a test labeled
  2558. # as MAYBE_ followed by a DISABLE_ (instead of the correct DISABLED)
  2559. maybe_pattern = input_api.re.compile(r'MAYBE_([a-zA-Z0-9_]+)')
  2560. disable_pattern = input_api.re.compile(r'DISABLE_([a-zA-Z0-9_]+)')
  2561. # This is for the case that a test is disabled on all platforms.
  2562. full_disable_pattern = input_api.re.compile(
  2563. r'^\s*TEST[^(]*\([a-zA-Z0-9_]+,\s*DISABLE_[a-zA-Z0-9_]+\)',
  2564. input_api.re.MULTILINE)
  2565. for f in input_api.AffectedFiles(include_deletes=False):
  2566. if not 'test' in f.LocalPath() or not f.LocalPath().endswith('.cc'):
  2567. continue
  2568. # Search for MAYBE_, DISABLE_ pairs.
  2569. disable_lines = {} # Maps of test name to line number.
  2570. maybe_lines = {}
  2571. for line_num, line in f.ChangedContents():
  2572. disable_match = disable_pattern.search(line)
  2573. if disable_match:
  2574. disable_lines[disable_match.group(1)] = line_num
  2575. maybe_match = maybe_pattern.search(line)
  2576. if maybe_match:
  2577. maybe_lines[maybe_match.group(1)] = line_num
  2578. # Search for DISABLE_ occurrences within a TEST() macro.
  2579. disable_tests = set(disable_lines.keys())
  2580. maybe_tests = set(maybe_lines.keys())
  2581. for test in disable_tests.intersection(maybe_tests):
  2582. problems.append(' %s:%d' % (f.LocalPath(), disable_lines[test]))
  2583. contents = input_api.ReadFile(f)
  2584. full_disable_match = full_disable_pattern.search(contents)
  2585. if full_disable_match:
  2586. problems.append(' %s' % f.LocalPath())
  2587. if not problems:
  2588. return []
  2589. return [
  2590. output_api.PresubmitPromptWarning(
  2591. 'Attempt to disable a test with DISABLE_ instead of DISABLED_?\n' +
  2592. '\n'.join(problems))
  2593. ]
  2594. def CheckForgettingMAYBEInTests(input_api, output_api):
  2595. """Checks to make sure tests disabled conditionally are not missing a
  2596. corresponding MAYBE_ prefix.
  2597. """
  2598. # Expect at least a lowercase character in the test name. This helps rule out
  2599. # false positives with macros wrapping the actual tests name.
  2600. define_maybe_pattern = input_api.re.compile(
  2601. r'^\#define MAYBE_(?P<test_name>\w*[a-z]\w*)')
  2602. # The test_maybe_pattern needs to handle all of these forms. The standard:
  2603. # IN_PROC_TEST_F(SyncTest, MAYBE_Start) {
  2604. # With a wrapper macro around the test name:
  2605. # IN_PROC_TEST_F(SyncTest, E2E_ENABLED(MAYBE_Start)) {
  2606. # And the odd-ball NACL_BROWSER_TEST_f format:
  2607. # NACL_BROWSER_TEST_F(NaClBrowserTest, SimpleLoad, {
  2608. # The optional E2E_ENABLED-style is handled with (\w*\()?
  2609. # The NACL_BROWSER_TEST_F pattern is handled by allowing a trailing comma or
  2610. # trailing ')'.
  2611. test_maybe_pattern = (
  2612. r'^\s*\w*TEST[^(]*\(\s*\w+,\s*(\w*\()?MAYBE_{test_name}[\),]')
  2613. suite_maybe_pattern = r'^\s*\w*TEST[^(]*\(\s*MAYBE_{test_name}[\),]'
  2614. warnings = []
  2615. # Read the entire files. We can't just read the affected lines, forgetting to
  2616. # add MAYBE_ on a change would not show up otherwise.
  2617. for f in input_api.AffectedFiles(include_deletes=False):
  2618. if not 'test' in f.LocalPath() or not f.LocalPath().endswith('.cc'):
  2619. continue
  2620. contents = input_api.ReadFile(f)
  2621. lines = contents.splitlines(True)
  2622. current_position = 0
  2623. warning_test_names = set()
  2624. for line_num, line in enumerate(lines, start=1):
  2625. current_position += len(line)
  2626. maybe_match = define_maybe_pattern.search(line)
  2627. if maybe_match:
  2628. test_name = maybe_match.group('test_name')
  2629. # Do not warn twice for the same test.
  2630. if (test_name in warning_test_names):
  2631. continue
  2632. warning_test_names.add(test_name)
  2633. # Attempt to find the corresponding MAYBE_ test or suite, starting from
  2634. # the current position.
  2635. test_match = input_api.re.compile(
  2636. test_maybe_pattern.format(test_name=test_name),
  2637. input_api.re.MULTILINE).search(contents, current_position)
  2638. suite_match = input_api.re.compile(
  2639. suite_maybe_pattern.format(test_name=test_name),
  2640. input_api.re.MULTILINE).search(contents, current_position)
  2641. if not test_match and not suite_match:
  2642. warnings.append(
  2643. output_api.PresubmitPromptWarning(
  2644. '%s:%d found MAYBE_ defined without corresponding test %s'
  2645. % (f.LocalPath(), line_num, test_name)))
  2646. return warnings
  2647. def CheckDCHECK_IS_ONHasBraces(input_api, output_api):
  2648. """Checks to make sure DCHECK_IS_ON() does not skip the parentheses."""
  2649. errors = []
  2650. pattern = input_api.re.compile(r'\bDCHECK_IS_ON\b(?!\(\))',
  2651. input_api.re.MULTILINE)
  2652. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  2653. if (not f.LocalPath().endswith(('.cc', '.mm', '.h'))):
  2654. continue
  2655. for lnum, line in f.ChangedContents():
  2656. if input_api.re.search(pattern, line):
  2657. errors.append(
  2658. output_api.PresubmitError((
  2659. '%s:%d: Use of DCHECK_IS_ON() must be written as "#if '
  2660. + 'DCHECK_IS_ON()", not forgetting the parentheses.') %
  2661. (f.LocalPath(), lnum)))
  2662. return errors
  2663. # TODO(crbug/1138055): Reimplement CheckUmaHistogramChangesOnUpload check in a
  2664. # more reliable way. See
  2665. # https://chromium-review.googlesource.com/c/chromium/src/+/2500269
  2666. def CheckFlakyTestUsage(input_api, output_api):
  2667. """Check that FlakyTest annotation is our own instead of the android one"""
  2668. pattern = input_api.re.compile(r'import android.test.FlakyTest;')
  2669. files = []
  2670. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  2671. if f.LocalPath().endswith('Test.java'):
  2672. if pattern.search(input_api.ReadFile(f)):
  2673. files.append(f)
  2674. if len(files):
  2675. return [
  2676. output_api.PresubmitError(
  2677. 'Use org.chromium.base.test.util.FlakyTest instead of '
  2678. 'android.test.FlakyTest', files)
  2679. ]
  2680. return []
  2681. def CheckNoDEPSGIT(input_api, output_api):
  2682. """Make sure .DEPS.git is never modified manually."""
  2683. if any(f.LocalPath().endswith('.DEPS.git')
  2684. for f in input_api.AffectedFiles()):
  2685. return [
  2686. output_api.PresubmitError(
  2687. 'Never commit changes to .DEPS.git. This file is maintained by an\n'
  2688. 'automated system based on what\'s in DEPS and your changes will be\n'
  2689. 'overwritten.\n'
  2690. 'See https://sites.google.com/a/chromium.org/dev/developers/how-tos/'
  2691. 'get-the-code#Rolling_DEPS\n'
  2692. 'for more information')
  2693. ]
  2694. return []
  2695. def CheckCrosApiNeedBrowserTest(input_api, output_api):
  2696. """Check new crosapi should add browser test."""
  2697. has_new_crosapi = False
  2698. has_browser_test = False
  2699. for f in input_api.AffectedFiles():
  2700. path = f.LocalPath()
  2701. if (path.startswith('chromeos/crosapi/mojom') and
  2702. _IsMojomFile(input_api, path) and f.Action() == 'A'):
  2703. has_new_crosapi = True
  2704. if path.endswith('browsertest.cc') or path.endswith('browser_test.cc'):
  2705. has_browser_test = True
  2706. if has_new_crosapi and not has_browser_test:
  2707. return [
  2708. output_api.PresubmitPromptWarning(
  2709. 'You are adding a new crosapi, but there is no file ends with '
  2710. 'browsertest.cc file being added or modified. It is important '
  2711. 'to add crosapi browser test coverage to avoid version '
  2712. ' skew issues.\n'
  2713. 'Check //docs/lacros/test_instructions.md for more information.'
  2714. )
  2715. ]
  2716. return []
  2717. def CheckValidHostsInDEPSOnUpload(input_api, output_api):
  2718. """Checks that DEPS file deps are from allowed_hosts."""
  2719. # Run only if DEPS file has been modified to annoy fewer bystanders.
  2720. if all(f.LocalPath() != 'DEPS' for f in input_api.AffectedFiles()):
  2721. return []
  2722. # Outsource work to gclient verify
  2723. try:
  2724. gclient_path = input_api.os_path.join(input_api.PresubmitLocalPath(),
  2725. 'third_party', 'depot_tools',
  2726. 'gclient.py')
  2727. input_api.subprocess.check_output(
  2728. [input_api.python3_executable, gclient_path, 'verify'],
  2729. stderr=input_api.subprocess.STDOUT)
  2730. return []
  2731. except input_api.subprocess.CalledProcessError as error:
  2732. return [
  2733. output_api.PresubmitError(
  2734. 'DEPS file must have only git dependencies.',
  2735. long_text=error.output)
  2736. ]
  2737. def _GetMessageForMatchingType(input_api, affected_file, line_number, line,
  2738. ban_rule):
  2739. """Helper method for checking for banned constructs.
  2740. Returns an string composed of the name of the file, the line number where the
  2741. match has been found and the additional text passed as |message| in case the
  2742. target type name matches the text inside the line passed as parameter.
  2743. """
  2744. result = []
  2745. # Ignore comments about banned types.
  2746. if input_api.re.search(r"^ *//", line):
  2747. return result
  2748. # A // nocheck comment will bypass this error.
  2749. if line.endswith(" nocheck"):
  2750. return result
  2751. matched = False
  2752. if ban_rule.pattern[0:1] == '/':
  2753. regex = ban_rule.pattern[1:]
  2754. if input_api.re.search(regex, line):
  2755. matched = True
  2756. elif ban_rule.pattern in line:
  2757. matched = True
  2758. if matched:
  2759. result.append(' %s:%d:' % (affected_file.LocalPath(), line_number))
  2760. for line in ban_rule.explanation:
  2761. result.append(' %s' % line)
  2762. return result
  2763. def CheckNoBannedFunctions(input_api, output_api):
  2764. """Make sure that banned functions are not used."""
  2765. warnings = []
  2766. errors = []
  2767. def IsExcludedFile(affected_file, excluded_paths):
  2768. if not excluded_paths:
  2769. return False
  2770. local_path = affected_file.LocalPath()
  2771. # Consistently use / as path separator to simplify the writing of regex
  2772. # expressions.
  2773. local_path = local_path.replace(input_api.os_path.sep, '/')
  2774. for item in excluded_paths:
  2775. if input_api.re.match(item, local_path):
  2776. return True
  2777. return False
  2778. def IsIosObjcFile(affected_file):
  2779. local_path = affected_file.LocalPath()
  2780. if input_api.os_path.splitext(local_path)[-1] not in ('.mm', '.m',
  2781. '.h'):
  2782. return False
  2783. basename = input_api.os_path.basename(local_path)
  2784. if 'ios' in basename.split('_'):
  2785. return True
  2786. for sep in (input_api.os_path.sep, input_api.os_path.altsep):
  2787. if sep and 'ios' in local_path.split(sep):
  2788. return True
  2789. return False
  2790. def CheckForMatch(affected_file, line_num: int, line: str,
  2791. ban_rule: BanRule):
  2792. if IsExcludedFile(affected_file, ban_rule.excluded_paths):
  2793. return
  2794. problems = _GetMessageForMatchingType(input_api, f, line_num, line,
  2795. ban_rule)
  2796. if problems:
  2797. if ban_rule.treat_as_error is not None and ban_rule.treat_as_error:
  2798. errors.extend(problems)
  2799. else:
  2800. warnings.extend(problems)
  2801. file_filter = lambda f: f.LocalPath().endswith(('.java'))
  2802. for f in input_api.AffectedFiles(file_filter=file_filter):
  2803. for line_num, line in f.ChangedContents():
  2804. for ban_rule in _BANNED_JAVA_FUNCTIONS:
  2805. CheckForMatch(f, line_num, line, ban_rule)
  2806. file_filter = lambda f: f.LocalPath().endswith(('.js', '.ts'))
  2807. for f in input_api.AffectedFiles(file_filter=file_filter):
  2808. for line_num, line in f.ChangedContents():
  2809. for ban_rule in _BANNED_JAVASCRIPT_FUNCTIONS:
  2810. CheckForMatch(f, line_num, line, ban_rule)
  2811. file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
  2812. for f in input_api.AffectedFiles(file_filter=file_filter):
  2813. for line_num, line in f.ChangedContents():
  2814. for ban_rule in _BANNED_OBJC_FUNCTIONS:
  2815. CheckForMatch(f, line_num, line, ban_rule)
  2816. for f in input_api.AffectedFiles(file_filter=IsIosObjcFile):
  2817. for line_num, line in f.ChangedContents():
  2818. for ban_rule in _BANNED_IOS_OBJC_FUNCTIONS:
  2819. CheckForMatch(f, line_num, line, ban_rule)
  2820. egtest_filter = lambda f: f.LocalPath().endswith(('_egtest.mm'))
  2821. for f in input_api.AffectedFiles(file_filter=egtest_filter):
  2822. for line_num, line in f.ChangedContents():
  2823. for ban_rule in _BANNED_IOS_EGTEST_FUNCTIONS:
  2824. CheckForMatch(f, line_num, line, ban_rule)
  2825. file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
  2826. for f in input_api.AffectedFiles(file_filter=file_filter):
  2827. for line_num, line in f.ChangedContents():
  2828. for ban_rule in _BANNED_CPP_FUNCTIONS:
  2829. CheckForMatch(f, line_num, line, ban_rule)
  2830. # As of 05/2024, iOS fully migrated ConsentLevel::kSync to kSignin, and
  2831. # Android is in the process of preventing new users from entering kSync.
  2832. # So the warning is restricted to those platforms.
  2833. ios_pattern = input_api.re.compile('(^|[\W_])ios[\W_]')
  2834. file_filter = lambda f: (f.LocalPath().endswith(('.cc', '.mm', '.h')) and
  2835. ('android' in f.LocalPath() or
  2836. # Simply checking for an 'ios' substring would
  2837. # catch unrelated cases, use a regex.
  2838. ios_pattern.search(f.LocalPath())))
  2839. for f in input_api.AffectedFiles(file_filter=file_filter):
  2840. for line_num, line in f.ChangedContents():
  2841. for ban_rule in _DEPRECATED_SYNC_CONSENT_CPP_FUNCTIONS:
  2842. CheckForMatch(f, line_num, line, ban_rule)
  2843. file_filter = lambda f: f.LocalPath().endswith(('.java'))
  2844. for f in input_api.AffectedFiles(file_filter=file_filter):
  2845. for line_num, line in f.ChangedContents():
  2846. for ban_rule in _DEPRECATED_SYNC_CONSENT_JAVA_FUNCTIONS:
  2847. CheckForMatch(f, line_num, line, ban_rule)
  2848. file_filter = lambda f: f.LocalPath().endswith(('.mojom'))
  2849. for f in input_api.AffectedFiles(file_filter=file_filter):
  2850. for line_num, line in f.ChangedContents():
  2851. for ban_rule in _BANNED_MOJOM_PATTERNS:
  2852. CheckForMatch(f, line_num, line, ban_rule)
  2853. result = []
  2854. if (warnings):
  2855. result.append(
  2856. output_api.PresubmitPromptWarning('Banned functions were used.\n' +
  2857. '\n'.join(warnings)))
  2858. if (errors):
  2859. result.append(
  2860. output_api.PresubmitError('Banned functions were used.\n' +
  2861. '\n'.join(errors)))
  2862. return result
  2863. def _CheckAndroidNoBannedImports(input_api, output_api):
  2864. """Make sure that banned java imports are not used."""
  2865. errors = []
  2866. file_filter = lambda f: f.LocalPath().endswith(('.java'))
  2867. for f in input_api.AffectedFiles(file_filter=file_filter):
  2868. for line_num, line in f.ChangedContents():
  2869. for ban_rule in _BANNED_JAVA_IMPORTS:
  2870. # Consider merging this into the above function. There is no
  2871. # real difference anymore other than helping with a little
  2872. # bit of boilerplate text. Doing so means things like
  2873. # `treat_as_error` will also be uniformly handled.
  2874. problems = _GetMessageForMatchingType(input_api, f, line_num,
  2875. line, ban_rule)
  2876. if problems:
  2877. errors.extend(problems)
  2878. result = []
  2879. if (errors):
  2880. result.append(
  2881. output_api.PresubmitError('Banned imports were used.\n' +
  2882. '\n'.join(errors)))
  2883. return result
  2884. def CheckNoPragmaOnce(input_api, output_api):
  2885. """Make sure that banned functions are not used."""
  2886. files = []
  2887. pattern = input_api.re.compile(r'^#pragma\s+once', input_api.re.MULTILINE)
  2888. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  2889. if not f.LocalPath().endswith('.h'):
  2890. continue
  2891. if f.LocalPath().endswith('com_imported_mstscax.h'):
  2892. continue
  2893. contents = input_api.ReadFile(f)
  2894. if pattern.search(contents):
  2895. files.append(f)
  2896. if files:
  2897. return [
  2898. output_api.PresubmitError(
  2899. 'Do not use #pragma once in header files.\n'
  2900. 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
  2901. files)
  2902. ]
  2903. return []
  2904. def CheckNoTrinaryTrueFalse(input_api, output_api):
  2905. """Checks to make sure we don't introduce use of foo ? true : false."""
  2906. problems = []
  2907. pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
  2908. for f in input_api.AffectedFiles():
  2909. if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
  2910. continue
  2911. for line_num, line in f.ChangedContents():
  2912. if pattern.match(line):
  2913. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  2914. if not problems:
  2915. return []
  2916. return [
  2917. output_api.PresubmitPromptWarning(
  2918. 'Please consider avoiding the "? true : false" pattern if possible.\n'
  2919. + '\n'.join(problems))
  2920. ]
  2921. def CheckUnwantedDependencies(input_api, output_api):
  2922. """Runs checkdeps on #include and import statements added in this
  2923. change. Breaking - rules is an error, breaking ! rules is a
  2924. warning.
  2925. """
  2926. # Return early if no relevant file types were modified.
  2927. for f in input_api.AffectedFiles():
  2928. path = f.LocalPath()
  2929. if (_IsCPlusPlusFile(input_api, path) or _IsProtoFile(input_api, path)
  2930. or _IsJavaFile(input_api, path)):
  2931. break
  2932. else:
  2933. return []
  2934. import sys
  2935. # We need to wait until we have an input_api object and use this
  2936. # roundabout construct to import checkdeps because this file is
  2937. # eval-ed and thus doesn't have __file__.
  2938. original_sys_path = sys.path
  2939. try:
  2940. sys.path = sys.path + [
  2941. input_api.os_path.join(input_api.PresubmitLocalPath(),
  2942. 'buildtools', 'checkdeps')
  2943. ]
  2944. import checkdeps
  2945. from rules import Rule
  2946. finally:
  2947. # Restore sys.path to what it was before.
  2948. sys.path = original_sys_path
  2949. added_includes = []
  2950. added_imports = []
  2951. added_java_imports = []
  2952. for f in input_api.AffectedFiles():
  2953. if _IsCPlusPlusFile(input_api, f.LocalPath()):
  2954. changed_lines = [line for _, line in f.ChangedContents()]
  2955. added_includes.append([f.AbsoluteLocalPath(), changed_lines])
  2956. elif _IsProtoFile(input_api, f.LocalPath()):
  2957. changed_lines = [line for _, line in f.ChangedContents()]
  2958. added_imports.append([f.AbsoluteLocalPath(), changed_lines])
  2959. elif _IsJavaFile(input_api, f.LocalPath()):
  2960. changed_lines = [line for _, line in f.ChangedContents()]
  2961. added_java_imports.append([f.AbsoluteLocalPath(), changed_lines])
  2962. deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
  2963. error_descriptions = []
  2964. warning_descriptions = []
  2965. error_subjects = set()
  2966. warning_subjects = set()
  2967. for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
  2968. added_includes):
  2969. path = input_api.os_path.relpath(path, input_api.PresubmitLocalPath())
  2970. description_with_path = '%s\n %s' % (path, rule_description)
  2971. if rule_type == Rule.DISALLOW:
  2972. error_descriptions.append(description_with_path)
  2973. error_subjects.add("#includes")
  2974. else:
  2975. warning_descriptions.append(description_with_path)
  2976. warning_subjects.add("#includes")
  2977. for path, rule_type, rule_description in deps_checker.CheckAddedProtoImports(
  2978. added_imports):
  2979. path = input_api.os_path.relpath(path, input_api.PresubmitLocalPath())
  2980. description_with_path = '%s\n %s' % (path, rule_description)
  2981. if rule_type == Rule.DISALLOW:
  2982. error_descriptions.append(description_with_path)
  2983. error_subjects.add("imports")
  2984. else:
  2985. warning_descriptions.append(description_with_path)
  2986. warning_subjects.add("imports")
  2987. for path, rule_type, rule_description in deps_checker.CheckAddedJavaImports(
  2988. added_java_imports, _JAVA_MULTIPLE_DEFINITION_EXCLUDED_PATHS):
  2989. path = input_api.os_path.relpath(path, input_api.PresubmitLocalPath())
  2990. description_with_path = '%s\n %s' % (path, rule_description)
  2991. if rule_type == Rule.DISALLOW:
  2992. error_descriptions.append(description_with_path)
  2993. error_subjects.add("imports")
  2994. else:
  2995. warning_descriptions.append(description_with_path)
  2996. warning_subjects.add("imports")
  2997. results = []
  2998. if error_descriptions:
  2999. results.append(
  3000. output_api.PresubmitError(
  3001. 'You added one or more %s that violate checkdeps rules.' %
  3002. " and ".join(error_subjects), error_descriptions))
  3003. if warning_descriptions:
  3004. results.append(
  3005. output_api.PresubmitPromptOrNotify(
  3006. 'You added one or more %s of files that are temporarily\n'
  3007. 'allowed but being removed. Can you avoid introducing the\n'
  3008. '%s? See relevant DEPS file(s) for details and contacts.' %
  3009. (" and ".join(warning_subjects), "/".join(warning_subjects)),
  3010. warning_descriptions))
  3011. return results
  3012. def CheckFilePermissions(input_api, output_api):
  3013. """Check that all files have their permissions properly set."""
  3014. if input_api.platform == 'win32':
  3015. return []
  3016. checkperms_tool = input_api.os_path.join(input_api.PresubmitLocalPath(),
  3017. 'tools', 'checkperms',
  3018. 'checkperms.py')
  3019. args = [
  3020. input_api.python3_executable, checkperms_tool, '--root',
  3021. input_api.change.RepositoryRoot()
  3022. ]
  3023. with input_api.CreateTemporaryFile() as file_list:
  3024. for f in input_api.AffectedFiles():
  3025. # checkperms.py file/directory arguments must be relative to the
  3026. # repository.
  3027. file_list.write((f.LocalPath() + '\n').encode('utf8'))
  3028. file_list.close()
  3029. args += ['--file-list', file_list.name]
  3030. try:
  3031. input_api.subprocess.check_output(args)
  3032. return []
  3033. except input_api.subprocess.CalledProcessError as error:
  3034. return [
  3035. output_api.PresubmitError('checkperms.py failed:',
  3036. long_text=error.output.decode(
  3037. 'utf-8', 'ignore'))
  3038. ]
  3039. def CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
  3040. """Makes sure we don't include ui/aura/window_property.h
  3041. in header files.
  3042. """
  3043. pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
  3044. errors = []
  3045. for f in input_api.AffectedFiles():
  3046. if not f.LocalPath().endswith('.h'):
  3047. continue
  3048. for line_num, line in f.ChangedContents():
  3049. if pattern.match(line):
  3050. errors.append(' %s:%d' % (f.LocalPath(), line_num))
  3051. results = []
  3052. if errors:
  3053. results.append(
  3054. output_api.PresubmitError(
  3055. 'Header files should not include ui/aura/window_property.h',
  3056. errors))
  3057. return results
  3058. def CheckNoInternalHeapIncludes(input_api, output_api):
  3059. """Makes sure we don't include any headers from
  3060. third_party/blink/renderer/platform/heap/impl or
  3061. third_party/blink/renderer/platform/heap/v8_wrapper from files outside of
  3062. third_party/blink/renderer/platform/heap
  3063. """
  3064. impl_pattern = input_api.re.compile(
  3065. r'^\s*#include\s*"third_party/blink/renderer/platform/heap/impl/.*"')
  3066. v8_wrapper_pattern = input_api.re.compile(
  3067. r'^\s*#include\s*"third_party/blink/renderer/platform/heap/v8_wrapper/.*"'
  3068. )
  3069. # Consistently use / as path separator to simplify the writing of regex
  3070. # expressions.
  3071. file_filter = lambda f: not input_api.re.match(
  3072. r"^third_party/blink/renderer/platform/heap/.*",
  3073. f.LocalPath().replace(input_api.os_path.sep, '/'))
  3074. errors = []
  3075. for f in input_api.AffectedFiles(file_filter=file_filter):
  3076. for line_num, line in f.ChangedContents():
  3077. if impl_pattern.match(line) or v8_wrapper_pattern.match(line):
  3078. errors.append(' %s:%d' % (f.LocalPath(), line_num))
  3079. results = []
  3080. if errors:
  3081. results.append(
  3082. output_api.PresubmitError(
  3083. 'Do not include files from third_party/blink/renderer/platform/heap/impl'
  3084. ' or third_party/blink/renderer/platform/heap/v8_wrapper. Use the '
  3085. 'relevant counterparts from third_party/blink/renderer/platform/heap',
  3086. errors))
  3087. return results
  3088. def _CheckForVersionControlConflictsInFile(input_api, f):
  3089. pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
  3090. errors = []
  3091. for line_num, line in f.ChangedContents():
  3092. if f.LocalPath().endswith(('.md', '.rst', '.txt')):
  3093. # First-level headers in markdown look a lot like version control
  3094. # conflict markers. http://daringfireball.net/projects/markdown/basics
  3095. continue
  3096. if pattern.match(line):
  3097. errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
  3098. return errors
  3099. def CheckForVersionControlConflicts(input_api, output_api):
  3100. """Usually this is not intentional and will cause a compile failure."""
  3101. errors = []
  3102. for f in input_api.AffectedFiles():
  3103. errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
  3104. results = []
  3105. if errors:
  3106. results.append(
  3107. output_api.PresubmitError(
  3108. 'Version control conflict markers found, please resolve.',
  3109. errors))
  3110. return results
  3111. def CheckGoogleSupportAnswerUrlOnUpload(input_api, output_api):
  3112. pattern = input_api.re.compile('support\.google\.com\/chrome.*/answer')
  3113. errors = []
  3114. for f in input_api.AffectedFiles():
  3115. for line_num, line in f.ChangedContents():
  3116. if pattern.search(line):
  3117. errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
  3118. results = []
  3119. if errors:
  3120. results.append(
  3121. output_api.PresubmitPromptWarning(
  3122. 'Found Google support URL addressed by answer number. Please replace '
  3123. 'with a p= identifier instead. See crbug.com/679462\n',
  3124. errors))
  3125. return results
  3126. def CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
  3127. def FilterFile(affected_file):
  3128. """Filter function for use with input_api.AffectedSourceFiles,
  3129. below. This filters out everything except non-test files from
  3130. top-level directories that generally speaking should not hard-code
  3131. service URLs (e.g. src/android_webview/, src/content/ and others).
  3132. """
  3133. return input_api.FilterSourceFile(
  3134. affected_file,
  3135. files_to_check=[r'^(android_webview|base|content|net)/.*'],
  3136. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  3137. input_api.DEFAULT_FILES_TO_SKIP))
  3138. base_pattern = ('"[^"]*(google|googleapis|googlezip|googledrive|appspot)'
  3139. '\.(com|net)[^"]*"')
  3140. comment_pattern = input_api.re.compile('//.*%s' % base_pattern)
  3141. pattern = input_api.re.compile(base_pattern)
  3142. problems = [] # items are (filename, line_number, line)
  3143. for f in input_api.AffectedSourceFiles(FilterFile):
  3144. for line_num, line in f.ChangedContents():
  3145. if not comment_pattern.search(line) and pattern.search(line):
  3146. problems.append((f.LocalPath(), line_num, line))
  3147. if problems:
  3148. return [
  3149. output_api.PresubmitPromptOrNotify(
  3150. 'Most layers below src/chrome/ should not hardcode service URLs.\n'
  3151. 'Are you sure this is correct?', [
  3152. ' %s:%d: %s' % (problem[0], problem[1], problem[2])
  3153. for problem in problems
  3154. ])
  3155. ]
  3156. else:
  3157. return []
  3158. def CheckChromeOsSyncedPrefRegistration(input_api, output_api):
  3159. """Warns if Chrome OS C++ files register syncable prefs as browser prefs."""
  3160. def FileFilter(affected_file):
  3161. """Includes directories known to be Chrome OS only."""
  3162. return input_api.FilterSourceFile(
  3163. affected_file,
  3164. files_to_check=(
  3165. '^ash/',
  3166. '^chromeos/', # Top-level src/chromeos.
  3167. '.*/chromeos/', # Any path component.
  3168. '^components/arc',
  3169. '^components/exo'),
  3170. files_to_skip=(input_api.DEFAULT_FILES_TO_SKIP))
  3171. prefs = []
  3172. priority_prefs = []
  3173. for f in input_api.AffectedFiles(file_filter=FileFilter):
  3174. for line_num, line in f.ChangedContents():
  3175. if input_api.re.search('PrefRegistrySyncable::SYNCABLE_PREF',
  3176. line):
  3177. prefs.append(' %s:%d:' % (f.LocalPath(), line_num))
  3178. prefs.append(' %s' % line)
  3179. if input_api.re.search(
  3180. 'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF', line):
  3181. priority_prefs.append(' %s:%d' % (f.LocalPath(), line_num))
  3182. priority_prefs.append(' %s' % line)
  3183. results = []
  3184. if (prefs):
  3185. results.append(
  3186. output_api.PresubmitPromptWarning(
  3187. 'Preferences were registered as SYNCABLE_PREF and will be controlled '
  3188. 'by browser sync settings. If these prefs should be controlled by OS '
  3189. 'sync settings use SYNCABLE_OS_PREF instead.\n' +
  3190. '\n'.join(prefs)))
  3191. if (priority_prefs):
  3192. results.append(
  3193. output_api.PresubmitPromptWarning(
  3194. 'Preferences were registered as SYNCABLE_PRIORITY_PREF and will be '
  3195. 'controlled by browser sync settings. If these prefs should be '
  3196. 'controlled by OS sync settings use SYNCABLE_OS_PRIORITY_PREF '
  3197. 'instead.\n' + '\n'.join(prefs)))
  3198. return results
  3199. def CheckNoAbbreviationInPngFileName(input_api, output_api):
  3200. """Makes sure there are no abbreviations in the name of PNG files.
  3201. The native_client_sdk directory is excluded because it has auto-generated PNG
  3202. files for documentation.
  3203. """
  3204. errors = []
  3205. files_to_check = [r'.*\.png$']
  3206. files_to_skip = [r'^native_client_sdk/',
  3207. r'^services/test/',
  3208. r'^third_party/blink/web_tests/',
  3209. ]
  3210. file_filter = lambda f: input_api.FilterSourceFile(
  3211. f, files_to_check=files_to_check, files_to_skip=files_to_skip)
  3212. abbreviation = input_api.re.compile('.+_[a-z]\.png|.+_[a-z]_.*\.png')
  3213. for f in input_api.AffectedFiles(include_deletes=False,
  3214. file_filter=file_filter):
  3215. file_name = input_api.os_path.split(f.LocalPath())[1]
  3216. if abbreviation.search(file_name):
  3217. errors.append(' %s' % f.LocalPath())
  3218. results = []
  3219. if errors:
  3220. results.append(
  3221. output_api.PresubmitError(
  3222. 'The name of PNG files should not have abbreviations. \n'
  3223. 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
  3224. 'Contact oshima@chromium.org if you have questions.', errors))
  3225. return results
  3226. def CheckNoProductIconsAddedToPublicRepo(input_api, output_api):
  3227. """Heuristically identifies product icons based on their file name and reminds
  3228. contributors not to add them to the Chromium repository.
  3229. """
  3230. errors = []
  3231. files_to_check = [r'.*google.*\.png$|.*google.*\.svg$|.*google.*\.icon$']
  3232. file_filter = lambda f: input_api.FilterSourceFile(
  3233. f, files_to_check=files_to_check)
  3234. for f in input_api.AffectedFiles(include_deletes=False,
  3235. file_filter=file_filter):
  3236. errors.append(' %s' % f.LocalPath())
  3237. results = []
  3238. if errors:
  3239. # Give warnings instead of errors on presubmit --all and presubmit
  3240. # --files.
  3241. message_type = (output_api.PresubmitNotifyResult if input_api.no_diffs
  3242. else output_api.PresubmitError)
  3243. results.append(
  3244. message_type(
  3245. 'Trademarked images should not be added to the public repo. '
  3246. 'See crbug.com/944754', errors))
  3247. return results
  3248. def _ExtractAddRulesFromParsedDeps(parsed_deps):
  3249. """Extract the rules that add dependencies from a parsed DEPS file.
  3250. Args:
  3251. parsed_deps: the locals dictionary from evaluating the DEPS file."""
  3252. add_rules = set()
  3253. add_rules.update([
  3254. rule[1:] for rule in parsed_deps.get('include_rules', [])
  3255. if rule.startswith('+') or rule.startswith('!')
  3256. ])
  3257. for _, rules in parsed_deps.get('specific_include_rules', {}).items():
  3258. add_rules.update([
  3259. rule[1:] for rule in rules
  3260. if rule.startswith('+') or rule.startswith('!')
  3261. ])
  3262. return add_rules
  3263. def _ParseDeps(contents):
  3264. """Simple helper for parsing DEPS files."""
  3265. # Stubs for handling special syntax in the root DEPS file.
  3266. class _VarImpl:
  3267. def __init__(self, local_scope):
  3268. self._local_scope = local_scope
  3269. def Lookup(self, var_name):
  3270. """Implements the Var syntax."""
  3271. try:
  3272. return self._local_scope['vars'][var_name]
  3273. except KeyError:
  3274. raise Exception('Var is not defined: %s' % var_name)
  3275. local_scope = {}
  3276. global_scope = {
  3277. 'Var': _VarImpl(local_scope).Lookup,
  3278. 'Str': str,
  3279. }
  3280. exec(contents, global_scope, local_scope)
  3281. return local_scope
  3282. def _FindAllDepsFilesForSubpath(input_api, subpath):
  3283. ret = []
  3284. while subpath:
  3285. cur = input_api.os_path.join(input_api.change.RepositoryRoot(), subpath, 'DEPS')
  3286. if input_api.os_path.isfile(cur):
  3287. ret.append(cur)
  3288. subpath = input_api.os_path.dirname(subpath)
  3289. return ret
  3290. def _FindAddedDepsThatRequireReview(input_api, depended_on_paths):
  3291. """Filters to those whose DEPS set new_usages_require_review=True"""
  3292. ret = set()
  3293. cache = {}
  3294. for target_path in depended_on_paths:
  3295. for subpath in _FindAllDepsFilesForSubpath(input_api, target_path):
  3296. config = cache.get(subpath)
  3297. if config is None:
  3298. config = _ParseDeps(input_api.ReadFile(subpath))
  3299. cache[subpath] = config
  3300. if config.get('new_usages_require_review'):
  3301. ret.add(target_path)
  3302. break
  3303. return ret
  3304. def _CalculateAddedDeps(os_path, old_contents, new_contents):
  3305. """Helper method for CheckAddedDepsHaveTargetApprovals. Returns
  3306. a set of DEPS entries that we should look up.
  3307. For a directory (rather than a specific filename) we fake a path to
  3308. a specific filename by adding /DEPS. This is chosen as a file that
  3309. will seldom or never be subject to per-file include_rules.
  3310. """
  3311. # We ignore deps entries on auto-generated directories.
  3312. AUTO_GENERATED_DIRS = ['grit', 'jni']
  3313. old_deps = _ExtractAddRulesFromParsedDeps(_ParseDeps(old_contents))
  3314. new_deps = _ExtractAddRulesFromParsedDeps(_ParseDeps(new_contents))
  3315. added_deps = new_deps.difference(old_deps)
  3316. results = set()
  3317. for added_dep in added_deps:
  3318. if added_dep.split('/')[0] in AUTO_GENERATED_DIRS:
  3319. continue
  3320. # Assume that a rule that ends in .h is a rule for a specific file.
  3321. if added_dep.endswith('.h'):
  3322. results.add(added_dep)
  3323. else:
  3324. results.add(os_path.join(added_dep, 'DEPS'))
  3325. return results
  3326. def CheckForNewDEPSDownloadFromGoogleStorageHooks(input_api, output_api):
  3327. """Checks that there are no new download_from_google_storage hooks"""
  3328. for f in input_api.AffectedFiles(include_deletes=False):
  3329. if f.LocalPath() == 'DEPS':
  3330. old_hooks = _ParseDeps('\n'.join(f.OldContents()))['hooks']
  3331. new_hooks = _ParseDeps('\n'.join(f.NewContents()))['hooks']
  3332. old_name_to_hook = {hook['name']: hook for hook in old_hooks}
  3333. new_name_to_hook = {hook['name']: hook for hook in new_hooks}
  3334. added_hook_names = set(new_name_to_hook.keys()) - set(
  3335. old_name_to_hook.keys())
  3336. if not added_hook_names:
  3337. return []
  3338. new_download_from_google_storage_hooks = []
  3339. for new_hook in added_hook_names:
  3340. hook = new_name_to_hook[new_hook]
  3341. action_cmd = hook['action']
  3342. if any('download_from_google_storage' in arg
  3343. for arg in action_cmd):
  3344. new_download_from_google_storage_hooks.append(new_hook)
  3345. if new_download_from_google_storage_hooks:
  3346. return [
  3347. output_api.PresubmitError(
  3348. 'Please do not add new download_from_google_storage '
  3349. 'hooks. Instead, add a `gcs` dep_type entry to `deps`. '
  3350. 'See https://chromium.googlesource.com/chromium/src.git'
  3351. '/+/refs/heads/main/docs/gcs_dependencies.md for more '
  3352. 'info. Added hooks:',
  3353. items=new_download_from_google_storage_hooks)
  3354. ]
  3355. return []
  3356. def CheckEachPerfettoTestDataFileHasDepsEntry(input_api, output_api):
  3357. test_data_filter = lambda f: input_api.FilterSourceFile(
  3358. f, files_to_check=[r'^base/tracing/test/data_sha256/.*\.sha256'])
  3359. if not any(input_api.AffectedFiles(file_filter=test_data_filter)):
  3360. return []
  3361. # Find DEPS entry
  3362. deps_entry = []
  3363. old_deps_entry = []
  3364. for f in input_api.AffectedFiles(include_deletes=False):
  3365. if f.LocalPath() == 'DEPS':
  3366. new_deps = _ParseDeps('\n'.join(f.NewContents()))['deps']
  3367. deps_entry = new_deps['src/base/tracing/test/data']
  3368. old_deps = _ParseDeps('\n'.join(f.OldContents()))['deps']
  3369. old_deps_entry = old_deps['src/base/tracing/test/data']
  3370. if not deps_entry:
  3371. # TODO(312895063):Add back error when .sha256 files have been moved.
  3372. return [output_api.PresubmitError(
  3373. 'You must update the DEPS file when you update a '
  3374. '.sha256 file in base/tracing/test/data_sha256'
  3375. )]
  3376. output = []
  3377. for f in input_api.AffectedFiles(file_filter=test_data_filter):
  3378. objects = deps_entry['objects']
  3379. if not f.NewContents():
  3380. # Deleted file so check that DEPS entry removed
  3381. sha256_from_file = f.OldContents()[0]
  3382. object_entry = next(
  3383. (item for item in objects if item["sha256sum"] == sha256_from_file),
  3384. None)
  3385. old_entry = next(
  3386. (item for item in old_deps_entry['objects'] if item["sha256sum"] == sha256_from_file),
  3387. None)
  3388. if object_entry:
  3389. # Allow renaming of objects with the same hash
  3390. if object_entry['object_name'] != old_entry['object_name']:
  3391. continue
  3392. output.append(output_api.PresubmitError(
  3393. 'You deleted %s so you must also remove the corresponding DEPS entry.'
  3394. % f.LocalPath()
  3395. ))
  3396. continue
  3397. sha256_from_file = f.NewContents()[0]
  3398. object_entry = next(
  3399. (item for item in objects if item["sha256sum"] == sha256_from_file),
  3400. None)
  3401. if not object_entry:
  3402. output.append(output_api.PresubmitError(
  3403. 'No corresponding DEPS entry found for %s. '
  3404. 'Run `base/tracing/test/test_data.py get_deps --filepath %s` '
  3405. 'to generate the DEPS entry.'
  3406. % (f.LocalPath(), f.LocalPath())
  3407. ))
  3408. if output:
  3409. output.append(output_api.PresubmitError(
  3410. 'The DEPS entry for `src/base/tracing/test/data` in the DEPS file has not been '
  3411. 'updated properly. Run `base/tracing/test/test_data.py get_all_deps` to see what '
  3412. 'the DEPS entry should look like.'
  3413. ))
  3414. return output
  3415. def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
  3416. """When a dependency prefixed with + is added to a DEPS file, we
  3417. want to make sure that the change is reviewed by an OWNER of the
  3418. target file or directory, to avoid layering violations from being
  3419. introduced. This check verifies that this happens.
  3420. """
  3421. # We rely on Gerrit's code-owners to check approvals.
  3422. # input_api.gerrit is always set for Chromium, but other projects
  3423. # might not use Gerrit.
  3424. if not input_api.gerrit or input_api.no_diffs:
  3425. return []
  3426. if 'PRESUBMIT_SKIP_NETWORK' in input_api.environ:
  3427. return []
  3428. try:
  3429. if (input_api.change.issue and
  3430. input_api.gerrit.IsOwnersOverrideApproved(
  3431. input_api.change.issue)):
  3432. # Skip OWNERS check when Owners-Override label is approved. This is
  3433. # intended for global owners, trusted bots, and on-call sheriffs.
  3434. # Review is still required for these changes.
  3435. return []
  3436. except Exception as e:
  3437. return [output_api.PresubmitPromptWarning(
  3438. 'Failed to retrieve owner override status - %s' % str(e))]
  3439. # A set of paths (that might not exist) that are being added as DEPS
  3440. # (via lines like "+foo/bar/baz").
  3441. depended_on_paths = set()
  3442. # Consistently use / as path separator to simplify the writing of regex
  3443. # expressions.
  3444. file_filter = lambda f: not input_api.re.match(
  3445. r"^third_party/blink/.*",
  3446. f.LocalPath().replace(input_api.os_path.sep, '/'))
  3447. for f in input_api.AffectedFiles(include_deletes=False,
  3448. file_filter=file_filter):
  3449. filename = input_api.os_path.basename(f.LocalPath())
  3450. if filename == 'DEPS':
  3451. depended_on_paths.update(
  3452. _CalculateAddedDeps(input_api.os_path,
  3453. '\n'.join(f.OldContents()),
  3454. '\n'.join(f.NewContents())))
  3455. # Requiring reviews is opt-in as of https://crbug.com/365797506
  3456. depended_on_paths = _FindAddedDepsThatRequireReview(input_api, depended_on_paths)
  3457. if not depended_on_paths:
  3458. return []
  3459. if input_api.is_committing:
  3460. if input_api.tbr:
  3461. return [
  3462. output_api.PresubmitNotifyResult(
  3463. '--tbr was specified, skipping OWNERS check for DEPS additions'
  3464. )
  3465. ]
  3466. # TODO(dcheng): Make this generate an error on dry runs if the reviewer
  3467. # is not added, to prevent review serialization.
  3468. if input_api.dry_run:
  3469. return [
  3470. output_api.PresubmitNotifyResult(
  3471. 'This is a dry run, skipping OWNERS check for DEPS additions'
  3472. )
  3473. ]
  3474. if not input_api.change.issue:
  3475. return [
  3476. output_api.PresubmitError(
  3477. "DEPS approval by OWNERS check failed: this change has "
  3478. "no change number, so we can't check it for approvals.")
  3479. ]
  3480. output = output_api.PresubmitError
  3481. else:
  3482. output = output_api.PresubmitNotifyResult
  3483. owner_email, reviewers = (
  3484. input_api.canned_checks.GetCodereviewOwnerAndReviewers(
  3485. input_api, None, approval_needed=input_api.is_committing))
  3486. owner_email = owner_email or input_api.change.author_email
  3487. approval_status = input_api.owners_client.GetFilesApprovalStatus(
  3488. depended_on_paths, reviewers.union([owner_email]), [])
  3489. missing_files = [
  3490. p for p in depended_on_paths
  3491. if approval_status[p] != input_api.owners_client.APPROVED
  3492. ]
  3493. # We strip the /DEPS part that was added by
  3494. # _FilesToCheckForIncomingDeps to fake a path to a file in a
  3495. # directory.
  3496. def StripDeps(path):
  3497. start_deps = path.rfind('/DEPS')
  3498. if start_deps != -1:
  3499. return path[:start_deps]
  3500. else:
  3501. return path
  3502. submodule_paths = set(input_api.ListSubmodules())
  3503. def is_from_submodules(path, submodule_paths):
  3504. path = input_api.os_path.normpath(path)
  3505. while path:
  3506. if path in submodule_paths:
  3507. return True
  3508. # All deps should be a relative path from the checkout.
  3509. # i.e., shouldn't start with "/" or "c:\", for example.
  3510. #
  3511. # That said, this is to prevent an infinite loop, just in case
  3512. # an input dep path starts with "/", because
  3513. # os.path.dirname("/") => "/"
  3514. parent = input_api.os_path.dirname(path)
  3515. if parent == path:
  3516. break
  3517. path = parent
  3518. return False
  3519. unapproved_dependencies = [
  3520. "'+%s'," % StripDeps(path) for path in missing_files
  3521. # if a newly added dep is from a submodule, it becomes trickier
  3522. # to get suggested owners, especially it is from a different host.
  3523. #
  3524. # skip the review enforcement for cross-repo deps.
  3525. if not is_from_submodules(path, submodule_paths)
  3526. ]
  3527. if unapproved_dependencies:
  3528. output_list = [
  3529. output(
  3530. 'You need LGTM from owners of depends-on paths in DEPS that were '
  3531. 'modified in this CL:\n %s' %
  3532. '\n '.join(sorted(unapproved_dependencies)))
  3533. ]
  3534. suggested_owners = input_api.owners_client.SuggestOwners(
  3535. missing_files, exclude=[owner_email])
  3536. output_list.append(
  3537. output('Suggested missing target path OWNERS:\n %s' %
  3538. '\n '.join(suggested_owners or [])))
  3539. return output_list
  3540. return []
  3541. # TODO: add unit tests.
  3542. def CheckSpamLogging(input_api, output_api):
  3543. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  3544. files_to_skip = (
  3545. _EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  3546. input_api.DEFAULT_FILES_TO_SKIP + (
  3547. r"^base/fuchsia/scoped_fx_logger\.cc$",
  3548. r"^base/logging\.h$",
  3549. r"^base/logging\.cc$",
  3550. r"^base/task/thread_pool/task_tracker\.cc$",
  3551. r"^chrome/app/chrome_main_delegate\.cc$",
  3552. r"^chrome/browser/ash/arc/enterprise/cert_store/arc_cert_installer\.cc$",
  3553. r"^chrome/browser/ash/policy/remote_commands/user_command_arc_job\.cc$",
  3554. r"^chrome/browser/chrome_browser_main\.cc$",
  3555. r"^chrome/browser/ui/startup/startup_browser_creator\.cc$",
  3556. r"^chrome/browser/browser_switcher/bho/.*",
  3557. r"^chrome/browser/diagnostics/diagnostics_writer\.cc$",
  3558. r"^chrome/chrome_elf/dll_hash/dll_hash_main\.cc$",
  3559. r"^chrome/installer/setup/.*",
  3560. # crdmg runs as a separate binary which intentionally does
  3561. # not depend on base logging.
  3562. r"^chrome/utility/safe_browsing/mac/crdmg\.cc$",
  3563. r"^chromecast/",
  3564. r"^components/cast",
  3565. r"^components/media_control/renderer/media_playback_options\.cc$",
  3566. r"^components/policy/core/common/policy_logger\.cc$",
  3567. r"^components/viz/service/display/"
  3568. r"overlay_strategy_underlay_cast\.cc$",
  3569. r"^components/zucchini/.*",
  3570. # TODO(peter): Remove exception. https://crbug.com/534537
  3571. r"^content/browser/notifications/"
  3572. r"notification_event_dispatcher_impl\.cc$",
  3573. r"^content/common/gpu/client/gl_helper_benchmark\.cc$",
  3574. r"^courgette/courgette_minimal_tool\.cc$",
  3575. r"^courgette/courgette_tool\.cc$",
  3576. r"^extensions/renderer/logging_native_handler\.cc$",
  3577. r"^fuchsia_web/common/init_logging\.cc$",
  3578. r"^fuchsia_web/runners/common/web_component\.cc$",
  3579. r"^fuchsia_web/shell/.*\.cc$",
  3580. r"^headless/app/headless_shell\.cc$",
  3581. r"^ipc/ipc_logging\.cc$",
  3582. r"^native_client_sdk/",
  3583. r"^remoting/base/logging\.h$",
  3584. r"^remoting/host/.*",
  3585. r"^sandbox/linux/.*",
  3586. r"^services/webnn/tflite/graph_impl_tflite\.cc$",
  3587. r"^services/webnn/coreml/graph_impl_coreml\.mm$",
  3588. r"^storage/browser/file_system/dump_file_system\.cc$",
  3589. r"^testing/perf/",
  3590. r"^tools/",
  3591. r"^ui/base/resource/data_pack\.cc$",
  3592. r"^ui/aura/bench/bench_main\.cc$",
  3593. r"^ui/ozone/platform/cast/",
  3594. r"^ui/base/x/xwmstartupcheck/"
  3595. r"xwmstartupcheck\.cc$"))
  3596. source_file_filter = lambda x: input_api.FilterSourceFile(
  3597. x, files_to_check=file_inclusion_pattern, files_to_skip=files_to_skip)
  3598. log_info = set([])
  3599. printf = set([])
  3600. for f in input_api.AffectedSourceFiles(source_file_filter):
  3601. for _, line in f.ChangedContents():
  3602. if input_api.re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", line):
  3603. log_info.add(f.LocalPath())
  3604. elif input_api.re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", line):
  3605. log_info.add(f.LocalPath())
  3606. if input_api.re.search(r"\bprintf\(", line):
  3607. printf.add(f.LocalPath())
  3608. elif input_api.re.search(r"\bfprintf\((stdout|stderr)", line):
  3609. printf.add(f.LocalPath())
  3610. if log_info:
  3611. return [
  3612. output_api.PresubmitError(
  3613. 'These files spam the console log with LOG(INFO):',
  3614. items=log_info)
  3615. ]
  3616. if printf:
  3617. return [
  3618. output_api.PresubmitError(
  3619. 'These files spam the console log with printf/fprintf:',
  3620. items=printf)
  3621. ]
  3622. return []
  3623. def CheckForAnonymousVariables(input_api, output_api):
  3624. """These types are all expected to hold locks while in scope and
  3625. so should never be anonymous (which causes them to be immediately
  3626. destroyed)."""
  3627. they_who_must_be_named = [
  3628. 'base::AutoLock',
  3629. 'base::AutoReset',
  3630. 'base::AutoUnlock',
  3631. 'SkAutoAlphaRestore',
  3632. 'SkAutoBitmapShaderInstall',
  3633. 'SkAutoBlitterChoose',
  3634. 'SkAutoBounderCommit',
  3635. 'SkAutoCallProc',
  3636. 'SkAutoCanvasRestore',
  3637. 'SkAutoCommentBlock',
  3638. 'SkAutoDescriptor',
  3639. 'SkAutoDisableDirectionCheck',
  3640. 'SkAutoDisableOvalCheck',
  3641. 'SkAutoFree',
  3642. 'SkAutoGlyphCache',
  3643. 'SkAutoHDC',
  3644. 'SkAutoLockColors',
  3645. 'SkAutoLockPixels',
  3646. 'SkAutoMalloc',
  3647. 'SkAutoMaskFreeImage',
  3648. 'SkAutoMutexAcquire',
  3649. 'SkAutoPathBoundsUpdate',
  3650. 'SkAutoPDFRelease',
  3651. 'SkAutoRasterClipValidate',
  3652. 'SkAutoRef',
  3653. 'SkAutoTime',
  3654. 'SkAutoTrace',
  3655. 'SkAutoUnref',
  3656. ]
  3657. anonymous = r'(%s)\s*[({]' % '|'.join(they_who_must_be_named)
  3658. # bad: base::AutoLock(lock.get());
  3659. # not bad: base::AutoLock lock(lock.get());
  3660. bad_pattern = input_api.re.compile(anonymous)
  3661. # good: new base::AutoLock(lock.get())
  3662. good_pattern = input_api.re.compile(r'\bnew\s*' + anonymous)
  3663. errors = []
  3664. for f in input_api.AffectedFiles():
  3665. if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
  3666. continue
  3667. for linenum, line in f.ChangedContents():
  3668. if bad_pattern.search(line) and not good_pattern.search(line):
  3669. errors.append('%s:%d' % (f.LocalPath(), linenum))
  3670. if errors:
  3671. return [
  3672. output_api.PresubmitError(
  3673. 'These lines create anonymous variables that need to be named:',
  3674. items=errors)
  3675. ]
  3676. return []
  3677. def CheckUniquePtrOnUpload(input_api, output_api):
  3678. # Returns whether |template_str| is of the form <T, U...> for some types T
  3679. # and U, or is invalid due to mismatched angle bracket pairs. Assumes that
  3680. # |template_str| is already in the form <...>.
  3681. def HasMoreThanOneArgOrInvalid(template_str):
  3682. # Level of <...> nesting.
  3683. nesting = 0
  3684. for c in template_str:
  3685. if c == '<':
  3686. nesting += 1
  3687. elif c == '>':
  3688. nesting -= 1
  3689. elif c == ',' and nesting == 1:
  3690. return True
  3691. if nesting != 0:
  3692. # Invalid.
  3693. return True
  3694. return False
  3695. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  3696. sources = lambda affected_file: input_api.FilterSourceFile(
  3697. affected_file,
  3698. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  3699. DEFAULT_FILES_TO_SKIP),
  3700. files_to_check=file_inclusion_pattern)
  3701. # Pattern to capture a single "<...>" block of template arguments. It can
  3702. # handle linearly nested blocks, such as "<std::vector<std::set<T>>>", but
  3703. # cannot handle branching structures, such as "<pair<set<T>,set<U>>". The
  3704. # latter would likely require counting that < and > match, which is not
  3705. # expressible in regular languages. Should the need arise, one can introduce
  3706. # limited counting (matching up to a total number of nesting depth), which
  3707. # should cover all practical cases for already a low nesting limit.
  3708. template_arg_pattern = (
  3709. r'<[^>]*' # Opening block of <.
  3710. r'>([^<]*>)?') # Closing block of >.
  3711. # Prefix expressing that whatever follows is not already inside a <...>
  3712. # block.
  3713. not_inside_template_arg_pattern = r'(^|[^<,\s]\s*)'
  3714. null_construct_pattern = input_api.re.compile(
  3715. not_inside_template_arg_pattern + r'\bstd::unique_ptr' +
  3716. template_arg_pattern + r'\(\)')
  3717. # Same as template_arg_pattern, but excluding type arrays, e.g., <T[]>.
  3718. template_arg_no_array_pattern = (
  3719. r'<[^>]*[^]]' # Opening block of <.
  3720. r'>([^(<]*[^]]>)?') # Closing block of >.
  3721. # Prefix saying that what follows is the start of an expression.
  3722. start_of_expr_pattern = r'(=|\breturn|^)\s*'
  3723. # Suffix saying that what follows are call parentheses with a non-empty list
  3724. # of arguments.
  3725. nonempty_arg_list_pattern = r'\(([^)]|$)'
  3726. # Put the template argument into a capture group for deeper examination later.
  3727. return_construct_pattern = input_api.re.compile(
  3728. start_of_expr_pattern + r'std::unique_ptr' + '(?P<template_arg>' +
  3729. template_arg_no_array_pattern + ')' + nonempty_arg_list_pattern)
  3730. problems_constructor = []
  3731. problems_nullptr = []
  3732. for f in input_api.AffectedSourceFiles(sources):
  3733. for line_number, line in f.ChangedContents():
  3734. # Disallow:
  3735. # return std::unique_ptr<T>(foo);
  3736. # bar = std::unique_ptr<T>(foo);
  3737. # But allow:
  3738. # return std::unique_ptr<T[]>(foo);
  3739. # bar = std::unique_ptr<T[]>(foo);
  3740. # And also allow cases when the second template argument is present. Those
  3741. # cases cannot be handled by std::make_unique:
  3742. # return std::unique_ptr<T, U>(foo);
  3743. # bar = std::unique_ptr<T, U>(foo);
  3744. local_path = f.LocalPath()
  3745. return_construct_result = return_construct_pattern.search(line)
  3746. if return_construct_result and not HasMoreThanOneArgOrInvalid(
  3747. return_construct_result.group('template_arg')):
  3748. problems_constructor.append(
  3749. '%s:%d\n %s' % (local_path, line_number, line.strip()))
  3750. # Disallow:
  3751. # std::unique_ptr<T>()
  3752. if null_construct_pattern.search(line):
  3753. problems_nullptr.append(
  3754. '%s:%d\n %s' % (local_path, line_number, line.strip()))
  3755. errors = []
  3756. if problems_nullptr:
  3757. errors.append(
  3758. output_api.PresubmitPromptWarning(
  3759. 'The following files use std::unique_ptr<T>(). Use nullptr instead.',
  3760. problems_nullptr))
  3761. if problems_constructor:
  3762. errors.append(
  3763. output_api.PresubmitError(
  3764. 'The following files use explicit std::unique_ptr constructor. '
  3765. 'Use std::make_unique<T>() instead, or use base::WrapUnique if '
  3766. 'std::make_unique is not an option.', problems_constructor))
  3767. return errors
  3768. def CheckUserActionUpdate(input_api, output_api):
  3769. """Checks if any new user action has been added."""
  3770. if any('actions.xml' == input_api.os_path.basename(f)
  3771. for f in input_api.LocalPaths()):
  3772. # If actions.xml is already included in the changelist, the PRESUBMIT
  3773. # for actions.xml will do a more complete presubmit check.
  3774. return []
  3775. file_inclusion_pattern = [r'.*\.(cc|mm)$']
  3776. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  3777. input_api.DEFAULT_FILES_TO_SKIP)
  3778. file_filter = lambda f: input_api.FilterSourceFile(
  3779. f, files_to_check=file_inclusion_pattern, files_to_skip=files_to_skip)
  3780. action_re = r'[^a-zA-Z]UserMetricsAction\("([^"]*)'
  3781. current_actions = None
  3782. for f in input_api.AffectedFiles(file_filter=file_filter):
  3783. for line_num, line in f.ChangedContents():
  3784. match = input_api.re.search(action_re, line)
  3785. if match:
  3786. # Loads contents in tools/metrics/actions/actions.xml to memory. It's
  3787. # loaded only once.
  3788. if not current_actions:
  3789. with open('tools/metrics/actions/actions.xml',
  3790. encoding='utf-8') as actions_f:
  3791. current_actions = actions_f.read()
  3792. # Search for the matched user action name in |current_actions|.
  3793. for action_name in match.groups():
  3794. action = 'name="{0}"'.format(action_name)
  3795. if action not in current_actions:
  3796. return [
  3797. output_api.PresubmitPromptWarning(
  3798. 'File %s line %d: %s is missing in '
  3799. 'tools/metrics/actions/actions.xml. Please run '
  3800. 'tools/metrics/actions/extract_actions.py to update.'
  3801. % (f.LocalPath(), line_num, action_name))
  3802. ]
  3803. return []
  3804. def _ImportJSONCommentEater(input_api):
  3805. import sys
  3806. sys.path = sys.path + [
  3807. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  3808. 'json_comment_eater')
  3809. ]
  3810. import json_comment_eater
  3811. return json_comment_eater
  3812. def _GetJSONParseError(input_api, filename, eat_comments=True):
  3813. try:
  3814. contents = input_api.ReadFile(filename)
  3815. if eat_comments:
  3816. json_comment_eater = _ImportJSONCommentEater(input_api)
  3817. contents = json_comment_eater.Nom(contents)
  3818. input_api.json.loads(contents)
  3819. except ValueError as e:
  3820. return e
  3821. return None
  3822. def _GetIDLParseError(input_api, filename):
  3823. try:
  3824. contents = input_api.ReadFile(filename)
  3825. for i, char in enumerate(contents):
  3826. if not char.isascii():
  3827. return (
  3828. 'Non-ascii character "%s" (ord %d) found at offset %d.' %
  3829. (char, ord(char), i))
  3830. idl_schema = input_api.os_path.join(input_api.PresubmitLocalPath(),
  3831. 'tools', 'json_schema_compiler',
  3832. 'idl_schema.py')
  3833. process = input_api.subprocess.Popen(
  3834. [input_api.python3_executable, idl_schema],
  3835. stdin=input_api.subprocess.PIPE,
  3836. stdout=input_api.subprocess.PIPE,
  3837. stderr=input_api.subprocess.PIPE,
  3838. universal_newlines=True)
  3839. (_, error) = process.communicate(input=contents)
  3840. return error or None
  3841. except ValueError as e:
  3842. return e
  3843. def CheckParseErrors(input_api, output_api):
  3844. """Check that IDL and JSON files do not contain syntax errors."""
  3845. actions = {
  3846. '.idl': _GetIDLParseError,
  3847. '.json': _GetJSONParseError,
  3848. }
  3849. # Most JSON files are preprocessed and support comments, but these do not.
  3850. json_no_comments_patterns = [
  3851. r'^testing/',
  3852. ]
  3853. # Only run IDL checker on files in these directories.
  3854. idl_included_patterns = [
  3855. r'^chrome/common/extensions/api/',
  3856. r'^extensions/common/api/',
  3857. ]
  3858. def get_action(affected_file):
  3859. filename = affected_file.LocalPath()
  3860. return actions.get(input_api.os_path.splitext(filename)[1])
  3861. def FilterFile(affected_file):
  3862. action = get_action(affected_file)
  3863. if not action:
  3864. return False
  3865. path = affected_file.LocalPath()
  3866. if _MatchesFile(input_api,
  3867. _KNOWN_TEST_DATA_AND_INVALID_JSON_FILE_PATTERNS, path):
  3868. return False
  3869. if (action == _GetIDLParseError
  3870. and not _MatchesFile(input_api, idl_included_patterns, path)):
  3871. return False
  3872. return True
  3873. results = []
  3874. for affected_file in input_api.AffectedFiles(file_filter=FilterFile,
  3875. include_deletes=False):
  3876. action = get_action(affected_file)
  3877. kwargs = {}
  3878. if (action == _GetJSONParseError
  3879. and _MatchesFile(input_api, json_no_comments_patterns,
  3880. affected_file.LocalPath())):
  3881. kwargs['eat_comments'] = False
  3882. parse_error = action(input_api, affected_file.AbsoluteLocalPath(),
  3883. **kwargs)
  3884. if parse_error:
  3885. results.append(
  3886. output_api.PresubmitError(
  3887. '%s could not be parsed: %s' %
  3888. (affected_file.LocalPath(), parse_error)))
  3889. return results
  3890. def CheckJavaStyle(input_api, output_api):
  3891. """Runs checkstyle on changed java files and returns errors if any exist."""
  3892. # Return early if no java files were modified.
  3893. if not any(
  3894. _IsJavaFile(input_api, f.LocalPath())
  3895. for f in input_api.AffectedFiles()):
  3896. return []
  3897. import sys
  3898. original_sys_path = sys.path
  3899. try:
  3900. sys.path = sys.path + [
  3901. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  3902. 'android', 'checkstyle')
  3903. ]
  3904. import checkstyle
  3905. finally:
  3906. # Restore sys.path to what it was before.
  3907. sys.path = original_sys_path
  3908. return checkstyle.run_presubmit(
  3909. input_api,
  3910. output_api,
  3911. files_to_skip=_EXCLUDED_PATHS + input_api.DEFAULT_FILES_TO_SKIP)
  3912. def CheckPythonDevilInit(input_api, output_api):
  3913. """Checks to make sure devil is initialized correctly in python scripts."""
  3914. script_common_initialize_pattern = input_api.re.compile(
  3915. r'script_common\.InitializeEnvironment\(')
  3916. devil_env_config_initialize = input_api.re.compile(
  3917. r'devil_env\.config\.Initialize\(')
  3918. errors = []
  3919. sources = lambda affected_file: input_api.FilterSourceFile(
  3920. affected_file,
  3921. files_to_skip=(_EXCLUDED_PATHS + input_api.DEFAULT_FILES_TO_SKIP + (
  3922. r'^build/android/devil_chromium\.py',
  3923. r'^tools/bisect-builds\.py',
  3924. r'^third_party/.*',
  3925. )),
  3926. files_to_check=[r'.*\.py$'])
  3927. for f in input_api.AffectedSourceFiles(sources):
  3928. for line_num, line in f.ChangedContents():
  3929. if (script_common_initialize_pattern.search(line)
  3930. or devil_env_config_initialize.search(line)):
  3931. errors.append("%s:%d" % (f.LocalPath(), line_num))
  3932. results = []
  3933. if errors:
  3934. results.append(
  3935. output_api.PresubmitError(
  3936. 'Devil initialization should always be done using '
  3937. 'devil_chromium.Initialize() in the chromium project, to use better '
  3938. 'defaults for dependencies (ex. up-to-date version of adb).',
  3939. errors))
  3940. return results
  3941. def _MatchesFile(input_api, patterns, path):
  3942. # Consistently use / as path separator to simplify the writing of regex
  3943. # expressions.
  3944. path = path.replace(input_api.os_path.sep, '/')
  3945. for pattern in patterns:
  3946. if input_api.re.search(pattern, path):
  3947. return True
  3948. return False
  3949. def _ChangeHasSecurityReviewer(input_api, owners_file):
  3950. """Returns True iff the CL has a reviewer from SECURITY_OWNERS.
  3951. Args:
  3952. input_api: The presubmit input API.
  3953. owners_file: OWNERS file with required reviewers. Typically, this is
  3954. something like ipc/SECURITY_OWNERS.
  3955. Note: if the presubmit is running for commit rather than for upload, this
  3956. only returns True if a security reviewer has also approved the CL.
  3957. """
  3958. # Owners-Override should bypass all additional OWNERS enforcement checks.
  3959. # A CR+1 vote will still be required to land this change.
  3960. if (input_api.change.issue and input_api.gerrit.IsOwnersOverrideApproved(
  3961. input_api.change.issue)):
  3962. return True
  3963. owner_email, reviewers = (
  3964. input_api.canned_checks.GetCodereviewOwnerAndReviewers(
  3965. input_api,
  3966. None,
  3967. approval_needed=input_api.is_committing and not input_api.dry_run))
  3968. security_owners = input_api.owners_client.ListOwners(owners_file)
  3969. return any(owner in reviewers for owner in security_owners)
  3970. @dataclass
  3971. class _SecurityProblemWithItems:
  3972. problem: str
  3973. items: Sequence[str]
  3974. @dataclass
  3975. class _MissingSecurityOwnersResult:
  3976. owners_file_problems: Sequence[_SecurityProblemWithItems]
  3977. has_security_sensitive_files: bool
  3978. missing_reviewer_problem: Optional[_SecurityProblemWithItems]
  3979. def _FindMissingSecurityOwners(input_api,
  3980. output_api,
  3981. file_patterns: Sequence[str],
  3982. excluded_patterns: Sequence[str],
  3983. required_owners_file: str,
  3984. custom_rule_function: Optional[Callable] = None
  3985. ) -> _MissingSecurityOwnersResult:
  3986. """Find OWNERS files missing per-file rules for security-sensitive files.
  3987. Args:
  3988. input_api: the PRESUBMIT input API object.
  3989. output_api: the PRESUBMIT output API object.
  3990. file_patterns: basename patterns that require a corresponding per-file
  3991. security restriction.
  3992. excluded_patterns: path patterns that should be exempted from
  3993. requiring a security restriction.
  3994. required_owners_file: path to the required OWNERS file, e.g.
  3995. ipc/SECURITY_OWNERS
  3996. cc_alias: If not None, email that will be CCed automatically if the
  3997. change contains security-sensitive files, as determined by
  3998. `file_patterns` and `excluded_patterns`.
  3999. custom_rule_function: If not None, will be called with `input_api` and
  4000. the current file under consideration. Returning True will add an
  4001. exact match per-file rule check for the current file.
  4002. """
  4003. # `to_check` is a mapping of an OWNERS file path to Patterns.
  4004. #
  4005. # Patterns is a dictionary mapping glob patterns (suitable for use in
  4006. # per-file rules) to a PatternEntry.
  4007. #
  4008. # PatternEntry is a dictionary with two keys:
  4009. # - 'files': the files that are matched by this pattern
  4010. # - 'rules': the per-file rules needed for this pattern
  4011. #
  4012. # For example, if we expect OWNERS file to contain rules for *.mojom and
  4013. # *_struct_traits*.*, Patterns might look like this:
  4014. # {
  4015. # '*.mojom': {
  4016. # 'files': ...,
  4017. # 'rules': [
  4018. # 'per-file *.mojom=set noparent',
  4019. # 'per-file *.mojom=file://ipc/SECURITY_OWNERS',
  4020. # ],
  4021. # },
  4022. # '*_struct_traits*.*': {
  4023. # 'files': ...,
  4024. # 'rules': [
  4025. # 'per-file *_struct_traits*.*=set noparent',
  4026. # 'per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS',
  4027. # ],
  4028. # },
  4029. # }
  4030. to_check = {}
  4031. files_to_review = []
  4032. def AddPatternToCheck(file, pattern):
  4033. owners_file = input_api.os_path.join(
  4034. input_api.os_path.dirname(file.LocalPath()), 'OWNERS')
  4035. if owners_file not in to_check:
  4036. to_check[owners_file] = {}
  4037. if pattern not in to_check[owners_file]:
  4038. to_check[owners_file][pattern] = {
  4039. 'files': [],
  4040. 'rules': [
  4041. f'per-file {pattern}=set noparent',
  4042. f'per-file {pattern}=file://{required_owners_file}',
  4043. ]
  4044. }
  4045. to_check[owners_file][pattern]['files'].append(file.LocalPath())
  4046. files_to_review.append(file.LocalPath())
  4047. # Only enforce security OWNERS rules for a directory if that directory has a
  4048. # file that matches `file_patterns`. For example, if a directory only
  4049. # contains *.mojom files and no *_messages*.h files, the check should only
  4050. # ensure that rules for *.mojom files are present.
  4051. for file in input_api.AffectedFiles(include_deletes=False):
  4052. file_basename = input_api.os_path.basename(file.LocalPath())
  4053. if custom_rule_function is not None and custom_rule_function(
  4054. input_api, file):
  4055. AddPatternToCheck(file, file_basename)
  4056. continue
  4057. if any(
  4058. input_api.fnmatch.fnmatch(file.LocalPath(), pattern)
  4059. for pattern in excluded_patterns):
  4060. continue
  4061. for pattern in file_patterns:
  4062. # Unlike `excluded_patterns`, `file_patterns` is checked only against the
  4063. # file's basename.
  4064. if input_api.fnmatch.fnmatch(file_basename, pattern):
  4065. AddPatternToCheck(file, pattern)
  4066. break
  4067. has_security_sensitive_files = bool(to_check)
  4068. # Check if any newly added lines in OWNERS files intersect with required
  4069. # per-file OWNERS lines. If so, ensure that a security reviewer is included.
  4070. # This is a hack, but is needed because the OWNERS check (by design) ignores
  4071. # new OWNERS entries; otherwise, a non-owner could add someone as a new
  4072. # OWNER and have that newly-added OWNER self-approve their own addition.
  4073. newly_covered_files = []
  4074. for file in input_api.AffectedFiles(include_deletes=False):
  4075. if not file.LocalPath() in to_check:
  4076. continue
  4077. for _, line in file.ChangedContents():
  4078. for _, entry in to_check[file.LocalPath()].items():
  4079. if line in entry['rules']:
  4080. newly_covered_files.extend(entry['files'])
  4081. missing_reviewer_problems = None
  4082. if newly_covered_files and not _ChangeHasSecurityReviewer(
  4083. input_api, required_owners_file):
  4084. missing_reviewer_problems = _SecurityProblemWithItems(
  4085. f'Review from an owner in {required_owners_file} is required for '
  4086. 'the following newly-added files:',
  4087. [f'{file}' for file in sorted(set(newly_covered_files))])
  4088. # Go through the OWNERS files to check, filtering out rules that are already
  4089. # present in that OWNERS file.
  4090. for owners_file, patterns in to_check.items():
  4091. try:
  4092. lines = set(
  4093. input_api.ReadFile(
  4094. input_api.os_path.join(input_api.change.RepositoryRoot(),
  4095. owners_file)).splitlines())
  4096. for entry in patterns.values():
  4097. entry['rules'] = [
  4098. rule for rule in entry['rules'] if rule not in lines
  4099. ]
  4100. except IOError:
  4101. # No OWNERS file, so all the rules are definitely missing.
  4102. continue
  4103. # All the remaining lines weren't found in OWNERS files, so emit an error.
  4104. owners_file_problems = []
  4105. for owners_file, patterns in to_check.items():
  4106. missing_lines = []
  4107. files = []
  4108. for _, entry in patterns.items():
  4109. files.extend(entry['files'])
  4110. missing_lines.extend(entry['rules'])
  4111. if missing_lines:
  4112. joined_missing_lines = '\n'.join(line for line in missing_lines)
  4113. owners_file_problems.append(
  4114. _SecurityProblemWithItems(
  4115. 'Found missing OWNERS lines for security-sensitive files. '
  4116. f'Please add the following lines to {owners_file}:\n'
  4117. f'{joined_missing_lines}\n\nTo ensure security review for:',
  4118. files))
  4119. return _MissingSecurityOwnersResult(owners_file_problems,
  4120. has_security_sensitive_files,
  4121. missing_reviewer_problems)
  4122. def _CheckChangeForIpcSecurityOwners(input_api, output_api):
  4123. # Whether or not a file affects IPC is (mostly) determined by a simple list
  4124. # of filename patterns.
  4125. file_patterns = [
  4126. # Legacy IPC:
  4127. '*_messages.cc',
  4128. '*_messages*.h',
  4129. '*_param_traits*.*',
  4130. # Mojo IPC:
  4131. '*.mojom',
  4132. '*_mojom_traits*.*',
  4133. '*_type_converter*.*',
  4134. # Android native IPC:
  4135. '*.aidl',
  4136. ]
  4137. excluded_patterns = [
  4138. # These third_party directories do not contain IPCs, but contain files
  4139. # matching the above patterns, which trigger false positives.
  4140. 'third_party/crashpad/*',
  4141. 'third_party/blink/renderer/platform/bindings/*',
  4142. 'third_party/protobuf/benchmarks/python/*',
  4143. 'third_party/win_build_output/*',
  4144. # Enum-only mojoms used for web metrics, so no security review needed.
  4145. 'third_party/blink/public/mojom/use_counter/metrics/*',
  4146. # These files are just used to communicate between class loaders running
  4147. # in the same process.
  4148. 'weblayer/browser/java/org/chromium/weblayer_private/interfaces/*',
  4149. 'weblayer/browser/java/org/chromium/weblayer_private/test_interfaces/*',
  4150. ]
  4151. def IsMojoServiceManifestFile(input_api, file):
  4152. manifest_pattern = input_api.re.compile('manifests?\.(cc|h)$')
  4153. test_manifest_pattern = input_api.re.compile('test_manifests?\.(cc|h)')
  4154. if not manifest_pattern.search(file.LocalPath()):
  4155. return False
  4156. if test_manifest_pattern.search(file.LocalPath()):
  4157. return False
  4158. # All actual service manifest files should contain at least one
  4159. # qualified reference to service_manager::Manifest.
  4160. return any('service_manager::Manifest' in line
  4161. for line in file.NewContents())
  4162. return _FindMissingSecurityOwners(
  4163. input_api,
  4164. output_api,
  4165. file_patterns,
  4166. excluded_patterns,
  4167. 'ipc/SECURITY_OWNERS',
  4168. custom_rule_function=IsMojoServiceManifestFile)
  4169. def _CheckChangeForFuchsiaSecurityOwners(input_api, output_api):
  4170. file_patterns = [
  4171. # Component specifications.
  4172. '*.cml', # Component Framework v2.
  4173. '*.cmx', # Component Framework v1.
  4174. # Fuchsia IDL protocol specifications.
  4175. '*.fidl',
  4176. ]
  4177. # Don't check for owners files for changes in these directories.
  4178. excluded_patterns = [
  4179. 'third_party/crashpad/*',
  4180. ]
  4181. return _FindMissingSecurityOwners(input_api, output_api, file_patterns,
  4182. excluded_patterns,
  4183. 'build/fuchsia/SECURITY_OWNERS')
  4184. def CheckSecurityOwners(input_api, output_api):
  4185. """Checks that various security-sensitive files have an IPC OWNERS rule."""
  4186. ipc_results = _CheckChangeForIpcSecurityOwners(input_api, output_api)
  4187. fuchsia_results = _CheckChangeForFuchsiaSecurityOwners(
  4188. input_api, output_api)
  4189. if ipc_results.has_security_sensitive_files:
  4190. output_api.AppendCC('ipc-security-reviews@chromium.org')
  4191. results = []
  4192. missing_reviewer_problems = []
  4193. if ipc_results.missing_reviewer_problem:
  4194. missing_reviewer_problems.append(ipc_results.missing_reviewer_problem)
  4195. if fuchsia_results.missing_reviewer_problem:
  4196. missing_reviewer_problems.append(
  4197. fuchsia_results.missing_reviewer_problem)
  4198. # Missing reviewers are an error unless there's no issue number
  4199. # associated with this branch; in that case, the presubmit is being run
  4200. # with --all or --files.
  4201. #
  4202. # Note that upload should never be an error; otherwise, it would be
  4203. # impossible to upload changes at all.
  4204. if input_api.is_committing and input_api.change.issue:
  4205. make_presubmit_message = output_api.PresubmitError
  4206. else:
  4207. make_presubmit_message = output_api.PresubmitNotifyResult
  4208. for problem in missing_reviewer_problems:
  4209. results.append(
  4210. make_presubmit_message(problem.problem, items=problem.items))
  4211. owners_file_problems = []
  4212. owners_file_problems.extend(ipc_results.owners_file_problems)
  4213. owners_file_problems.extend(fuchsia_results.owners_file_problems)
  4214. for problem in owners_file_problems:
  4215. # Missing per-file rules are always an error. While swarming and caching
  4216. # means that uploading a patchset with updated OWNERS files and sending
  4217. # it to the CQ again should not have a large incremental cost, it is
  4218. # still frustrating to discover the error only after the change has
  4219. # already been uploaded.
  4220. results.append(
  4221. output_api.PresubmitError(problem.problem, items=problem.items))
  4222. return results
  4223. def _GetFilesUsingSecurityCriticalFunctions(input_api):
  4224. """Checks affected files for changes to security-critical calls. This
  4225. function checks the full change diff, to catch both additions/changes
  4226. and removals.
  4227. Returns a dict keyed by file name, and the value is a set of detected
  4228. functions.
  4229. """
  4230. # Map of function pretty name (displayed in an error) to the pattern to
  4231. # match it with.
  4232. _PATTERNS_TO_CHECK = {
  4233. 'content::GetServiceSandboxType<>()': 'GetServiceSandboxType\\<'
  4234. }
  4235. _PATTERNS_TO_CHECK = {
  4236. k: input_api.re.compile(v)
  4237. for k, v in _PATTERNS_TO_CHECK.items()
  4238. }
  4239. # We don't want to trigger on strings within this file.
  4240. def presubmit_file_filter(f):
  4241. return 'PRESUBMIT.py' != input_api.os_path.split(f.LocalPath())[1]
  4242. # Scan all affected files for changes touching _FUNCTIONS_TO_CHECK.
  4243. files_to_functions = {}
  4244. for f in input_api.AffectedFiles(file_filter=presubmit_file_filter):
  4245. diff = f.GenerateScmDiff()
  4246. for line in diff.split('\n'):
  4247. # Not using just RightHandSideLines() because removing a
  4248. # call to a security-critical function can be just as important
  4249. # as adding or changing the arguments.
  4250. if line.startswith('-') or (line.startswith('+')
  4251. and not line.startswith('++')):
  4252. for name, pattern in _PATTERNS_TO_CHECK.items():
  4253. if pattern.search(line):
  4254. path = f.LocalPath()
  4255. if not path in files_to_functions:
  4256. files_to_functions[path] = set()
  4257. files_to_functions[path].add(name)
  4258. return files_to_functions
  4259. def CheckSecurityChanges(input_api, output_api):
  4260. """Checks that changes involving security-critical functions are reviewed
  4261. by the security team.
  4262. """
  4263. files_to_functions = _GetFilesUsingSecurityCriticalFunctions(input_api)
  4264. if not len(files_to_functions):
  4265. return []
  4266. owners_file = 'ipc/SECURITY_OWNERS'
  4267. if _ChangeHasSecurityReviewer(input_api, owners_file):
  4268. return []
  4269. msg = 'The following files change calls to security-sensitive functions\n' \
  4270. 'that need to be reviewed by {}.\n'.format(owners_file)
  4271. for path, names in files_to_functions.items():
  4272. msg += ' {}\n'.format(path)
  4273. for name in names:
  4274. msg += ' {}\n'.format(name)
  4275. msg += '\n'
  4276. if input_api.is_committing:
  4277. output = output_api.PresubmitError
  4278. else:
  4279. output = output_api.PresubmitNotifyResult
  4280. return [output(msg)]
  4281. def CheckSetNoParent(input_api, output_api):
  4282. """Checks that set noparent is only used together with an OWNERS file in
  4283. //build/OWNERS.setnoparent (see also
  4284. //docs/code_reviews.md#owners-files-details)
  4285. """
  4286. # Return early if no OWNERS files were modified.
  4287. if not any(f.LocalPath().endswith('OWNERS')
  4288. for f in input_api.AffectedFiles(include_deletes=False)):
  4289. return []
  4290. errors = []
  4291. allowed_owners_files_file = 'build/OWNERS.setnoparent'
  4292. allowed_owners_files = set()
  4293. with open(allowed_owners_files_file, 'r', encoding='utf-8') as f:
  4294. for line in f:
  4295. line = line.strip()
  4296. if not line or line.startswith('#'):
  4297. continue
  4298. allowed_owners_files.add(line)
  4299. per_file_pattern = input_api.re.compile('per-file (.+)=(.+)')
  4300. for f in input_api.AffectedFiles(include_deletes=False):
  4301. if not f.LocalPath().endswith('OWNERS'):
  4302. continue
  4303. found_owners_files = set()
  4304. found_set_noparent_lines = dict()
  4305. # Parse the OWNERS file.
  4306. for lineno, line in enumerate(f.NewContents(), 1):
  4307. line = line.strip()
  4308. if line.startswith('set noparent'):
  4309. found_set_noparent_lines[''] = lineno
  4310. if line.startswith('file://'):
  4311. if line in allowed_owners_files:
  4312. found_owners_files.add('')
  4313. if line.startswith('per-file'):
  4314. match = per_file_pattern.match(line)
  4315. if match:
  4316. glob = match.group(1).strip()
  4317. directive = match.group(2).strip()
  4318. if directive == 'set noparent':
  4319. found_set_noparent_lines[glob] = lineno
  4320. if directive.startswith('file://'):
  4321. if directive in allowed_owners_files:
  4322. found_owners_files.add(glob)
  4323. # Check that every set noparent line has a corresponding file:// line
  4324. # listed in build/OWNERS.setnoparent. An exception is made for top level
  4325. # directories since src/OWNERS shouldn't review them.
  4326. linux_path = f.LocalPath().replace(input_api.os_path.sep, '/')
  4327. if (linux_path.count('/') != 1
  4328. and (not linux_path in _EXCLUDED_SET_NO_PARENT_PATHS)):
  4329. for set_noparent_line in found_set_noparent_lines:
  4330. if set_noparent_line in found_owners_files:
  4331. continue
  4332. errors.append(' %s:%d' %
  4333. (linux_path,
  4334. found_set_noparent_lines[set_noparent_line]))
  4335. results = []
  4336. if errors:
  4337. if input_api.is_committing:
  4338. output = output_api.PresubmitError
  4339. else:
  4340. output = output_api.PresubmitPromptWarning
  4341. results.append(
  4342. output(
  4343. 'Found the following "set noparent" restrictions in OWNERS files that '
  4344. 'do not include owners from build/OWNERS.setnoparent:',
  4345. long_text='\n\n'.join(errors)))
  4346. return results
  4347. def CheckUselessForwardDeclarations(input_api, output_api):
  4348. """Checks that added or removed lines in non third party affected
  4349. header files do not lead to new useless class or struct forward
  4350. declaration.
  4351. """
  4352. results = []
  4353. class_pattern = input_api.re.compile(r'^class\s+(\w+);$',
  4354. input_api.re.MULTILINE)
  4355. struct_pattern = input_api.re.compile(r'^struct\s+(\w+);$',
  4356. input_api.re.MULTILINE)
  4357. for f in input_api.AffectedFiles(include_deletes=False):
  4358. if (f.LocalPath().startswith('third_party')
  4359. and not f.LocalPath().startswith('third_party/blink')
  4360. and not f.LocalPath().startswith('third_party\\blink')):
  4361. continue
  4362. if not f.LocalPath().endswith('.h'):
  4363. continue
  4364. contents = input_api.ReadFile(f)
  4365. fwd_decls = input_api.re.findall(class_pattern, contents)
  4366. fwd_decls.extend(input_api.re.findall(struct_pattern, contents))
  4367. useless_fwd_decls = []
  4368. for decl in fwd_decls:
  4369. count = sum(1 for _ in input_api.re.finditer(
  4370. r'\b%s\b' % input_api.re.escape(decl), contents))
  4371. if count == 1:
  4372. useless_fwd_decls.append(decl)
  4373. if not useless_fwd_decls:
  4374. continue
  4375. for line in f.GenerateScmDiff().splitlines():
  4376. if (line.startswith('-') and not line.startswith('--')
  4377. or line.startswith('+') and not line.startswith('++')):
  4378. for decl in useless_fwd_decls:
  4379. if input_api.re.search(r'\b%s\b' % decl, line[1:]):
  4380. results.append(
  4381. output_api.PresubmitPromptWarning(
  4382. '%s: %s forward declaration is no longer needed'
  4383. % (f.LocalPath(), decl)))
  4384. useless_fwd_decls.remove(decl)
  4385. return results
  4386. def _CheckAndroidDebuggableBuild(input_api, output_api):
  4387. """Checks that code uses BuildInfo.isDebugAndroid() instead of
  4388. Build.TYPE.equals('') or ''.equals(Build.TYPE) to check if
  4389. this is a debuggable build of Android.
  4390. """
  4391. build_type_check_pattern = input_api.re.compile(
  4392. r'\bBuild\.TYPE\.equals\(|\.equals\(\s*\bBuild\.TYPE\)')
  4393. errors = []
  4394. sources = lambda affected_file: input_api.FilterSourceFile(
  4395. affected_file,
  4396. files_to_skip=(
  4397. _EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  4398. DEFAULT_FILES_TO_SKIP + (
  4399. r"^android_webview/support_library/boundary_interfaces/",
  4400. r"^chrome/android/webapk/.*",
  4401. r'^third_party/.*',
  4402. r"tools/android/customtabs_benchmark/.*",
  4403. r"webview/chromium/License.*",
  4404. )),
  4405. files_to_check=[r'.*\.java$'])
  4406. for f in input_api.AffectedSourceFiles(sources):
  4407. for line_num, line in f.ChangedContents():
  4408. if build_type_check_pattern.search(line):
  4409. errors.append("%s:%d" % (f.LocalPath(), line_num))
  4410. results = []
  4411. if errors:
  4412. results.append(
  4413. output_api.PresubmitPromptWarning(
  4414. 'Build.TYPE.equals or .equals(Build.TYPE) usage is detected.'
  4415. ' Please use BuildInfo.isDebugAndroid() instead.', errors))
  4416. return results
  4417. # TODO: add unit tests
  4418. def _CheckAndroidToastUsage(input_api, output_api):
  4419. """Checks that code uses org.chromium.ui.widget.Toast instead of
  4420. android.widget.Toast (Chromium Toast doesn't force hardware
  4421. acceleration on low-end devices, saving memory).
  4422. """
  4423. toast_import_pattern = input_api.re.compile(
  4424. r'^import android\.widget\.Toast;$')
  4425. errors = []
  4426. sources = lambda affected_file: input_api.FilterSourceFile(
  4427. affected_file,
  4428. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  4429. DEFAULT_FILES_TO_SKIP + (r'^chromecast/.*',
  4430. r'^remoting/.*')),
  4431. files_to_check=[r'.*\.java$'])
  4432. for f in input_api.AffectedSourceFiles(sources):
  4433. for line_num, line in f.ChangedContents():
  4434. if toast_import_pattern.search(line):
  4435. errors.append("%s:%d" % (f.LocalPath(), line_num))
  4436. results = []
  4437. if errors:
  4438. results.append(
  4439. output_api.PresubmitError(
  4440. 'android.widget.Toast usage is detected. Android toasts use hardware'
  4441. ' acceleration, and can be\ncostly on low-end devices. Please use'
  4442. ' org.chromium.ui.widget.Toast instead.\n'
  4443. 'Contact dskiba@chromium.org if you have any questions.',
  4444. errors))
  4445. return results
  4446. def _CheckAndroidCrLogUsage(input_api, output_api):
  4447. """Checks that new logs using org.chromium.base.Log:
  4448. - Are using 'TAG' as variable name for the tags (warn)
  4449. - Are using a tag that is shorter than 20 characters (error)
  4450. """
  4451. # Do not check format of logs in the given files
  4452. cr_log_check_excluded_paths = [
  4453. # //chrome/android/webapk cannot depend on //base
  4454. r"^chrome/android/webapk/.*",
  4455. # WebView license viewer code cannot depend on //base; used in stub APK.
  4456. r"^android_webview/glue/java/src/com/android/"
  4457. r"webview/chromium/License.*",
  4458. # The customtabs_benchmark is a small app that does not depend on Chromium
  4459. # java pieces.
  4460. r"tools/android/customtabs_benchmark/.*",
  4461. ]
  4462. cr_log_import_pattern = input_api.re.compile(
  4463. r'^import org\.chromium\.base\.Log;$', input_api.re.MULTILINE)
  4464. class_in_base_pattern = input_api.re.compile(
  4465. r'^package org\.chromium\.base;$', input_api.re.MULTILINE)
  4466. has_some_log_import_pattern = input_api.re.compile(r'^import .*\.Log;$',
  4467. input_api.re.MULTILINE)
  4468. # Extract the tag from lines like `Log.d(TAG, "*");` or `Log.d("TAG", "*");`
  4469. log_call_pattern = input_api.re.compile(r'\bLog\.\w\((?P<tag>\"?\w+)')
  4470. log_decl_pattern = input_api.re.compile(
  4471. r'static final String TAG = "(?P<name>(.*))"')
  4472. rough_log_decl_pattern = input_api.re.compile(r'\bString TAG\s*=')
  4473. REF_MSG = ('See docs/android_logging.md for more info.')
  4474. sources = lambda x: input_api.FilterSourceFile(
  4475. x,
  4476. files_to_check=[r'.*\.java$'],
  4477. files_to_skip=cr_log_check_excluded_paths)
  4478. tag_decl_errors = []
  4479. tag_length_errors = []
  4480. tag_errors = []
  4481. tag_with_dot_errors = []
  4482. util_log_errors = []
  4483. for f in input_api.AffectedSourceFiles(sources):
  4484. file_content = input_api.ReadFile(f)
  4485. has_modified_logs = False
  4486. # Per line checks
  4487. if (cr_log_import_pattern.search(file_content)
  4488. or (class_in_base_pattern.search(file_content)
  4489. and not has_some_log_import_pattern.search(file_content))):
  4490. # Checks to run for files using cr log
  4491. for line_num, line in f.ChangedContents():
  4492. if rough_log_decl_pattern.search(line):
  4493. has_modified_logs = True
  4494. # Check if the new line is doing some logging
  4495. match = log_call_pattern.search(line)
  4496. if match:
  4497. has_modified_logs = True
  4498. # Make sure it uses "TAG"
  4499. if not match.group('tag') == 'TAG':
  4500. tag_errors.append("%s:%d" % (f.LocalPath(), line_num))
  4501. else:
  4502. # Report non cr Log function calls in changed lines
  4503. for line_num, line in f.ChangedContents():
  4504. if log_call_pattern.search(line):
  4505. util_log_errors.append("%s:%d" % (f.LocalPath(), line_num))
  4506. # Per file checks
  4507. if has_modified_logs:
  4508. # Make sure the tag is using the "cr" prefix and is not too long
  4509. match = log_decl_pattern.search(file_content)
  4510. tag_name = match.group('name') if match else None
  4511. if not tag_name:
  4512. tag_decl_errors.append(f.LocalPath())
  4513. elif len(tag_name) > 20:
  4514. tag_length_errors.append(f.LocalPath())
  4515. elif '.' in tag_name:
  4516. tag_with_dot_errors.append(f.LocalPath())
  4517. results = []
  4518. if tag_decl_errors:
  4519. results.append(
  4520. output_api.PresubmitPromptWarning(
  4521. 'Please define your tags using the suggested format: .\n'
  4522. '"private static final String TAG = "<package tag>".\n'
  4523. 'They will be prepended with "cr_" automatically.\n' + REF_MSG,
  4524. tag_decl_errors))
  4525. if tag_length_errors:
  4526. results.append(
  4527. output_api.PresubmitError(
  4528. 'The tag length is restricted by the system to be at most '
  4529. '20 characters.\n' + REF_MSG, tag_length_errors))
  4530. if tag_errors:
  4531. results.append(
  4532. output_api.PresubmitPromptWarning(
  4533. 'Please use a variable named "TAG" for your log tags.\n' +
  4534. REF_MSG, tag_errors))
  4535. if util_log_errors:
  4536. results.append(
  4537. output_api.PresubmitPromptWarning(
  4538. 'Please use org.chromium.base.Log for new logs.\n' + REF_MSG,
  4539. util_log_errors))
  4540. if tag_with_dot_errors:
  4541. results.append(
  4542. output_api.PresubmitPromptWarning(
  4543. 'Dot in log tags cause them to be elided in crash reports.\n' +
  4544. REF_MSG, tag_with_dot_errors))
  4545. return results
  4546. def _CheckAndroidTestAnnotationUsage(input_api, output_api):
  4547. """Checks that android.test.suitebuilder.annotation.* is no longer used."""
  4548. deprecated_annotation_import_pattern = input_api.re.compile(
  4549. r'^import android\.test\.suitebuilder\.annotation\..*;',
  4550. input_api.re.MULTILINE)
  4551. sources = lambda x: input_api.FilterSourceFile(
  4552. x, files_to_check=[r'.*\.java$'], files_to_skip=None)
  4553. errors = []
  4554. for f in input_api.AffectedFiles(file_filter=sources):
  4555. for line_num, line in f.ChangedContents():
  4556. if deprecated_annotation_import_pattern.search(line):
  4557. errors.append("%s:%d" % (f.LocalPath(), line_num))
  4558. results = []
  4559. if errors:
  4560. results.append(
  4561. output_api.PresubmitError(
  4562. 'Annotations in android.test.suitebuilder.annotation have been'
  4563. ' deprecated since API level 24. Please use androidx.test.filters'
  4564. ' from //third_party/androidx:androidx_test_runner_java instead.'
  4565. ' Contact yolandyan@chromium.org if you have any questions.',
  4566. errors))
  4567. return results
  4568. def _CheckAndroidNewMdpiAssetLocation(input_api, output_api):
  4569. """Checks if MDPI assets are placed in a correct directory."""
  4570. file_filter = lambda f: (f.LocalPath().endswith(
  4571. '.png') and ('/res/drawable/'.replace('/', input_api.os_path.sep) in f.
  4572. LocalPath() or '/res/drawable-ldrtl/'.replace(
  4573. '/', input_api.os_path.sep) in f.LocalPath()))
  4574. errors = []
  4575. for f in input_api.AffectedFiles(include_deletes=False,
  4576. file_filter=file_filter):
  4577. errors.append(' %s' % f.LocalPath())
  4578. results = []
  4579. if errors:
  4580. results.append(
  4581. output_api.PresubmitError(
  4582. 'MDPI assets should be placed in /res/drawable-mdpi/ or '
  4583. '/res/drawable-ldrtl-mdpi/\ninstead of /res/drawable/ and'
  4584. '/res/drawable-ldrtl/.\n'
  4585. 'Contact newt@chromium.org if you have questions.', errors))
  4586. return results
  4587. def _CheckAndroidWebkitImports(input_api, output_api):
  4588. """Checks that code uses org.chromium.base.Callback instead of
  4589. android.webview.ValueCallback except in the WebView glue layer
  4590. and WebLayer.
  4591. """
  4592. valuecallback_import_pattern = input_api.re.compile(
  4593. r'^import android\.webkit\.ValueCallback;$')
  4594. errors = []
  4595. sources = lambda affected_file: input_api.FilterSourceFile(
  4596. affected_file,
  4597. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  4598. DEFAULT_FILES_TO_SKIP + (
  4599. r'^android_webview/glue/.*',
  4600. r'^android_webview/support_library/.*',
  4601. r'^weblayer/.*',
  4602. )),
  4603. files_to_check=[r'.*\.java$'])
  4604. for f in input_api.AffectedSourceFiles(sources):
  4605. for line_num, line in f.ChangedContents():
  4606. if valuecallback_import_pattern.search(line):
  4607. errors.append("%s:%d" % (f.LocalPath(), line_num))
  4608. results = []
  4609. if errors:
  4610. results.append(
  4611. output_api.PresubmitError(
  4612. 'android.webkit.ValueCallback usage is detected outside of the glue'
  4613. ' layer. To stay compatible with the support library, android.webkit.*'
  4614. ' classes should only be used inside the glue layer and'
  4615. ' org.chromium.base.Callback should be used instead.', errors))
  4616. return results
  4617. def _CheckAndroidXmlStyle(input_api, output_api, is_check_on_upload):
  4618. """Checks Android XML styles """
  4619. # Return early if no relevant files were modified.
  4620. if not any(
  4621. _IsXmlOrGrdFile(input_api, f.LocalPath())
  4622. for f in input_api.AffectedFiles(include_deletes=False)):
  4623. return []
  4624. import sys
  4625. original_sys_path = sys.path
  4626. try:
  4627. sys.path = sys.path + [
  4628. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  4629. 'android', 'checkxmlstyle')
  4630. ]
  4631. import checkxmlstyle
  4632. finally:
  4633. # Restore sys.path to what it was before.
  4634. sys.path = original_sys_path
  4635. if is_check_on_upload:
  4636. return checkxmlstyle.CheckStyleOnUpload(input_api, output_api)
  4637. else:
  4638. return checkxmlstyle.CheckStyleOnCommit(input_api, output_api)
  4639. def _CheckAndroidInfoBarDeprecation(input_api, output_api):
  4640. """Checks Android Infobar Deprecation """
  4641. import sys
  4642. original_sys_path = sys.path
  4643. try:
  4644. sys.path = sys.path + [
  4645. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  4646. 'android', 'infobar_deprecation')
  4647. ]
  4648. import infobar_deprecation
  4649. finally:
  4650. # Restore sys.path to what it was before.
  4651. sys.path = original_sys_path
  4652. return infobar_deprecation.CheckDeprecationOnUpload(input_api, output_api)
  4653. class _PydepsCheckerResult:
  4654. def __init__(self, cmd, pydeps_path, process, old_contents):
  4655. self._cmd = cmd
  4656. self._pydeps_path = pydeps_path
  4657. self._process = process
  4658. self._old_contents = old_contents
  4659. def GetError(self):
  4660. """Returns an error message, or None."""
  4661. import difflib
  4662. new_contents = self._process.stdout.read().splitlines()[2:]
  4663. if self._process.wait() != 0:
  4664. # STDERR should already be printed.
  4665. return 'Command failed: ' + self._cmd
  4666. if self._old_contents != new_contents:
  4667. diff = '\n'.join(
  4668. difflib.context_diff(self._old_contents, new_contents))
  4669. return ('File is stale: {}\n'
  4670. 'Diff (apply to fix):\n'
  4671. '{}\n'
  4672. 'To regenerate, run:\n\n'
  4673. ' {}').format(self._pydeps_path, diff, self._cmd)
  4674. return None
  4675. class PydepsChecker:
  4676. def __init__(self, input_api, pydeps_files):
  4677. self._file_cache = {}
  4678. self._input_api = input_api
  4679. self._pydeps_files = pydeps_files
  4680. def _LoadFile(self, path):
  4681. """Returns the list of paths within a .pydeps file relative to //."""
  4682. if path not in self._file_cache:
  4683. with open(path, encoding='utf-8') as f:
  4684. self._file_cache[path] = f.read()
  4685. return self._file_cache[path]
  4686. def _ComputeNormalizedPydepsEntries(self, pydeps_path):
  4687. """Returns an iterable of paths within the .pydep, relativized to //."""
  4688. pydeps_data = self._LoadFile(pydeps_path)
  4689. uses_gn_paths = '--gn-paths' in pydeps_data
  4690. entries = (l for l in pydeps_data.splitlines()
  4691. if not l.startswith('#'))
  4692. if uses_gn_paths:
  4693. # Paths look like: //foo/bar/baz
  4694. return (e[2:] for e in entries)
  4695. else:
  4696. # Paths look like: path/relative/to/file.pydeps
  4697. os_path = self._input_api.os_path
  4698. pydeps_dir = os_path.dirname(pydeps_path)
  4699. return (os_path.normpath(os_path.join(pydeps_dir, e))
  4700. for e in entries)
  4701. def _CreateFilesToPydepsMap(self):
  4702. """Returns a map of local_path -> list_of_pydeps."""
  4703. ret = {}
  4704. for pydep_local_path in self._pydeps_files:
  4705. for path in self._ComputeNormalizedPydepsEntries(pydep_local_path):
  4706. ret.setdefault(path, []).append(pydep_local_path)
  4707. return ret
  4708. def ComputeAffectedPydeps(self):
  4709. """Returns an iterable of .pydeps files that might need regenerating."""
  4710. affected_pydeps = set()
  4711. file_to_pydeps_map = None
  4712. for f in self._input_api.AffectedFiles(include_deletes=True):
  4713. local_path = f.LocalPath()
  4714. # Changes to DEPS can lead to .pydeps changes if any .py files are in
  4715. # subrepositories. We can't figure out which files change, so re-check
  4716. # all files.
  4717. # Changes to print_python_deps.py affect all .pydeps.
  4718. if local_path in ('DEPS', 'PRESUBMIT.py'
  4719. ) or local_path.endswith('print_python_deps.py'):
  4720. return self._pydeps_files
  4721. elif local_path.endswith('.pydeps'):
  4722. if local_path in self._pydeps_files:
  4723. affected_pydeps.add(local_path)
  4724. elif local_path.endswith('.py'):
  4725. if file_to_pydeps_map is None:
  4726. file_to_pydeps_map = self._CreateFilesToPydepsMap()
  4727. affected_pydeps.update(file_to_pydeps_map.get(local_path, ()))
  4728. return affected_pydeps
  4729. def DetermineIfStaleAsync(self, pydeps_path):
  4730. """Runs print_python_deps.py to see if the files is stale."""
  4731. import os
  4732. old_pydeps_data = self._LoadFile(pydeps_path).splitlines()
  4733. if old_pydeps_data:
  4734. cmd = old_pydeps_data[1][1:].strip()
  4735. if '--output' not in cmd:
  4736. cmd += ' --output ' + pydeps_path
  4737. old_contents = old_pydeps_data[2:]
  4738. else:
  4739. # A default cmd that should work in most cases (as long as pydeps filename
  4740. # matches the script name) so that PRESUBMIT.py does not crash if pydeps
  4741. # file is empty/new.
  4742. cmd = 'build/print_python_deps.py {} --root={} --output={}'.format(
  4743. pydeps_path[:-4], os.path.dirname(pydeps_path), pydeps_path)
  4744. old_contents = []
  4745. env = dict(os.environ)
  4746. env['PYTHONDONTWRITEBYTECODE'] = '1'
  4747. process = self._input_api.subprocess.Popen(
  4748. cmd + ' --output ""',
  4749. shell=True,
  4750. env=env,
  4751. stdout=self._input_api.subprocess.PIPE,
  4752. encoding='utf-8')
  4753. return _PydepsCheckerResult(cmd, pydeps_path, process, old_contents)
  4754. def _ParseGclientArgs():
  4755. args = {}
  4756. with open('build/config/gclient_args.gni', 'r') as f:
  4757. for line in f:
  4758. line = line.strip()
  4759. if not line or line.startswith('#'):
  4760. continue
  4761. attribute, value = line.split('=')
  4762. args[attribute.strip()] = value.strip()
  4763. return args
  4764. def CheckPydepsNeedsUpdating(input_api, output_api, checker_for_tests=None):
  4765. """Checks if a .pydeps file needs to be regenerated."""
  4766. # This check is for Python dependency lists (.pydeps files), and involves
  4767. # paths not only in the PRESUBMIT.py, but also in the .pydeps files. It
  4768. # doesn't work on Windows and Mac, so skip it on other platforms.
  4769. if not input_api.platform.startswith('linux'):
  4770. return []
  4771. results = []
  4772. # First, check for new / deleted .pydeps.
  4773. for f in input_api.AffectedFiles(include_deletes=True):
  4774. # Check whether we are running the presubmit check for a file in src.
  4775. if f.LocalPath().endswith('.pydeps'):
  4776. # f.LocalPath is relative to repo (src, or internal repo).
  4777. # os_path.exists is relative to src repo.
  4778. # Therefore if os_path.exists is true, it means f.LocalPath is relative
  4779. # to src and we can conclude that the pydeps is in src.
  4780. exists = input_api.os_path.exists(f.LocalPath())
  4781. if f.Action() == 'D' and f.LocalPath() in _ALL_PYDEPS_FILES:
  4782. results.append(
  4783. output_api.PresubmitError(
  4784. 'Please update _ALL_PYDEPS_FILES within //PRESUBMIT.py to '
  4785. 'remove %s' % f.LocalPath()))
  4786. elif (f.Action() != 'D' and exists
  4787. and f.LocalPath() not in _ALL_PYDEPS_FILES):
  4788. results.append(
  4789. output_api.PresubmitError(
  4790. 'Please update _ALL_PYDEPS_FILES within //PRESUBMIT.py to '
  4791. 'include %s' % f.LocalPath()))
  4792. if results:
  4793. return results
  4794. try:
  4795. parsed_args = _ParseGclientArgs()
  4796. except FileNotFoundError:
  4797. message = (
  4798. 'build/config/gclient_args.gni not found. Please make sure your '
  4799. 'workspace has been initialized with gclient sync.'
  4800. )
  4801. import sys
  4802. original_sys_path = sys.path
  4803. try:
  4804. sys.path = sys.path + [
  4805. input_api.os_path.join(input_api.PresubmitLocalPath(),
  4806. 'third_party', 'depot_tools')
  4807. ]
  4808. import gclient_utils
  4809. if gclient_utils.IsEnvCog():
  4810. # Users will always hit this when they run presubmits before cog
  4811. # workspace initialization finishes. The check shouldn't fail in
  4812. # this case. This is an unavoidable workaround that's needed for
  4813. # good presubmit UX for cog.
  4814. results.append(output_api.PresubmitPromptWarning(message))
  4815. else:
  4816. results.append(output_api.PresubmitError(message))
  4817. return results
  4818. finally:
  4819. # Restore sys.path to what it was before.
  4820. sys.path = original_sys_path
  4821. is_android = parsed_args.get('checkout_android', 'false') == 'true'
  4822. checker = checker_for_tests or PydepsChecker(input_api, _ALL_PYDEPS_FILES)
  4823. affected_pydeps = set(checker.ComputeAffectedPydeps())
  4824. affected_android_pydeps = affected_pydeps.intersection(
  4825. set(_ANDROID_SPECIFIC_PYDEPS_FILES))
  4826. if affected_android_pydeps and not is_android:
  4827. results.append(
  4828. output_api.PresubmitPromptOrNotify(
  4829. 'You have changed python files that may affect pydeps for android\n'
  4830. 'specific scripts. However, the relevant presubmit check cannot be\n'
  4831. 'run because you are not using an Android checkout. To validate that\n'
  4832. 'the .pydeps are correct, re-run presubmit in an Android checkout, or\n'
  4833. 'use the android-internal-presubmit optional trybot.\n'
  4834. 'Possibly stale pydeps files:\n{}'.format(
  4835. '\n'.join(affected_android_pydeps))))
  4836. all_pydeps = _ALL_PYDEPS_FILES if is_android else _GENERIC_PYDEPS_FILES
  4837. pydeps_to_check = affected_pydeps.intersection(all_pydeps)
  4838. # Process these concurrently, as each one takes 1-2 seconds.
  4839. pydep_results = [checker.DetermineIfStaleAsync(p) for p in pydeps_to_check]
  4840. for result in pydep_results:
  4841. error_msg = result.GetError()
  4842. if error_msg:
  4843. results.append(output_api.PresubmitError(error_msg))
  4844. return results
  4845. def CheckSingletonInHeaders(input_api, output_api):
  4846. """Checks to make sure no header files have |Singleton<|."""
  4847. def FileFilter(affected_file):
  4848. # It's ok for base/memory/singleton.h to have |Singleton<|.
  4849. files_to_skip = (_EXCLUDED_PATHS + input_api.DEFAULT_FILES_TO_SKIP +
  4850. (r"^base/memory/singleton\.h$",
  4851. r"^net/quic/platform/impl/quic_singleton_impl\.h$"))
  4852. return input_api.FilterSourceFile(affected_file,
  4853. files_to_skip=files_to_skip)
  4854. pattern = input_api.re.compile(r'(?<!class\sbase::)Singleton\s*<')
  4855. files = []
  4856. for f in input_api.AffectedSourceFiles(FileFilter):
  4857. if (f.LocalPath().endswith('.h') or f.LocalPath().endswith('.hxx')
  4858. or f.LocalPath().endswith('.hpp')
  4859. or f.LocalPath().endswith('.inl')):
  4860. contents = input_api.ReadFile(f)
  4861. for line in contents.splitlines(False):
  4862. if (not line.lstrip().startswith('//')
  4863. and # Strip C++ comment.
  4864. pattern.search(line)):
  4865. files.append(f)
  4866. break
  4867. if files:
  4868. return [
  4869. output_api.PresubmitError(
  4870. 'Found base::Singleton<T> in the following header files.\n' +
  4871. 'Please move them to an appropriate source file so that the ' +
  4872. 'template gets instantiated in a single compilation unit.',
  4873. files)
  4874. ]
  4875. return []
  4876. _DEPRECATED_CSS = [
  4877. # Values
  4878. ( "-webkit-box", "flex" ),
  4879. ( "-webkit-inline-box", "inline-flex" ),
  4880. ( "-webkit-flex", "flex" ),
  4881. ( "-webkit-inline-flex", "inline-flex" ),
  4882. ( "-webkit-min-content", "min-content" ),
  4883. ( "-webkit-max-content", "max-content" ),
  4884. # Properties
  4885. ( "-webkit-background-clip", "background-clip" ),
  4886. ( "-webkit-background-origin", "background-origin" ),
  4887. ( "-webkit-background-size", "background-size" ),
  4888. ( "-webkit-box-shadow", "box-shadow" ),
  4889. ( "-webkit-user-select", "user-select" ),
  4890. # Functions
  4891. ( "-webkit-gradient", "gradient" ),
  4892. ( "-webkit-repeating-gradient", "repeating-gradient" ),
  4893. ( "-webkit-linear-gradient", "linear-gradient" ),
  4894. ( "-webkit-repeating-linear-gradient", "repeating-linear-gradient" ),
  4895. ( "-webkit-radial-gradient", "radial-gradient" ),
  4896. ( "-webkit-repeating-radial-gradient", "repeating-radial-gradient" ),
  4897. ]
  4898. # TODO: add unit tests
  4899. def CheckNoDeprecatedCss(input_api, output_api):
  4900. """ Make sure that we don't use deprecated CSS
  4901. properties, functions or values. Our external
  4902. documentation and iOS CSS for dom distiller
  4903. (reader mode) are ignored by the hooks as it
  4904. needs to be consumed by WebKit. """
  4905. results = []
  4906. file_inclusion_pattern = [r".+\.css$"]
  4907. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  4908. input_api.DEFAULT_FILES_TO_SKIP +
  4909. (# Legacy CSS file using deprecated CSS.
  4910. r"^chrome/browser/resources/chromeos/arc_support/cr_overlay.css$",
  4911. r"^chrome/common/extensions/docs", r"^chrome/docs",
  4912. r"^native_client_sdk",
  4913. # The NTP team prefers reserving -webkit-line-clamp for
  4914. # ellipsis effect which can only be used with -webkit-box.
  4915. r"ui/webui/resources/cr_components/most_visited/.*\.css$"))
  4916. file_filter = lambda f: input_api.FilterSourceFile(
  4917. f, files_to_check=file_inclusion_pattern, files_to_skip=files_to_skip)
  4918. for fpath in input_api.AffectedFiles(file_filter=file_filter):
  4919. for line_num, line in fpath.ChangedContents():
  4920. for (deprecated_value, value) in _DEPRECATED_CSS:
  4921. if deprecated_value in line:
  4922. results.append(
  4923. output_api.PresubmitError(
  4924. "%s:%d: Use of deprecated CSS %s, use %s instead" %
  4925. (fpath.LocalPath(), line_num, deprecated_value,
  4926. value)))
  4927. return results
  4928. def CheckForRelativeIncludes(input_api, output_api):
  4929. bad_files = {}
  4930. for f in input_api.AffectedFiles(include_deletes=False):
  4931. if (f.LocalPath().startswith('third_party')
  4932. and not f.LocalPath().startswith('third_party/blink')
  4933. and not f.LocalPath().startswith('third_party\\blink')):
  4934. continue
  4935. if not _IsCPlusPlusFile(input_api, f.LocalPath()):
  4936. continue
  4937. relative_includes = [
  4938. line for _, line in f.ChangedContents()
  4939. if "#include" in line and "../" in line
  4940. ]
  4941. if not relative_includes:
  4942. continue
  4943. bad_files[f.LocalPath()] = relative_includes
  4944. if not bad_files:
  4945. return []
  4946. error_descriptions = []
  4947. for file_path, bad_lines in bad_files.items():
  4948. error_description = file_path
  4949. for line in bad_lines:
  4950. error_description += '\n ' + line
  4951. error_descriptions.append(error_description)
  4952. results = []
  4953. results.append(
  4954. output_api.PresubmitError(
  4955. 'You added one or more relative #include paths (including "../").\n'
  4956. 'These shouldn\'t be used because they can be used to include headers\n'
  4957. 'from code that\'s not correctly specified as a dependency in the\n'
  4958. 'relevant BUILD.gn file(s).', error_descriptions))
  4959. return results
  4960. def CheckForCcIncludes(input_api, output_api):
  4961. """Check that nobody tries to include a cc file. It's a relatively
  4962. common error which results in duplicate symbols in object
  4963. files. This may not always break the build until someone later gets
  4964. very confusing linking errors."""
  4965. results = []
  4966. for f in input_api.AffectedFiles(include_deletes=False):
  4967. # We let third_party code do whatever it wants
  4968. if (f.LocalPath().startswith('third_party')
  4969. and not f.LocalPath().startswith('third_party/blink')
  4970. and not f.LocalPath().startswith('third_party\\blink')):
  4971. continue
  4972. if not _IsCPlusPlusFile(input_api, f.LocalPath()):
  4973. continue
  4974. for _, line in f.ChangedContents():
  4975. if line.startswith('#include "'):
  4976. included_file = line.split('"')[1]
  4977. if _IsCPlusPlusFile(input_api, included_file):
  4978. # The most common naming for external files with C++ code,
  4979. # apart from standard headers, is to call them foo.inc, but
  4980. # Chromium sometimes uses foo-inc.cc so allow that as well.
  4981. if not included_file.endswith(('.h', '-inc.cc')):
  4982. results.append(
  4983. output_api.PresubmitError(
  4984. 'Only header files or .inc files should be included in other\n'
  4985. 'C++ files. Compiling the contents of a cc file more than once\n'
  4986. 'will cause duplicate information in the build which may later\n'
  4987. 'result in strange link_errors.\n' +
  4988. f.LocalPath() + ':\n ' + line))
  4989. return results
  4990. def _CheckWatchlistDefinitionsEntrySyntax(key, value, ast):
  4991. if not isinstance(key, ast.Str):
  4992. return 'Key at line %d must be a string literal' % key.lineno
  4993. if not isinstance(value, ast.Dict):
  4994. return 'Value at line %d must be a dict' % value.lineno
  4995. if len(value.keys) != 1:
  4996. return 'Dict at line %d must have single entry' % value.lineno
  4997. if not isinstance(value.keys[0], ast.Str) or value.keys[0].s != 'filepath':
  4998. return (
  4999. 'Entry at line %d must have a string literal \'filepath\' as key' %
  5000. value.lineno)
  5001. return None
  5002. def _CheckWatchlistsEntrySyntax(key, value, ast, email_regex):
  5003. if not isinstance(key, ast.Str):
  5004. return 'Key at line %d must be a string literal' % key.lineno
  5005. if not isinstance(value, ast.List):
  5006. return 'Value at line %d must be a list' % value.lineno
  5007. for element in value.elts:
  5008. if not isinstance(element, ast.Str):
  5009. return 'Watchlist elements on line %d is not a string' % key.lineno
  5010. if not email_regex.match(element.s):
  5011. return ('Watchlist element on line %d doesn\'t look like a valid '
  5012. + 'email: %s') % (key.lineno, element.s)
  5013. return None
  5014. def _CheckWATCHLISTSEntries(wd_dict, w_dict, input_api):
  5015. mismatch_template = (
  5016. 'Mismatch between WATCHLIST_DEFINITIONS entry (%s) and WATCHLISTS '
  5017. 'entry (%s)')
  5018. email_regex = input_api.re.compile(
  5019. r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+$")
  5020. ast = input_api.ast
  5021. i = 0
  5022. last_key = ''
  5023. while True:
  5024. if i >= len(wd_dict.keys):
  5025. if i >= len(w_dict.keys):
  5026. return None
  5027. return mismatch_template % ('missing',
  5028. 'line %d' % w_dict.keys[i].lineno)
  5029. elif i >= len(w_dict.keys):
  5030. return (mismatch_template %
  5031. ('line %d' % wd_dict.keys[i].lineno, 'missing'))
  5032. wd_key = wd_dict.keys[i]
  5033. w_key = w_dict.keys[i]
  5034. result = _CheckWatchlistDefinitionsEntrySyntax(wd_key,
  5035. wd_dict.values[i], ast)
  5036. if result is not None:
  5037. return 'Bad entry in WATCHLIST_DEFINITIONS dict: %s' % result
  5038. result = _CheckWatchlistsEntrySyntax(w_key, w_dict.values[i], ast,
  5039. email_regex)
  5040. if result is not None:
  5041. return 'Bad entry in WATCHLISTS dict: %s' % result
  5042. if wd_key.s != w_key.s:
  5043. return mismatch_template % ('%s at line %d' %
  5044. (wd_key.s, wd_key.lineno),
  5045. '%s at line %d' %
  5046. (w_key.s, w_key.lineno))
  5047. if wd_key.s < last_key:
  5048. return (
  5049. 'WATCHLISTS dict is not sorted lexicographically at line %d and %d'
  5050. % (wd_key.lineno, w_key.lineno))
  5051. last_key = wd_key.s
  5052. i = i + 1
  5053. def _CheckWATCHLISTSSyntax(expression, input_api):
  5054. ast = input_api.ast
  5055. if not isinstance(expression, ast.Expression):
  5056. return 'WATCHLISTS file must contain a valid expression'
  5057. dictionary = expression.body
  5058. if not isinstance(dictionary, ast.Dict) or len(dictionary.keys) != 2:
  5059. return 'WATCHLISTS file must have single dict with exactly two entries'
  5060. first_key = dictionary.keys[0]
  5061. first_value = dictionary.values[0]
  5062. second_key = dictionary.keys[1]
  5063. second_value = dictionary.values[1]
  5064. if (not isinstance(first_key, ast.Str)
  5065. or first_key.s != 'WATCHLIST_DEFINITIONS'
  5066. or not isinstance(first_value, ast.Dict)):
  5067. return ('The first entry of the dict in WATCHLISTS file must be '
  5068. 'WATCHLIST_DEFINITIONS dict')
  5069. if (not isinstance(second_key, ast.Str) or second_key.s != 'WATCHLISTS'
  5070. or not isinstance(second_value, ast.Dict)):
  5071. return ('The second entry of the dict in WATCHLISTS file must be '
  5072. 'WATCHLISTS dict')
  5073. return _CheckWATCHLISTSEntries(first_value, second_value, input_api)
  5074. def CheckWATCHLISTS(input_api, output_api):
  5075. for f in input_api.AffectedFiles(include_deletes=False):
  5076. if f.LocalPath() == 'WATCHLISTS':
  5077. contents = input_api.ReadFile(f, 'r')
  5078. try:
  5079. # First, make sure that it can be evaluated.
  5080. input_api.ast.literal_eval(contents)
  5081. # Get an AST tree for it and scan the tree for detailed style checking.
  5082. expression = input_api.ast.parse(contents,
  5083. filename='WATCHLISTS',
  5084. mode='eval')
  5085. except ValueError as e:
  5086. return [
  5087. output_api.PresubmitError('Cannot parse WATCHLISTS file',
  5088. long_text=repr(e))
  5089. ]
  5090. except SyntaxError as e:
  5091. return [
  5092. output_api.PresubmitError('Cannot parse WATCHLISTS file',
  5093. long_text=repr(e))
  5094. ]
  5095. except TypeError as e:
  5096. return [
  5097. output_api.PresubmitError('Cannot parse WATCHLISTS file',
  5098. long_text=repr(e))
  5099. ]
  5100. result = _CheckWATCHLISTSSyntax(expression, input_api)
  5101. if result is not None:
  5102. return [output_api.PresubmitError(result)]
  5103. break
  5104. return []
  5105. def CheckGnRebasePath(input_api, output_api):
  5106. """Checks that target_gen_dir is not used with "//" in rebase_path().
  5107. Developers should use root_build_dir instead of "//" when using target_gen_dir because
  5108. Chromium is sometimes built outside of the source tree.
  5109. """
  5110. def gn_files(f):
  5111. return input_api.FilterSourceFile(f, files_to_check=(r'.+\.gn', ))
  5112. rebase_path_regex = input_api.re.compile(r'rebase_path\(("\$target_gen_dir"|target_gen_dir), ("/"|"//")\)')
  5113. problems = []
  5114. for f in input_api.AffectedSourceFiles(gn_files):
  5115. for line_num, line in f.ChangedContents():
  5116. if rebase_path_regex.search(line):
  5117. problems.append(
  5118. 'Absolute path in rebase_path() in %s:%d' %
  5119. (f.LocalPath(), line_num))
  5120. if problems:
  5121. return [
  5122. output_api.PresubmitPromptWarning(
  5123. 'Using an absolute path in rebase_path()',
  5124. items=sorted(problems),
  5125. long_text=(
  5126. 'rebase_path() should use root_build_dir instead of "/" ',
  5127. 'since builds can be initiated from outside of the source ',
  5128. 'root.'))
  5129. ]
  5130. return []
  5131. def CheckGnGlobForward(input_api, output_api):
  5132. """Checks that forward_variables_from(invoker, "*") follows best practices.
  5133. As documented at //build/docs/writing_gn_templates.md
  5134. """
  5135. def gn_files(f):
  5136. return input_api.FilterSourceFile(f, files_to_check=(r'.+\.gni', ))
  5137. problems = []
  5138. for f in input_api.AffectedSourceFiles(gn_files):
  5139. for line_num, line in f.ChangedContents():
  5140. if 'forward_variables_from(invoker, "*")' in line:
  5141. problems.append(
  5142. 'Bare forward_variables_from(invoker, "*") in %s:%d' %
  5143. (f.LocalPath(), line_num))
  5144. if problems:
  5145. return [
  5146. output_api.PresubmitPromptWarning(
  5147. 'forward_variables_from("*") without exclusions',
  5148. items=sorted(problems),
  5149. long_text=(
  5150. 'The variables "visibility" and "test_only" should be '
  5151. 'explicitly listed in forward_variables_from(). For more '
  5152. 'details, see:\n'
  5153. 'https://chromium.googlesource.com/chromium/src/+/HEAD/'
  5154. 'build/docs/writing_gn_templates.md'
  5155. '#Using-forward_variables_from'))
  5156. ]
  5157. return []
  5158. def CheckNewHeaderWithoutGnChangeOnUpload(input_api, output_api):
  5159. """Checks that newly added header files have corresponding GN changes.
  5160. Note that this is only a heuristic. To be precise, run script:
  5161. build/check_gn_headers.py.
  5162. """
  5163. def headers(f):
  5164. return input_api.FilterSourceFile(
  5165. f, files_to_check=(r'.+%s' % _HEADER_EXTENSIONS, ))
  5166. new_headers = []
  5167. for f in input_api.AffectedSourceFiles(headers):
  5168. if f.Action() != 'A':
  5169. continue
  5170. new_headers.append(f.LocalPath())
  5171. def gn_files(f):
  5172. return input_api.FilterSourceFile(f, files_to_check=(r'.+\.gn', ))
  5173. all_gn_changed_contents = ''
  5174. for f in input_api.AffectedSourceFiles(gn_files):
  5175. for _, line in f.ChangedContents():
  5176. all_gn_changed_contents += line
  5177. problems = []
  5178. for header in new_headers:
  5179. basename = input_api.os_path.basename(header)
  5180. if basename not in all_gn_changed_contents:
  5181. problems.append(header)
  5182. if problems:
  5183. return [
  5184. output_api.PresubmitPromptWarning(
  5185. 'Missing GN changes for new header files',
  5186. items=sorted(problems),
  5187. long_text=
  5188. 'Please double check whether newly added header files need '
  5189. 'corresponding changes in gn or gni files.\nThis checking is only a '
  5190. 'heuristic. Run build/check_gn_headers.py to be precise.\n'
  5191. 'Read https://crbug.com/661774 for more info.')
  5192. ]
  5193. return []
  5194. def CheckCorrectProductNameInMessages(input_api, output_api):
  5195. """Check that Chromium-branded strings don't include "Chrome" or vice versa.
  5196. This assumes we won't intentionally reference one product from the other
  5197. product.
  5198. """
  5199. all_problems = []
  5200. test_cases = [{
  5201. "filename_postfix": "google_chrome_strings.grd",
  5202. "correct_name": "Chrome",
  5203. "incorrect_name": "Chromium",
  5204. }, {
  5205. "filename_postfix": "google_chrome_strings.grd",
  5206. "correct_name": "Chrome",
  5207. "incorrect_name": "Chrome for Testing",
  5208. }, {
  5209. "filename_postfix": "chromium_strings.grd",
  5210. "correct_name": "Chromium",
  5211. "incorrect_name": "Chrome",
  5212. }]
  5213. for test_case in test_cases:
  5214. problems = []
  5215. filename_filter = lambda x: x.LocalPath().endswith(test_case[
  5216. "filename_postfix"])
  5217. # Check each new line. Can yield false positives in multiline comments, but
  5218. # easier than trying to parse the XML because messages can have nested
  5219. # children, and associating message elements with affected lines is hard.
  5220. for f in input_api.AffectedSourceFiles(filename_filter):
  5221. for line_num, line in f.ChangedContents():
  5222. if "<message" in line or "<!--" in line or "-->" in line:
  5223. continue
  5224. if test_case["incorrect_name"] in line:
  5225. # Chrome for Testing is a special edge case: https://goo.gle/chrome-for-testing#bookmark=id.n1rat320av91
  5226. if (test_case["correct_name"] == "Chromium" and line.count("Chrome") == line.count("Chrome for Testing")):
  5227. continue
  5228. problems.append("Incorrect product name in %s:%d" %
  5229. (f.LocalPath(), line_num))
  5230. if problems:
  5231. message = (
  5232. "Strings in %s-branded string files should reference \"%s\", not \"%s\""
  5233. % (test_case["correct_name"], test_case["correct_name"],
  5234. test_case["incorrect_name"]))
  5235. all_problems.append(
  5236. output_api.PresubmitPromptWarning(message, items=problems))
  5237. return all_problems
  5238. def CheckForTooLargeFiles(input_api, output_api):
  5239. """Avoid large files, especially binary files, in the repository since
  5240. git doesn't scale well for those. They will be in everyone's repo
  5241. clones forever, forever making Chromium slower to clone and work
  5242. with."""
  5243. # Uploading files to cloud storage is not trivial so we don't want
  5244. # to set the limit too low, but the upper limit for "normal" large
  5245. # files seems to be 1-2 MB, with a handful around 5-8 MB, so
  5246. # anything over 20 MB is exceptional.
  5247. TOO_LARGE_FILE_SIZE_LIMIT = 20 * 1024 * 1024
  5248. too_large_files = []
  5249. for f in input_api.AffectedFiles():
  5250. # Check both added and modified files (but not deleted files).
  5251. if f.Action() in ('A', 'M'):
  5252. size = input_api.os_path.getsize(f.AbsoluteLocalPath())
  5253. if size > TOO_LARGE_FILE_SIZE_LIMIT:
  5254. too_large_files.append("%s: %d bytes" % (f.LocalPath(), size))
  5255. if too_large_files:
  5256. message = (
  5257. 'Do not commit large files to git since git scales badly for those.\n'
  5258. +
  5259. 'Instead put the large files in cloud storage and use DEPS to\n' +
  5260. 'fetch them.\n' + '\n'.join(too_large_files))
  5261. return [
  5262. output_api.PresubmitError('Too large files found in commit',
  5263. long_text=message + '\n')
  5264. ]
  5265. else:
  5266. return []
  5267. def CheckFuzzTargetsOnUpload(input_api, output_api):
  5268. """Checks specific for fuzz target sources."""
  5269. EXPORTED_SYMBOLS = [
  5270. 'LLVMFuzzerInitialize',
  5271. 'LLVMFuzzerCustomMutator',
  5272. 'LLVMFuzzerCustomCrossOver',
  5273. 'LLVMFuzzerMutate',
  5274. ]
  5275. REQUIRED_HEADER = '#include "testing/libfuzzer/libfuzzer_exports.h"'
  5276. def FilterFile(affected_file):
  5277. """Ignore libFuzzer source code."""
  5278. files_to_check = r'.*fuzz.*\.(h|hpp|hcc|cc|cpp|cxx)$'
  5279. files_to_skip = r"^third_party/libFuzzer"
  5280. return input_api.FilterSourceFile(affected_file,
  5281. files_to_check=[files_to_check],
  5282. files_to_skip=[files_to_skip])
  5283. files_with_missing_header = []
  5284. for f in input_api.AffectedSourceFiles(FilterFile):
  5285. contents = input_api.ReadFile(f, 'r')
  5286. if REQUIRED_HEADER in contents:
  5287. continue
  5288. if any(symbol in contents for symbol in EXPORTED_SYMBOLS):
  5289. files_with_missing_header.append(f.LocalPath())
  5290. if not files_with_missing_header:
  5291. return []
  5292. long_text = (
  5293. 'If you define any of the libFuzzer optional functions (%s), it is '
  5294. 'recommended to add \'%s\' directive. Otherwise, the fuzz target may '
  5295. 'work incorrectly on Mac (crbug.com/687076).\nNote that '
  5296. 'LLVMFuzzerInitialize should not be used, unless your fuzz target needs '
  5297. 'to access command line arguments passed to the fuzzer. Instead, prefer '
  5298. 'static initialization and shared resources as documented in '
  5299. 'https://chromium.googlesource.com/chromium/src/+/main/testing/'
  5300. 'libfuzzer/efficient_fuzzing.md#simplifying-initialization_cleanup.\n'
  5301. % (', '.join(EXPORTED_SYMBOLS), REQUIRED_HEADER))
  5302. return [
  5303. output_api.PresubmitPromptWarning(message="Missing '%s' in:" %
  5304. REQUIRED_HEADER,
  5305. items=files_with_missing_header,
  5306. long_text=long_text)
  5307. ]
  5308. def _CheckNewImagesWarning(input_api, output_api):
  5309. """
  5310. Warns authors who add images into the repo to make sure their images are
  5311. optimized before committing.
  5312. """
  5313. images_added = False
  5314. image_paths = []
  5315. errors = []
  5316. filter_lambda = lambda x: input_api.FilterSourceFile(
  5317. x,
  5318. files_to_skip=(('(?i).*test', r'.*\/junit\/') + input_api.
  5319. DEFAULT_FILES_TO_SKIP),
  5320. files_to_check=[r'.*\/(drawable|mipmap)'])
  5321. for f in input_api.AffectedFiles(include_deletes=False,
  5322. file_filter=filter_lambda):
  5323. local_path = f.LocalPath().lower()
  5324. if any(
  5325. local_path.endswith(extension)
  5326. for extension in _IMAGE_EXTENSIONS):
  5327. images_added = True
  5328. image_paths.append(f)
  5329. if images_added:
  5330. errors.append(
  5331. output_api.PresubmitPromptWarning(
  5332. 'It looks like you are trying to commit some images. If these are '
  5333. 'non-test-only images, please make sure to read and apply the tips in '
  5334. 'https://chromium.googlesource.com/chromium/src/+/HEAD/docs/speed/'
  5335. 'binary_size/optimization_advice.md#optimizing-images\nThis check is '
  5336. 'FYI only and will not block your CL on the CQ.', image_paths))
  5337. return errors
  5338. def ChecksAndroidSpecificOnUpload(input_api, output_api):
  5339. """Groups upload checks that target android code."""
  5340. results = []
  5341. results.extend(_CheckAndroidCrLogUsage(input_api, output_api))
  5342. results.extend(_CheckAndroidDebuggableBuild(input_api, output_api))
  5343. results.extend(_CheckAndroidNewMdpiAssetLocation(input_api, output_api))
  5344. results.extend(_CheckAndroidToastUsage(input_api, output_api))
  5345. results.extend(_CheckAndroidTestAnnotationUsage(input_api, output_api))
  5346. results.extend(_CheckAndroidWebkitImports(input_api, output_api))
  5347. results.extend(_CheckAndroidXmlStyle(input_api, output_api, True))
  5348. results.extend(_CheckNewImagesWarning(input_api, output_api))
  5349. results.extend(_CheckAndroidNoBannedImports(input_api, output_api))
  5350. results.extend(_CheckAndroidInfoBarDeprecation(input_api, output_api))
  5351. return results
  5352. def ChecksAndroidSpecificOnCommit(input_api, output_api):
  5353. """Groups commit checks that target android code."""
  5354. results = []
  5355. results.extend(_CheckAndroidXmlStyle(input_api, output_api, False))
  5356. return results
  5357. # TODO(chrishall): could we additionally match on any path owned by
  5358. # ui/accessibility/OWNERS ?
  5359. _ACCESSIBILITY_PATHS = (
  5360. r"^chrome/browser.*/accessibility/",
  5361. r"^chrome/browser/extensions/api/automation.*/",
  5362. r"^chrome/renderer/extensions/accessibility_.*",
  5363. r"^chrome/tests/data/accessibility/",
  5364. r"^content/browser/accessibility/",
  5365. r"^content/renderer/accessibility/",
  5366. r"^content/tests/data/accessibility/",
  5367. r"^extensions/renderer/api/automation/",
  5368. r"^services/accessibility/",
  5369. r"^services/screen_ai/",
  5370. r"^ui/accessibility/",
  5371. r"^ui/views/accessibility/",
  5372. )
  5373. def CheckAccessibilityRelnotesField(input_api, output_api):
  5374. """Checks that commits to accessibility code contain an AX-Relnotes field in
  5375. their commit message."""
  5376. def FileFilter(affected_file):
  5377. paths = _ACCESSIBILITY_PATHS
  5378. return input_api.FilterSourceFile(affected_file, files_to_check=paths)
  5379. # Only consider changes affecting accessibility paths.
  5380. if not any(input_api.AffectedFiles(file_filter=FileFilter)):
  5381. return []
  5382. # AX-Relnotes can appear in either the description or the footer.
  5383. # When searching the description, require 'AX-Relnotes:' to appear at the
  5384. # beginning of a line.
  5385. ax_regex = input_api.re.compile('ax-relnotes[:=]')
  5386. description_has_relnotes = any(
  5387. ax_regex.match(line)
  5388. for line in input_api.change.DescriptionText().lower().splitlines())
  5389. footer_relnotes = input_api.change.GitFootersFromDescription().get(
  5390. 'AX-Relnotes', [])
  5391. if description_has_relnotes or footer_relnotes:
  5392. return []
  5393. # TODO(chrishall): link to Relnotes documentation in message.
  5394. message = (
  5395. "Missing 'AX-Relnotes:' field required for accessibility changes"
  5396. "\n please add 'AX-Relnotes: [release notes].' to describe any "
  5397. "user-facing changes"
  5398. "\n otherwise add 'AX-Relnotes: n/a.' if this change has no "
  5399. "user-facing effects"
  5400. "\n if this is confusing or annoying then please contact members "
  5401. "of ui/accessibility/OWNERS.")
  5402. return [output_api.PresubmitNotifyResult(message)]
  5403. _ACCESSIBILITY_ARIA_METHOD_CANDIDATES_PATTERNS = r'(\-\>|\.)(get|has|FastGet|FastHas)Attribute\('
  5404. _ACCESSIBILITY_ARIA_BAD_PARAMS_PATTERNS = (
  5405. r"\(html_names::kAria(.*)Attr\)",
  5406. r"\(html_names::kRoleAttr\)"
  5407. )
  5408. _ACCESSIBILITY_ARIA_FILE_CANDIDATES_PATTERNS = (
  5409. r".*/accessibility/.*.(cc|h)",
  5410. r".*/ax_.*.(cc|h)"
  5411. )
  5412. def CheckAccessibilityAriaElementAttributeGetters(input_api, output_api):
  5413. """Checks that the blink accessibility code follows the defined patterns
  5414. for checking aria attributes, so that ElementInternals is not bypassed."""
  5415. # Limit to accessibility-related files.
  5416. def FileFilter(affected_file):
  5417. paths = _ACCESSIBILITY_ARIA_FILE_CANDIDATES_PATTERNS
  5418. return input_api.FilterSourceFile(affected_file, files_to_check=paths)
  5419. aria_method_regex = input_api.re.compile(_ACCESSIBILITY_ARIA_METHOD_CANDIDATES_PATTERNS)
  5420. aria_bad_params_regex = input_api.re.compile(
  5421. "|".join(_ACCESSIBILITY_ARIA_BAD_PARAMS_PATTERNS)
  5422. )
  5423. problems = []
  5424. for f in input_api.AffectedSourceFiles(FileFilter):
  5425. for line_num, line in f.ChangedContents():
  5426. if aria_method_regex.search(line) and aria_bad_params_regex.search(line):
  5427. problems.append(f"{f.LocalPath()}:{line_num}\n {line.strip()}")
  5428. if problems:
  5429. return [
  5430. output_api.PresubmitPromptWarning(
  5431. "Accessibility code should not use element methods to get or check"
  5432. "\nthe presence of aria attributes"
  5433. "\nPlease use ARIA-specific attribute access, e.g. HasAriaAttribute(),"
  5434. "\nAriaTokenAttribute(), AriaBoolAttribute(), AriaBooleanAttribute(),"
  5435. "\nAriaFloatAttribute().",
  5436. problems,
  5437. )
  5438. ]
  5439. return []
  5440. # string pattern, sequence of strings to show when pattern matches,
  5441. # error flag. True if match is a presubmit error, otherwise it's a warning.
  5442. _NON_INCLUSIVE_TERMS = (
  5443. (
  5444. # Note that \b pattern in python re is pretty particular. In this
  5445. # regexp, 'class WhiteList ...' will match, but 'class FooWhiteList
  5446. # ...' will not. This may require some tweaking to catch these cases
  5447. # without triggering a lot of false positives. Leaving it naive and
  5448. # less matchy for now.
  5449. r'/(?i)\b((black|white)list|master|slave)\b', # nocheck
  5450. (
  5451. 'Please don\'t use blacklist, whitelist, ' # nocheck
  5452. 'or slave in your', # nocheck
  5453. 'code and make every effort to use other terms. Using "// nocheck"',
  5454. '"# nocheck" or "<!-- nocheck -->"',
  5455. 'at the end of the offending line will bypass this PRESUBMIT error',
  5456. 'but avoid using this whenever possible. Reach out to',
  5457. 'community@chromium.org if you have questions'),
  5458. True),)
  5459. def ChecksCommon(input_api, output_api):
  5460. """Checks common to both upload and commit."""
  5461. results = []
  5462. results.extend(
  5463. input_api.canned_checks.PanProjectChecks(
  5464. input_api, output_api, excluded_paths=_EXCLUDED_PATHS))
  5465. author = input_api.change.author_email
  5466. if author and author not in _KNOWN_ROBOTS:
  5467. results.extend(
  5468. input_api.canned_checks.CheckAuthorizedAuthor(
  5469. input_api, output_api))
  5470. results.extend(
  5471. input_api.canned_checks.CheckChangeHasNoTabs(
  5472. input_api,
  5473. output_api,
  5474. source_file_filter=lambda x: x.LocalPath().endswith('.grd')))
  5475. results.extend(
  5476. input_api.RunTests(
  5477. input_api.canned_checks.CheckVPythonSpec(input_api, output_api)))
  5478. dirmd = 'dirmd.bat' if input_api.is_windows else 'dirmd'
  5479. dirmd_bin = input_api.os_path.join(input_api.PresubmitLocalPath(),
  5480. 'third_party', 'depot_tools', dirmd)
  5481. results.extend(
  5482. input_api.RunTests(
  5483. input_api.canned_checks.CheckDirMetadataFormat(
  5484. input_api, output_api, dirmd_bin)))
  5485. results.extend(
  5486. input_api.canned_checks.CheckOwnersDirMetadataExclusive(
  5487. input_api, output_api))
  5488. results.extend(
  5489. input_api.canned_checks.CheckNoNewMetadataInOwners(
  5490. input_api, output_api))
  5491. results.extend(
  5492. input_api.canned_checks.CheckInclusiveLanguage(
  5493. input_api,
  5494. output_api,
  5495. excluded_directories_relative_path=[
  5496. 'infra', 'inclusive_language_presubmit_exempt_dirs.txt'
  5497. ],
  5498. non_inclusive_terms=_NON_INCLUSIVE_TERMS))
  5499. presubmit_py_filter = lambda f: input_api.FilterSourceFile(
  5500. f, files_to_check=[r'.*PRESUBMIT\.py$'])
  5501. for f in input_api.AffectedFiles(include_deletes=False,
  5502. file_filter=presubmit_py_filter):
  5503. full_path = input_api.os_path.dirname(f.AbsoluteLocalPath())
  5504. test_file = input_api.os_path.join(full_path, 'PRESUBMIT_test.py')
  5505. # The PRESUBMIT.py file (and the directory containing it) might have
  5506. # been affected by being moved or removed, so only try to run the tests
  5507. # if they still exist.
  5508. if not input_api.os_path.exists(test_file):
  5509. continue
  5510. results.extend(
  5511. input_api.canned_checks.RunUnitTestsInDirectory(
  5512. input_api,
  5513. output_api,
  5514. full_path,
  5515. files_to_check=[r'^PRESUBMIT_test\.py$']))
  5516. return results
  5517. def CheckPatchFiles(input_api, output_api):
  5518. problems = [
  5519. f.LocalPath() for f in input_api.AffectedFiles()
  5520. if f.LocalPath().endswith(('.orig', '.rej'))
  5521. ]
  5522. # Cargo.toml.orig files are part of third-party crates downloaded from
  5523. # crates.io and should be included.
  5524. problems = [f for f in problems if not f.endswith('Cargo.toml.orig')]
  5525. if problems:
  5526. return [
  5527. output_api.PresubmitError("Don't commit .rej and .orig files.",
  5528. problems)
  5529. ]
  5530. else:
  5531. return []
  5532. def CheckBuildConfigMacrosWithoutInclude(input_api, output_api):
  5533. # Excludes OS_CHROMEOS, which is not defined in build_config.h.
  5534. macro_re = input_api.re.compile(
  5535. r'^\s*#(el)?if.*\bdefined\(((COMPILER_|ARCH_CPU_|WCHAR_T_IS_)[^)]*)')
  5536. include_re = input_api.re.compile(r'^#include\s+"build/build_config.h"',
  5537. input_api.re.MULTILINE)
  5538. extension_re = input_api.re.compile(r'\.[a-z]+$')
  5539. errors = []
  5540. config_h_file = input_api.os_path.join('build', 'build_config.h')
  5541. for f in input_api.AffectedFiles(include_deletes=False):
  5542. # The build-config macros are allowed to be used in build_config.h
  5543. # without including itself.
  5544. if f.LocalPath() == config_h_file:
  5545. continue
  5546. if not f.LocalPath().endswith(
  5547. ('.h', '.c', '.cc', '.cpp', '.m', '.mm')):
  5548. continue
  5549. found_line_number = None
  5550. found_macro = None
  5551. all_lines = input_api.ReadFile(f, 'r').splitlines()
  5552. for line_num, line in enumerate(all_lines):
  5553. match = macro_re.search(line)
  5554. if match:
  5555. found_line_number = line_num
  5556. found_macro = match.group(2)
  5557. break
  5558. if not found_line_number:
  5559. continue
  5560. found_include_line = -1
  5561. for line_num, line in enumerate(all_lines):
  5562. if include_re.search(line):
  5563. found_include_line = line_num
  5564. break
  5565. if found_include_line >= 0 and found_include_line < found_line_number:
  5566. continue
  5567. if not f.LocalPath().endswith('.h'):
  5568. primary_header_path = extension_re.sub('.h', f.AbsoluteLocalPath())
  5569. try:
  5570. content = input_api.ReadFile(primary_header_path, 'r')
  5571. if include_re.search(content):
  5572. continue
  5573. except IOError:
  5574. pass
  5575. errors.append('%s:%d %s macro is used without first including build/'
  5576. 'build_config.h.' %
  5577. (f.LocalPath(), found_line_number, found_macro))
  5578. if errors:
  5579. return [output_api.PresubmitPromptWarning('\n'.join(errors))]
  5580. return []
  5581. def CheckForSuperfluousStlIncludesInHeaders(input_api, output_api):
  5582. stl_include_re = input_api.re.compile(r'^#include\s+<('
  5583. r'algorithm|'
  5584. r'array|'
  5585. r'limits|'
  5586. r'list|'
  5587. r'map|'
  5588. r'memory|'
  5589. r'queue|'
  5590. r'set|'
  5591. r'string|'
  5592. r'unordered_map|'
  5593. r'unordered_set|'
  5594. r'utility|'
  5595. r'vector)>')
  5596. std_namespace_re = input_api.re.compile(r'std::')
  5597. errors = []
  5598. for f in input_api.AffectedFiles():
  5599. if not _IsCPlusPlusHeaderFile(input_api, f.LocalPath()):
  5600. continue
  5601. uses_std_namespace = False
  5602. has_stl_include = False
  5603. for line in f.NewContents():
  5604. if has_stl_include and uses_std_namespace:
  5605. break
  5606. if not has_stl_include and stl_include_re.search(line):
  5607. has_stl_include = True
  5608. continue
  5609. if not uses_std_namespace and (std_namespace_re.search(line)
  5610. or 'no-std-usage-because-pch-file' in line):
  5611. uses_std_namespace = True
  5612. continue
  5613. if has_stl_include and not uses_std_namespace:
  5614. errors.append(
  5615. '%s: Includes STL header(s) but does not reference std::' %
  5616. f.LocalPath())
  5617. if errors:
  5618. return [output_api.PresubmitPromptWarning('\n'.join(errors))]
  5619. return []
  5620. def _CheckForDeprecatedOSMacrosInFile(input_api, f):
  5621. """Check for sensible looking, totally invalid OS macros."""
  5622. preprocessor_statement = input_api.re.compile(r'^\s*#')
  5623. os_macro = input_api.re.compile(r'defined\(OS_([^)]+)\)')
  5624. results = []
  5625. for lnum, line in f.ChangedContents():
  5626. if preprocessor_statement.search(line):
  5627. for match in os_macro.finditer(line):
  5628. results.append(
  5629. ' %s:%d: %s' %
  5630. (f.LocalPath(), lnum, 'defined(OS_' + match.group(1) +
  5631. ') -> BUILDFLAG(IS_' + match.group(1) + ')'))
  5632. return results
  5633. def CheckForDeprecatedOSMacros(input_api, output_api):
  5634. """Check all affected files for invalid OS macros."""
  5635. bad_macros = []
  5636. # The OS_ macros are allowed to be used in build/build_config.h.
  5637. config_h_file = input_api.os_path.join('build', 'build_config.h')
  5638. for f in input_api.AffectedSourceFiles(None):
  5639. if not f.LocalPath().endswith(('.py', '.js', '.html', '.css', '.md')) \
  5640. and f.LocalPath() != config_h_file:
  5641. bad_macros.extend(_CheckForDeprecatedOSMacrosInFile(input_api, f))
  5642. if not bad_macros:
  5643. return []
  5644. return [
  5645. output_api.PresubmitError(
  5646. 'OS macros have been deprecated. Please use BUILDFLAGs instead (still '
  5647. 'defined in build_config.h):', bad_macros)
  5648. ]
  5649. def _CheckForInvalidIfDefinedMacrosInFile(input_api, f):
  5650. """Check all affected files for invalid "if defined" macros."""
  5651. ALWAYS_DEFINED_MACROS = (
  5652. "TARGET_CPU_PPC",
  5653. "TARGET_CPU_PPC64",
  5654. "TARGET_CPU_68K",
  5655. "TARGET_CPU_X86",
  5656. "TARGET_CPU_ARM",
  5657. "TARGET_CPU_MIPS",
  5658. "TARGET_CPU_SPARC",
  5659. "TARGET_CPU_ALPHA",
  5660. "TARGET_IPHONE_SIMULATOR",
  5661. "TARGET_OS_EMBEDDED",
  5662. "TARGET_OS_IPHONE",
  5663. "TARGET_OS_MAC",
  5664. "TARGET_OS_UNIX",
  5665. "TARGET_OS_WIN32",
  5666. )
  5667. ifdef_macro = input_api.re.compile(
  5668. r'^\s*#.*(?:ifdef\s|defined\()([^\s\)]+)')
  5669. results = []
  5670. for lnum, line in f.ChangedContents():
  5671. for match in ifdef_macro.finditer(line):
  5672. if match.group(1) in ALWAYS_DEFINED_MACROS:
  5673. always_defined = ' %s is always defined. ' % match.group(1)
  5674. did_you_mean = 'Did you mean \'#if %s\'?' % match.group(1)
  5675. results.append(
  5676. ' %s:%d %s\n\t%s' %
  5677. (f.LocalPath(), lnum, always_defined, did_you_mean))
  5678. return results
  5679. def CheckForInvalidIfDefinedMacros(input_api, output_api):
  5680. """Check all affected files for invalid "if defined" macros."""
  5681. SKIPPED_PATHS = [
  5682. 'base/allocator/partition_allocator/src/partition_alloc/build_config.h',
  5683. 'build/build_config.h',
  5684. 'third_party/abseil-cpp/',
  5685. 'third_party/sqlite/',
  5686. ]
  5687. def affected_files_filter(f):
  5688. # Normalize the local path to Linux-style path separators so that the
  5689. # path comparisons work on Windows as well.
  5690. path = f.LocalPath().replace('\\', '/')
  5691. for skipped_path in SKIPPED_PATHS:
  5692. if path.startswith(skipped_path):
  5693. return False
  5694. return path.endswith(('.h', '.c', '.cc', '.m', '.mm'))
  5695. bad_macros = []
  5696. for f in input_api.AffectedSourceFiles(affected_files_filter):
  5697. bad_macros.extend(_CheckForInvalidIfDefinedMacrosInFile(input_api, f))
  5698. if not bad_macros:
  5699. return []
  5700. return [
  5701. output_api.PresubmitError(
  5702. 'Found ifdef check on always-defined macro[s]. Please fix your code\n'
  5703. 'or check the list of ALWAYS_DEFINED_MACROS in src/PRESUBMIT.py.',
  5704. bad_macros)
  5705. ]
  5706. def CheckForIPCRules(input_api, output_api):
  5707. """Check for same IPC rules described in
  5708. http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc
  5709. """
  5710. base_pattern = r'IPC_ENUM_TRAITS\('
  5711. inclusion_pattern = input_api.re.compile(r'(%s)' % base_pattern)
  5712. comment_pattern = input_api.re.compile(r'//.*(%s)' % base_pattern)
  5713. problems = []
  5714. for f in input_api.AffectedSourceFiles(None):
  5715. local_path = f.LocalPath()
  5716. if not local_path.endswith('.h'):
  5717. continue
  5718. for line_number, line in f.ChangedContents():
  5719. if inclusion_pattern.search(
  5720. line) and not comment_pattern.search(line):
  5721. problems.append('%s:%d\n %s' %
  5722. (local_path, line_number, line.strip()))
  5723. if problems:
  5724. return [
  5725. output_api.PresubmitPromptWarning(_IPC_ENUM_TRAITS_DEPRECATED,
  5726. problems)
  5727. ]
  5728. else:
  5729. return []
  5730. def CheckForLongPathnames(input_api, output_api):
  5731. """Check to make sure no files being submitted have long paths.
  5732. This causes issues on Windows.
  5733. """
  5734. problems = []
  5735. for f in input_api.AffectedTestableFiles():
  5736. local_path = f.LocalPath()
  5737. # Windows has a path limit of 260 characters. Limit path length to 200 so
  5738. # that we have some extra for the prefix on dev machines and the bots.
  5739. if (local_path.startswith('third_party/blink/web_tests/platform/') and
  5740. not local_path.startswith('third_party/blink/web_tests/platform/win')):
  5741. # Do not check length of the path for files not used by Windows
  5742. continue
  5743. if len(local_path) > 200:
  5744. problems.append(local_path)
  5745. if problems:
  5746. return [output_api.PresubmitError(_LONG_PATH_ERROR, problems)]
  5747. else:
  5748. return []
  5749. def CheckForIncludeGuards(input_api, output_api):
  5750. """Check that header files have proper guards against multiple inclusion.
  5751. If a file should not have such guards (and it probably should) then it
  5752. should include the string "no-include-guard-because-multiply-included" or
  5753. "no-include-guard-because-pch-file".
  5754. """
  5755. def is_chromium_header_file(f):
  5756. # We only check header files under the control of the Chromium
  5757. # project. This excludes:
  5758. # - third_party/*, except blink.
  5759. # - base/allocator/partition_allocator/: PartitionAlloc is a standalone
  5760. # library used outside of Chrome. Includes are referenced from its
  5761. # own base directory. It has its own `CheckForIncludeGuards`
  5762. # PRESUBMIT.py check.
  5763. # - *_message_generator.h: They use include guards in a special,
  5764. # non-typical way.
  5765. file_with_path = input_api.os_path.normpath(f.LocalPath())
  5766. return (file_with_path.endswith('.h')
  5767. and not file_with_path.endswith('_message_generator.h')
  5768. and not file_with_path.endswith('com_imported_mstscax.h')
  5769. and not file_with_path.startswith(
  5770. input_api.os_path.join('base', 'allocator',
  5771. 'partition_allocator'))
  5772. and (not file_with_path.startswith('third_party')
  5773. or file_with_path.startswith(
  5774. input_api.os_path.join('third_party', 'blink'))))
  5775. def replace_special_with_underscore(string):
  5776. return input_api.re.sub(r'[+\\/.-]', '_', string)
  5777. errors = []
  5778. for f in input_api.AffectedSourceFiles(is_chromium_header_file):
  5779. guard_name = None
  5780. guard_line_number = None
  5781. seen_guard_end = False
  5782. bypass_checks_at_end_of_file = False
  5783. file_with_path = input_api.os_path.normpath(f.LocalPath())
  5784. base_file_name = input_api.os_path.splitext(
  5785. input_api.os_path.basename(file_with_path))[0]
  5786. upper_base_file_name = base_file_name.upper()
  5787. expected_guard = replace_special_with_underscore(
  5788. file_with_path.upper() + '_')
  5789. # For "path/elem/file_name.h" we should really only accept
  5790. # PATH_ELEM_FILE_NAME_H_ per coding style. Unfortunately there
  5791. # are too many (1000+) files with slight deviations from the
  5792. # coding style. The most important part is that the include guard
  5793. # is there, and that it's unique, not the name so this check is
  5794. # forgiving for existing files.
  5795. #
  5796. # As code becomes more uniform, this could be made stricter.
  5797. guard_name_pattern_list = [
  5798. # Anything with the right suffix (maybe with an extra _).
  5799. r'\w+_H__?',
  5800. # To cover include guards with old Blink style.
  5801. r'\w+_h',
  5802. # Anything including the uppercase name of the file.
  5803. r'\w*' + input_api.re.escape(
  5804. replace_special_with_underscore(upper_base_file_name)) +
  5805. r'\w*',
  5806. ]
  5807. guard_name_pattern = '|'.join(guard_name_pattern_list)
  5808. guard_pattern = input_api.re.compile(r'#ifndef\s+(' +
  5809. guard_name_pattern + ')')
  5810. for line_number, line in enumerate(f.NewContents()):
  5811. if ('no-include-guard-because-multiply-included' in line
  5812. or 'no-include-guard-because-pch-file' in line):
  5813. bypass_checks_at_end_of_file = True
  5814. break
  5815. if guard_name is None:
  5816. match = guard_pattern.match(line)
  5817. if match:
  5818. guard_name = match.group(1)
  5819. guard_line_number = line_number
  5820. # We allow existing files to use include guards whose names
  5821. # don't match the chromium style guide, but new files should
  5822. # get it right.
  5823. if guard_name != expected_guard:
  5824. if f.Action() == 'A': # If file was just 'A'dded
  5825. errors.append(
  5826. output_api.PresubmitPromptWarning(
  5827. 'Header using the wrong include guard name %s'
  5828. % guard_name, [
  5829. '%s:%d' %
  5830. (f.LocalPath(), line_number + 1)
  5831. ], 'Expected: %r\nFound: %r' %
  5832. (expected_guard, guard_name)))
  5833. else:
  5834. # The line after #ifndef should have a #define of the same name.
  5835. if line_number == guard_line_number + 1:
  5836. expected_line = '#define %s' % guard_name
  5837. if line != expected_line:
  5838. errors.append(
  5839. output_api.PresubmitPromptWarning(
  5840. 'Missing "%s" for include guard' %
  5841. expected_line,
  5842. ['%s:%d' % (f.LocalPath(), line_number + 1)],
  5843. 'Expected: %r\nGot: %r' %
  5844. (expected_line, line)))
  5845. if not seen_guard_end and line == '#endif // %s' % guard_name:
  5846. seen_guard_end = True
  5847. elif seen_guard_end:
  5848. if line.strip() != '':
  5849. errors.append(
  5850. output_api.PresubmitPromptWarning(
  5851. 'Include guard %s not covering the whole file'
  5852. % (guard_name), [f.LocalPath()]))
  5853. break # Nothing else to check and enough to warn once.
  5854. if bypass_checks_at_end_of_file:
  5855. continue
  5856. if guard_name is None:
  5857. errors.append(
  5858. output_api.PresubmitPromptWarning(
  5859. 'Missing include guard in %s\n'
  5860. 'Recommended name: %s\n'
  5861. 'This check can be disabled by having the string\n'
  5862. '"no-include-guard-because-multiply-included" or\n'
  5863. '"no-include-guard-because-pch-file" in the header.'
  5864. % (f.LocalPath(), expected_guard)))
  5865. elif not seen_guard_end:
  5866. errors.append(
  5867. output_api.PresubmitPromptWarning(
  5868. 'Incorrect or missing include guard #endif in %s\n'
  5869. 'Recommended #endif comment: // %s'
  5870. % (f.LocalPath(), expected_guard)))
  5871. return errors
  5872. def CheckForWindowsLineEndings(input_api, output_api):
  5873. """Check source code and known ascii text files for Windows style line
  5874. endings.
  5875. """
  5876. known_text_files = r'.*\.(txt|html|htm|py|gyp|gypi|gn|isolate|icon)$'
  5877. file_inclusion_pattern = (known_text_files,
  5878. r'.+%s' % _IMPLEMENTATION_EXTENSIONS,
  5879. r'.+%s' % _HEADER_EXTENSIONS)
  5880. problems = []
  5881. source_file_filter = lambda f: input_api.FilterSourceFile(
  5882. f, files_to_check=file_inclusion_pattern, files_to_skip=None)
  5883. for f in input_api.AffectedSourceFiles(source_file_filter):
  5884. # Ignore test files that contain crlf intentionally.
  5885. if f.LocalPath().endswith('crlf.txt'):
  5886. continue
  5887. include_file = False
  5888. for line in input_api.ReadFile(f, 'r').splitlines(True):
  5889. if line.endswith('\r\n'):
  5890. include_file = True
  5891. if include_file:
  5892. problems.append(f.LocalPath())
  5893. if problems:
  5894. return [
  5895. output_api.PresubmitPromptWarning(
  5896. 'Are you sure that you want '
  5897. 'these files to contain Windows style line endings?\n' +
  5898. '\n'.join(problems))
  5899. ]
  5900. return []
  5901. def CheckIconFilesForLicenseHeaders(input_api, output_api):
  5902. """Check that .icon files (which are fragments of C++) have license headers.
  5903. """
  5904. icon_files = (r'.*\.icon$', )
  5905. icons = lambda x: input_api.FilterSourceFile(x, files_to_check=icon_files)
  5906. return input_api.canned_checks.CheckLicense(input_api,
  5907. output_api,
  5908. source_file_filter=icons)
  5909. def CheckForUseOfChromeAppsDeprecations(input_api, output_api):
  5910. """Check source code for use of Chrome App technologies being
  5911. deprecated.
  5912. """
  5913. def _CheckForDeprecatedTech(input_api,
  5914. output_api,
  5915. detection_list,
  5916. files_to_check=None,
  5917. files_to_skip=None):
  5918. if (files_to_check or files_to_skip):
  5919. source_file_filter = lambda f: input_api.FilterSourceFile(
  5920. f, files_to_check=files_to_check, files_to_skip=files_to_skip)
  5921. else:
  5922. source_file_filter = None
  5923. problems = []
  5924. for f in input_api.AffectedSourceFiles(source_file_filter):
  5925. if f.Action() == 'D':
  5926. continue
  5927. for _, line in f.ChangedContents():
  5928. if any(detect in line for detect in detection_list):
  5929. problems.append(f.LocalPath())
  5930. return problems
  5931. # to avoid this presubmit script triggering warnings
  5932. files_to_skip = ['PRESUBMIT.py', 'PRESUBMIT_test.py']
  5933. problems = []
  5934. # NMF: any files with extensions .nmf or NMF
  5935. _NMF_FILES = r'\.(nmf|NMF)$'
  5936. problems += _CheckForDeprecatedTech(
  5937. input_api,
  5938. output_api,
  5939. detection_list=[''], # any change to the file will trigger warning
  5940. files_to_check=[r'.+%s' % _NMF_FILES])
  5941. # MANIFEST: any manifest.json that in its diff includes "app":
  5942. _MANIFEST_FILES = r'(manifest\.json)$'
  5943. problems += _CheckForDeprecatedTech(
  5944. input_api,
  5945. output_api,
  5946. detection_list=['"app":'],
  5947. files_to_check=[r'.*%s' % _MANIFEST_FILES])
  5948. # NaCl / PNaCl: any file that in its diff contains the strings in the list
  5949. problems += _CheckForDeprecatedTech(
  5950. input_api,
  5951. output_api,
  5952. detection_list=['config=nacl', 'enable-nacl', 'cpu=pnacl', 'nacl_io'],
  5953. files_to_skip=files_to_skip + [r"^native_client_sdk/"])
  5954. # PPAPI: any C/C++ file that in its diff includes a ppapi library
  5955. problems += _CheckForDeprecatedTech(
  5956. input_api,
  5957. output_api,
  5958. detection_list=['#include "ppapi', '#include <ppapi'],
  5959. files_to_check=(r'.+%s' % _HEADER_EXTENSIONS,
  5960. r'.+%s' % _IMPLEMENTATION_EXTENSIONS),
  5961. files_to_skip=[r"^ppapi/"])
  5962. if problems:
  5963. return [
  5964. output_api.PresubmitPromptWarning(
  5965. 'You are adding/modifying code'
  5966. 'related to technologies which will soon be deprecated (Chrome Apps, NaCl,'
  5967. ' PNaCl, PPAPI). See this blog post for more details:\n'
  5968. 'https://blog.chromium.org/2020/08/changes-to-chrome-app-support-timeline.html\n'
  5969. 'and this documentation for options to replace these technologies:\n'
  5970. 'https://developer.chrome.com/docs/apps/migration/\n' +
  5971. '\n'.join(problems))
  5972. ]
  5973. return []
  5974. def CheckSyslogUseWarningOnUpload(input_api, output_api, src_file_filter=None):
  5975. """Checks that all source files use SYSLOG properly."""
  5976. syslog_files = []
  5977. for f in input_api.AffectedSourceFiles(src_file_filter):
  5978. for line_number, line in f.ChangedContents():
  5979. if 'SYSLOG' in line:
  5980. syslog_files.append(f.LocalPath() + ':' + str(line_number))
  5981. if syslog_files:
  5982. return [
  5983. output_api.PresubmitPromptWarning(
  5984. 'Please make sure there are no privacy sensitive bits of data in SYSLOG'
  5985. ' calls.\nFiles to check:\n',
  5986. items=syslog_files)
  5987. ]
  5988. return []
  5989. def CheckChangeOnUpload(input_api, output_api):
  5990. if input_api.version < [2, 0, 0]:
  5991. return [
  5992. output_api.PresubmitError(
  5993. "Your depot_tools is out of date. "
  5994. "This PRESUBMIT.py requires at least presubmit_support version 2.0.0, "
  5995. "but your version is %d.%d.%d" % tuple(input_api.version))
  5996. ]
  5997. results = []
  5998. results.extend(
  5999. input_api.canned_checks.CheckPatchFormatted(input_api, output_api))
  6000. return results
  6001. def CheckChangeOnCommit(input_api, output_api):
  6002. if input_api.version < [2, 0, 0]:
  6003. return [
  6004. output_api.PresubmitError(
  6005. "Your depot_tools is out of date. "
  6006. "This PRESUBMIT.py requires at least presubmit_support version 2.0.0, "
  6007. "but your version is %d.%d.%d" % tuple(input_api.version))
  6008. ]
  6009. results = []
  6010. # Make sure the tree is 'open'.
  6011. results.extend(
  6012. input_api.canned_checks.CheckTreeIsOpen(
  6013. input_api,
  6014. output_api,
  6015. json_url='http://chromium-status.appspot.com/current?format=json'))
  6016. results.extend(
  6017. input_api.canned_checks.CheckPatchFormatted(input_api, output_api))
  6018. results.extend(
  6019. input_api.canned_checks.CheckChangeHasBugField(input_api, output_api))
  6020. results.extend(
  6021. input_api.canned_checks.CheckChangeHasNoUnwantedTags(
  6022. input_api, output_api))
  6023. return results
  6024. def CheckStrings(input_api, output_api):
  6025. """Check string ICU syntax validity and if translation screenshots exist."""
  6026. # Skip translation screenshots check if a SkipTranslationScreenshotsCheck
  6027. # footer is set to true.
  6028. git_footers = input_api.change.GitFootersFromDescription()
  6029. skip_screenshot_check_footer = [
  6030. footer.lower() for footer in git_footers.get(
  6031. u'Skip-Translation-Screenshots-Check', [])
  6032. ]
  6033. run_screenshot_check = u'true' not in skip_screenshot_check_footer
  6034. import os
  6035. import re
  6036. import sys
  6037. from io import StringIO
  6038. new_or_added_paths = set(f.LocalPath() for f in input_api.AffectedFiles()
  6039. if (f.Action() == 'A' or f.Action() == 'M'))
  6040. removed_paths = set(f.LocalPath()
  6041. for f in input_api.AffectedFiles(include_deletes=True)
  6042. if f.Action() == 'D')
  6043. affected_grds = [
  6044. f for f in input_api.AffectedFiles()
  6045. if f.LocalPath().endswith(('.grd', '.grdp'))
  6046. ]
  6047. affected_grds = [
  6048. f for f in affected_grds if not 'testdata' in f.LocalPath()
  6049. ]
  6050. if not affected_grds:
  6051. return []
  6052. affected_png_paths = [
  6053. f.LocalPath() for f in input_api.AffectedFiles()
  6054. if f.LocalPath().endswith('.png')
  6055. ]
  6056. # Check for screenshots. Developers can upload screenshots using
  6057. # tools/translation/upload_screenshots.py which finds and uploads
  6058. # images associated with .grd files (e.g. test_grd/IDS_STRING.png for the
  6059. # message named IDS_STRING in test.grd) and produces a .sha1 file (e.g.
  6060. # test_grd/IDS_STRING.png.sha1) for each png when the upload is successful.
  6061. #
  6062. # The logic here is as follows:
  6063. #
  6064. # - If the CL has a .png file under the screenshots directory for a grd
  6065. # file, warn the developer. Actual images should never be checked into the
  6066. # Chrome repo.
  6067. #
  6068. # - If the CL contains modified or new messages in grd files and doesn't
  6069. # contain the corresponding .sha1 files, warn the developer to add images
  6070. # and upload them via tools/translation/upload_screenshots.py.
  6071. #
  6072. # - If the CL contains modified or new messages in grd files and the
  6073. # corresponding .sha1 files, everything looks good.
  6074. #
  6075. # - If the CL contains removed messages in grd files but the corresponding
  6076. # .sha1 files aren't removed, warn the developer to remove them.
  6077. unnecessary_screenshots = []
  6078. invalid_sha1 = []
  6079. missing_sha1 = []
  6080. missing_sha1_modified = []
  6081. unnecessary_sha1_files = []
  6082. # This checks verifies that the ICU syntax of messages this CL touched is
  6083. # valid, and reports any found syntax errors.
  6084. # Without this presubmit check, ICU syntax errors in Chromium strings can land
  6085. # without developers being aware of them. Later on, such ICU syntax errors
  6086. # break message extraction for translation, hence would block Chromium
  6087. # translations until they are fixed.
  6088. icu_syntax_errors = []
  6089. sha1_pattern = input_api.re.compile(r'^[a-fA-F0-9]{40}$',
  6090. input_api.re.MULTILINE)
  6091. def _CheckScreenshotAdded(screenshots_dir, message_id):
  6092. sha1_path = input_api.os_path.join(screenshots_dir,
  6093. message_id + '.png.sha1')
  6094. if sha1_path not in new_or_added_paths:
  6095. missing_sha1.append(sha1_path)
  6096. elif not _CheckValidSha1(sha1_path):
  6097. invalid_sha1.append(sha1_path)
  6098. def _CheckScreenshotModified(screenshots_dir, message_id):
  6099. sha1_path = input_api.os_path.join(screenshots_dir,
  6100. message_id + '.png.sha1')
  6101. if sha1_path not in new_or_added_paths:
  6102. missing_sha1_modified.append(sha1_path)
  6103. elif not _CheckValidSha1(sha1_path):
  6104. invalid_sha1.append(sha1_path)
  6105. def _CheckValidSha1(sha1_path):
  6106. return sha1_pattern.search(
  6107. next("\n".join(f.NewContents()) for f in input_api.AffectedFiles()
  6108. if f.LocalPath() == sha1_path))
  6109. def _CheckScreenshotRemoved(screenshots_dir, message_id):
  6110. sha1_path = input_api.os_path.join(screenshots_dir,
  6111. message_id + '.png.sha1')
  6112. if input_api.os_path.exists(
  6113. sha1_path) and sha1_path not in removed_paths:
  6114. unnecessary_sha1_files.append(sha1_path)
  6115. def _ValidateIcuSyntax(text, level, signatures):
  6116. """Validates ICU syntax of a text string.
  6117. Check if text looks similar to ICU and checks for ICU syntax correctness
  6118. in this case. Reports various issues with ICU syntax and values of
  6119. variants. Supports checking of nested messages. Accumulate information of
  6120. each ICU messages found in the text for further checking.
  6121. Args:
  6122. text: a string to check.
  6123. level: a number of current nesting level.
  6124. signatures: an accumulator, a list of tuple of (level, variable,
  6125. kind, variants).
  6126. Returns:
  6127. None if a string is not ICU or no issue detected.
  6128. A tuple of (message, start index, end index) if an issue detected.
  6129. """
  6130. valid_types = {
  6131. 'plural': (frozenset(
  6132. ['=0', '=1', '=2', '=3', 'zero', 'one', 'two', 'few', 'many',
  6133. 'other']), frozenset(['=1', 'other'])),
  6134. 'selectordinal': (frozenset(
  6135. ['=0', '=1', '=2', '=3', 'zero', 'one', 'two', 'few', 'many',
  6136. 'other']), frozenset(['one', 'other'])),
  6137. 'select': (frozenset(), frozenset(['other'])),
  6138. }
  6139. # Check if the message looks like an attempt to use ICU
  6140. # plural. If yes - check if its syntax strictly matches ICU format.
  6141. like = re.match(r'^[^{]*\{[^{]*\b(plural|selectordinal|select)\b',
  6142. text)
  6143. if not like:
  6144. signatures.append((level, None, None, None))
  6145. return
  6146. # Check for valid prefix and suffix
  6147. m = re.match(
  6148. r'^([^{]*\{)([a-zA-Z0-9_]+),\s*'
  6149. r'(plural|selectordinal|select),\s*'
  6150. r'(?:offset:\d+)?\s*(.*)', text, re.DOTALL)
  6151. if not m:
  6152. return (('This message looks like an ICU plural, '
  6153. 'but does not follow ICU syntax.'), like.start(),
  6154. like.end())
  6155. starting, variable, kind, variant_pairs = m.groups()
  6156. variants, depth, last_pos = _ParseIcuVariants(variant_pairs,
  6157. m.start(4))
  6158. if depth:
  6159. return ('Invalid ICU format. Unbalanced opening bracket', last_pos,
  6160. len(text))
  6161. first = text[0]
  6162. ending = text[last_pos:]
  6163. if not starting:
  6164. return ('Invalid ICU format. No initial opening bracket',
  6165. last_pos - 1, last_pos)
  6166. if not ending or '}' not in ending:
  6167. return ('Invalid ICU format. No final closing bracket',
  6168. last_pos - 1, last_pos)
  6169. elif first != '{':
  6170. return ((
  6171. 'Invalid ICU format. Extra characters at the start of a complex '
  6172. 'message (go/icu-message-migration): "%s"') % starting, 0,
  6173. len(starting))
  6174. elif ending != '}':
  6175. return ((
  6176. 'Invalid ICU format. Extra characters at the end of a complex '
  6177. 'message (go/icu-message-migration): "%s"') % ending,
  6178. last_pos - 1, len(text) - 1)
  6179. if kind not in valid_types:
  6180. return (('Unknown ICU message type %s. '
  6181. 'Valid types are: plural, select, selectordinal') % kind,
  6182. 0, 0)
  6183. known, required = valid_types[kind]
  6184. defined_variants = set()
  6185. for variant, variant_range, value, value_range in variants:
  6186. start, end = variant_range
  6187. if variant in defined_variants:
  6188. return ('Variant "%s" is defined more than once' % variant,
  6189. start, end)
  6190. elif known and variant not in known:
  6191. return ('Variant "%s" is not valid for %s message' %
  6192. (variant, kind), start, end)
  6193. defined_variants.add(variant)
  6194. # Check for nested structure
  6195. res = _ValidateIcuSyntax(value[1:-1], level + 1, signatures)
  6196. if res:
  6197. return (res[0], res[1] + value_range[0] + 1,
  6198. res[2] + value_range[0] + 1)
  6199. missing = required - defined_variants
  6200. if missing:
  6201. return ('Required variants missing: %s' % ', '.join(missing), 0,
  6202. len(text))
  6203. signatures.append((level, variable, kind, defined_variants))
  6204. def _ParseIcuVariants(text, offset=0):
  6205. """Parse variants part of ICU complex message.
  6206. Builds a tuple of variant names and values, as well as
  6207. their offsets in the input string.
  6208. Args:
  6209. text: a string to parse
  6210. offset: additional offset to add to positions in the text to get correct
  6211. position in the complete ICU string.
  6212. Returns:
  6213. List of tuples, each tuple consist of four fields: variant name,
  6214. variant name span (tuple of two integers), variant value, value
  6215. span (tuple of two integers).
  6216. """
  6217. depth, start, end = 0, -1, -1
  6218. variants = []
  6219. key = None
  6220. for idx, char in enumerate(text):
  6221. if char == '{':
  6222. if not depth:
  6223. start = idx
  6224. chunk = text[end + 1:start]
  6225. key = chunk.strip()
  6226. pos = offset + end + 1 + chunk.find(key)
  6227. span = (pos, pos + len(key))
  6228. depth += 1
  6229. elif char == '}':
  6230. if not depth:
  6231. return variants, depth, offset + idx
  6232. depth -= 1
  6233. if not depth:
  6234. end = idx
  6235. variants.append((key, span, text[start:end + 1],
  6236. (offset + start, offset + end + 1)))
  6237. return variants, depth, offset + end + 1
  6238. old_sys_path = sys.path
  6239. try:
  6240. sys.path = sys.path + [
  6241. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  6242. 'translation')
  6243. ]
  6244. from helper import grd_helper
  6245. finally:
  6246. sys.path = old_sys_path
  6247. for f in affected_grds:
  6248. file_path = f.LocalPath()
  6249. old_id_to_msg_map = {}
  6250. new_id_to_msg_map = {}
  6251. # Note that this code doesn't check if the file has been deleted. This is
  6252. # OK because it only uses the old and new file contents and doesn't load
  6253. # the file via its path.
  6254. # It's also possible that a file's content refers to a renamed or deleted
  6255. # file via a <part> tag, such as <part file="now-deleted-file.grdp">. This
  6256. # is OK as well, because grd_helper ignores <part> tags when loading .grd or
  6257. # .grdp files.
  6258. if file_path.endswith('.grdp'):
  6259. if f.OldContents():
  6260. old_id_to_msg_map = grd_helper.GetGrdpMessagesFromString(
  6261. '\n'.join(f.OldContents()))
  6262. if f.NewContents():
  6263. new_id_to_msg_map = grd_helper.GetGrdpMessagesFromString(
  6264. '\n'.join(f.NewContents()))
  6265. else:
  6266. file_dir = input_api.os_path.dirname(file_path) or '.'
  6267. if f.OldContents():
  6268. old_id_to_msg_map = grd_helper.GetGrdMessages(
  6269. StringIO('\n'.join(f.OldContents())), file_dir)
  6270. if f.NewContents():
  6271. new_id_to_msg_map = grd_helper.GetGrdMessages(
  6272. StringIO('\n'.join(f.NewContents())), file_dir)
  6273. grd_name, ext = input_api.os_path.splitext(
  6274. input_api.os_path.basename(file_path))
  6275. screenshots_dir = input_api.os_path.join(
  6276. input_api.os_path.dirname(file_path),
  6277. grd_name + ext.replace('.', '_'))
  6278. # Compute added, removed and modified message IDs.
  6279. old_ids = set(old_id_to_msg_map)
  6280. new_ids = set(new_id_to_msg_map)
  6281. added_ids = new_ids - old_ids
  6282. removed_ids = old_ids - new_ids
  6283. modified_ids = set([])
  6284. for key in old_ids.intersection(new_ids):
  6285. if (old_id_to_msg_map[key].ContentsAsXml('', True) !=
  6286. new_id_to_msg_map[key].ContentsAsXml('', True)):
  6287. # The message content itself changed. Require an updated screenshot.
  6288. modified_ids.add(key)
  6289. elif old_id_to_msg_map[key].attrs['meaning'] != \
  6290. new_id_to_msg_map[key].attrs['meaning']:
  6291. # The message meaning changed. We later check for a screenshot.
  6292. modified_ids.add(key)
  6293. if run_screenshot_check:
  6294. # Check the screenshot directory for .png files. Warn if there is any.
  6295. for png_path in affected_png_paths:
  6296. if png_path.startswith(screenshots_dir):
  6297. unnecessary_screenshots.append(png_path)
  6298. for added_id in added_ids:
  6299. _CheckScreenshotAdded(screenshots_dir, added_id)
  6300. for modified_id in modified_ids:
  6301. _CheckScreenshotModified(screenshots_dir, modified_id)
  6302. for removed_id in removed_ids:
  6303. _CheckScreenshotRemoved(screenshots_dir, removed_id)
  6304. # Check new and changed strings for ICU syntax errors.
  6305. for key in added_ids.union(modified_ids):
  6306. msg = new_id_to_msg_map[key].ContentsAsXml('', True)
  6307. err = _ValidateIcuSyntax(msg, 0, [])
  6308. if err is not None:
  6309. icu_syntax_errors.append(str(key) + ': ' + str(err[0]))
  6310. results = []
  6311. if run_screenshot_check:
  6312. if unnecessary_screenshots:
  6313. results.append(
  6314. output_api.PresubmitError(
  6315. 'Do not include actual screenshots in the changelist. Run '
  6316. 'tools/translate/upload_screenshots.py to upload them instead:',
  6317. sorted(unnecessary_screenshots)))
  6318. if missing_sha1:
  6319. results.append(
  6320. output_api.PresubmitError(
  6321. 'You are adding UI strings.\n'
  6322. 'To ensure the best translations, take screenshots of the relevant UI '
  6323. '(https://g.co/chrome/translation) and add these files to your '
  6324. 'changelist:', sorted(missing_sha1)))
  6325. if invalid_sha1:
  6326. results.append(
  6327. output_api.PresubmitError(
  6328. 'The following files do not seem to contain valid sha1 hashes. '
  6329. 'Make sure they contain hashes created by '
  6330. 'tools/translate/upload_screenshots.py:', sorted(invalid_sha1)))
  6331. if missing_sha1_modified:
  6332. results.append(
  6333. output_api.PresubmitError(
  6334. 'You are modifying UI strings or their meanings.\n'
  6335. 'To ensure the best translations, take screenshots of the relevant UI '
  6336. '(https://g.co/chrome/translation) and add these files to your '
  6337. 'changelist:', sorted(missing_sha1_modified)))
  6338. if unnecessary_sha1_files:
  6339. results.append(
  6340. output_api.PresubmitError(
  6341. 'You removed strings associated with these files. Remove:',
  6342. sorted(unnecessary_sha1_files)))
  6343. else:
  6344. results.append(
  6345. output_api.PresubmitPromptOrNotify('Skipping translation '
  6346. 'screenshots check.'))
  6347. if icu_syntax_errors:
  6348. results.append(
  6349. output_api.PresubmitPromptWarning(
  6350. 'ICU syntax errors were found in the following strings (problems or '
  6351. 'feedback? Contact rainhard@chromium.org):',
  6352. items=icu_syntax_errors))
  6353. return results
  6354. def CheckTranslationExpectations(input_api, output_api,
  6355. repo_root=None,
  6356. translation_expectations_path=None,
  6357. grd_files=None):
  6358. import sys
  6359. affected_grds = [
  6360. f for f in input_api.AffectedFiles()
  6361. if (f.LocalPath().endswith('.grd') or f.LocalPath().endswith('.grdp'))
  6362. ]
  6363. if not affected_grds:
  6364. return []
  6365. old_sys_path = sys.path
  6366. try:
  6367. sys.path = sys.path + [
  6368. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  6369. 'translation')
  6370. ]
  6371. sys.path = sys.path + [
  6372. input_api.os_path.join(input_api.PresubmitLocalPath(),
  6373. 'third_party', 'depot_tools')
  6374. ]
  6375. from helper import git_helper
  6376. from helper import translation_helper
  6377. import gclient_utils
  6378. finally:
  6379. sys.path = old_sys_path
  6380. # Check that translation expectations can be parsed and we can get a list of
  6381. # translatable grd files. |repo_root| and |translation_expectations_path| are
  6382. # only passed by tests.
  6383. if not repo_root:
  6384. repo_root = input_api.PresubmitLocalPath()
  6385. if not translation_expectations_path:
  6386. translation_expectations_path = input_api.os_path.join(
  6387. repo_root, 'tools', 'gritsettings', 'translation_expectations.pyl')
  6388. is_cog = gclient_utils.IsEnvCog()
  6389. # Git is not available in cog workspaces.
  6390. if not grd_files and not is_cog:
  6391. grd_files = git_helper.list_grds_in_repository(repo_root)
  6392. if not grd_files:
  6393. grd_files = []
  6394. # Ignore bogus grd files used only for testing
  6395. # ui/webui/resources/tools/generate_grd.py.
  6396. ignore_path = input_api.os_path.join('ui', 'webui', 'resources', 'tools',
  6397. 'tests')
  6398. grd_files = [p for p in grd_files if ignore_path not in p]
  6399. try:
  6400. translation_helper.get_translatable_grds(
  6401. repo_root, grd_files, translation_expectations_path, is_cog)
  6402. except Exception as e:
  6403. return [
  6404. output_api.PresubmitNotifyResult(
  6405. 'Failed to get a list of translatable grd files. This happens when:\n'
  6406. ' - One of the modified grd or grdp files cannot be parsed or\n'
  6407. ' - %s is not updated.\n'
  6408. 'Stack:\n%s' % (translation_expectations_path, str(e)))
  6409. ]
  6410. return []
  6411. def CheckStableMojomChanges(input_api, output_api):
  6412. """Changes to [Stable] mojom types must preserve backward-compatibility."""
  6413. changed_mojoms = input_api.AffectedFiles(
  6414. include_deletes=True,
  6415. file_filter=lambda f: f.LocalPath().endswith(('.mojom')))
  6416. if not changed_mojoms or input_api.no_diffs:
  6417. return []
  6418. delta = []
  6419. for mojom in changed_mojoms:
  6420. delta.append({
  6421. 'filename': mojom.LocalPath(),
  6422. 'old': '\n'.join(mojom.OldContents()) or None,
  6423. 'new': '\n'.join(mojom.NewContents()) or None,
  6424. })
  6425. process = input_api.subprocess.Popen([
  6426. input_api.python3_executable,
  6427. input_api.os_path.join(
  6428. input_api.PresubmitLocalPath(), 'mojo', 'public', 'tools', 'mojom',
  6429. 'check_stable_mojom_compatibility.py'), '--src-root',
  6430. input_api.PresubmitLocalPath()
  6431. ],
  6432. stdin=input_api.subprocess.PIPE,
  6433. stdout=input_api.subprocess.PIPE,
  6434. stderr=input_api.subprocess.PIPE,
  6435. universal_newlines=True)
  6436. (x, error) = process.communicate(input=input_api.json.dumps(delta))
  6437. if process.returncode:
  6438. return [
  6439. output_api.PresubmitError(
  6440. 'One or more [Stable] mojom definitions appears to have been changed '
  6441. 'in a way that is not backward-compatible. See '
  6442. 'https://chromium.googlesource.com/chromium/src/+/HEAD/mojo/public/tools/bindings/README.md#versioning'
  6443. ' for details.',
  6444. long_text=error)
  6445. ]
  6446. return []
  6447. def CheckDeprecationOfPreferences(input_api, output_api):
  6448. """Removing a preference should come with a deprecation."""
  6449. def FilterFile(affected_file):
  6450. """Accept only .cc files and the like."""
  6451. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  6452. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  6453. input_api.DEFAULT_FILES_TO_SKIP)
  6454. return input_api.FilterSourceFile(
  6455. affected_file,
  6456. files_to_check=file_inclusion_pattern,
  6457. files_to_skip=files_to_skip)
  6458. def ModifiedLines(affected_file):
  6459. """Returns a list of tuples (line number, line text) of added and removed
  6460. lines.
  6461. Deleted lines share the same line number as the previous line.
  6462. This relies on the scm diff output describing each changed code section
  6463. with a line of the form
  6464. ^@@ <old line num>,<old size> <new line num>,<new size> @@$
  6465. """
  6466. line_num = 0
  6467. modified_lines = []
  6468. for line in affected_file.GenerateScmDiff().splitlines():
  6469. # Extract <new line num> of the patch fragment (see format above).
  6470. m = input_api.re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@',
  6471. line)
  6472. if m:
  6473. line_num = int(m.groups(1)[0])
  6474. continue
  6475. if ((line.startswith('+') and not line.startswith('++'))
  6476. or (line.startswith('-') and not line.startswith('--'))):
  6477. modified_lines.append((line_num, line))
  6478. if not line.startswith('-'):
  6479. line_num += 1
  6480. return modified_lines
  6481. def FindLineWith(lines, needle):
  6482. """Returns the line number (i.e. index + 1) in `lines` containing `needle`.
  6483. If 0 or >1 lines contain `needle`, -1 is returned.
  6484. """
  6485. matching_line_numbers = [
  6486. # + 1 for 1-based counting of line numbers.
  6487. i + 1 for i, line in enumerate(lines) if needle in line
  6488. ]
  6489. return matching_line_numbers[0] if len(
  6490. matching_line_numbers) == 1 else -1
  6491. def ModifiedPrefMigration(affected_file):
  6492. """Returns whether the MigrateObsolete.*Pref functions were modified."""
  6493. # Determine first and last lines of MigrateObsolete.*Pref functions.
  6494. new_contents = affected_file.NewContents()
  6495. range_1 = (FindLineWith(new_contents,
  6496. 'BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS'),
  6497. FindLineWith(new_contents,
  6498. 'END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS'))
  6499. range_2 = (FindLineWith(new_contents,
  6500. 'BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS'),
  6501. FindLineWith(new_contents,
  6502. 'END_MIGRATE_OBSOLETE_PROFILE_PREFS'))
  6503. if (-1 in range_1 + range_2):
  6504. raise Exception(
  6505. 'Broken .*MIGRATE_OBSOLETE_.*_PREFS markers in browser_prefs.cc.'
  6506. )
  6507. # Check whether any of the modified lines are part of the
  6508. # MigrateObsolete.*Pref functions.
  6509. for line_nr, line in ModifiedLines(affected_file):
  6510. if (range_1[0] <= line_nr <= range_1[1]
  6511. or range_2[0] <= line_nr <= range_2[1]):
  6512. return True
  6513. return False
  6514. register_pref_pattern = input_api.re.compile(r'Register.+Pref')
  6515. browser_prefs_file_pattern = input_api.re.compile(
  6516. r'chrome/browser/prefs/browser_prefs.cc')
  6517. changes = input_api.AffectedFiles(include_deletes=True,
  6518. file_filter=FilterFile)
  6519. potential_problems = []
  6520. for f in changes:
  6521. for line in f.GenerateScmDiff().splitlines():
  6522. # Check deleted lines for pref registrations.
  6523. if (line.startswith('-') and not line.startswith('--')
  6524. and register_pref_pattern.search(line)):
  6525. potential_problems.append('%s: %s' % (f.LocalPath(), line))
  6526. if browser_prefs_file_pattern.search(f.LocalPath()):
  6527. # If the developer modified the MigrateObsolete.*Prefs() functions, we
  6528. # assume that they knew that they have to deprecate preferences and don't
  6529. # warn.
  6530. try:
  6531. if ModifiedPrefMigration(f):
  6532. return []
  6533. except Exception as e:
  6534. return [output_api.PresubmitError(str(e))]
  6535. if potential_problems:
  6536. return [
  6537. output_api.PresubmitPromptWarning(
  6538. 'Discovered possible removal of preference registrations.\n\n'
  6539. 'Please make sure to properly deprecate preferences by clearing their\n'
  6540. 'value for a couple of milestones before finally removing the code.\n'
  6541. 'Otherwise data may stay in the preferences files forever. See\n'
  6542. 'Migrate*Prefs() in chrome/browser/prefs/browser_prefs.cc and\n'
  6543. 'chrome/browser/prefs/README.md for examples.\n'
  6544. 'This may be a false positive warning (e.g. if you move preference\n'
  6545. 'registrations to a different place).\n', potential_problems)
  6546. ]
  6547. return []
  6548. def CheckConsistentGrdChanges(input_api, output_api):
  6549. """Changes to GRD files must be consistent for tools to read them."""
  6550. changed_grds = input_api.AffectedFiles(
  6551. include_deletes=False,
  6552. file_filter=lambda f: f.LocalPath().endswith(('.grd')))
  6553. errors = []
  6554. invalid_file_regexes = [(input_api.re.compile(matcher), msg)
  6555. for matcher, msg in _INVALID_GRD_FILE_LINE]
  6556. for grd in changed_grds:
  6557. for i, line in enumerate(grd.NewContents()):
  6558. for matcher, msg in invalid_file_regexes:
  6559. if matcher.search(line):
  6560. errors.append(
  6561. output_api.PresubmitError(
  6562. 'Problem on {grd}:{i} - {msg}'.format(
  6563. grd=grd.LocalPath(), i=i + 1, msg=msg)))
  6564. return errors
  6565. def CheckAssertAshOnlyCode(input_api, output_api):
  6566. """Errors if a BUILD.gn file in an ash/ directory doesn't include
  6567. assert(is_chromeos).
  6568. For a transition period, assert(is_chromeos_ash) is also accepted.
  6569. """
  6570. def FileFilter(affected_file):
  6571. """Includes directories known to be Ash only."""
  6572. return input_api.FilterSourceFile(
  6573. affected_file,
  6574. files_to_check=(
  6575. r'^ash/.*BUILD\.gn', # Top-level src/ash/.
  6576. r'.*/ash/.*BUILD\.gn'), # Any path component.
  6577. files_to_skip=(input_api.DEFAULT_FILES_TO_SKIP))
  6578. errors = []
  6579. pattern = input_api.re.compile(r'assert\(is_chromeos(_ash)?\b')
  6580. for f in input_api.AffectedFiles(include_deletes=False,
  6581. file_filter=FileFilter):
  6582. if (not pattern.search(input_api.ReadFile(f))):
  6583. errors.append(
  6584. output_api.PresubmitError(
  6585. 'Please add assert(is_chromeos) to %s. If that\'s not '
  6586. 'possible, please create an issue and add a comment such '
  6587. 'as:\n # TODO(crbug.com/XXX): add '
  6588. 'assert(is_chromeos) when ...' % f.LocalPath()))
  6589. return errors
  6590. def _IsMiraclePtrDisallowed(input_api, affected_file):
  6591. path = affected_file.LocalPath()
  6592. if not _IsCPlusPlusFile(input_api, path):
  6593. return False
  6594. # Renderer-only code is generally allowed to use MiraclePtr. These
  6595. # directories, however, are specifically disallowed, for perf reasons.
  6596. if ("third_party/blink/renderer/core/" in path
  6597. or "third_party/blink/renderer/platform/heap/" in path
  6598. or "third_party/blink/renderer/platform/wtf/" in path
  6599. or "third_party/blink/renderer/platform/fonts/" in path):
  6600. return True
  6601. # The below paths are an explicitly listed subset of Renderer-only code,
  6602. # because the plan is to Oilpanize it.
  6603. # TODO(crbug.com/330759291): Remove once Oilpanization is completed or
  6604. # abandoned.
  6605. if ("third_party/blink/renderer/core/paint/" in path
  6606. or "third_party/blink/renderer/platform/graphics/compositing/" in path
  6607. or "third_party/blink/renderer/platform/graphics/paint/" in path):
  6608. return True
  6609. # We assume that everything else may be used outside of Renderer processes.
  6610. return False
  6611. # TODO(crbug.com/40206238): Remove these checks, once they are replaced
  6612. # by the Chromium Clang Plugin (which will be preferable because it will
  6613. # 1) report errors earlier - at compile-time and 2) cover more rules).
  6614. def CheckRawPtrUsage(input_api, output_api):
  6615. """Rough checks that raw_ptr<T> usage guidelines are followed."""
  6616. errors = []
  6617. # The regex below matches "raw_ptr<" following a word boundary, but not in a
  6618. # C++ comment.
  6619. raw_ptr_matcher = input_api.re.compile(r'^((?!//).)*\braw_ptr<')
  6620. file_filter = lambda f: _IsMiraclePtrDisallowed(input_api, f)
  6621. for f, line_num, line in input_api.RightHandSideLines(file_filter):
  6622. if raw_ptr_matcher.search(line):
  6623. errors.append(
  6624. output_api.PresubmitError(
  6625. 'Problem on {path}:{line} - '\
  6626. 'raw_ptr<T> should not be used in this renderer code '\
  6627. '(as documented in the "Pointers to unprotected memory" '\
  6628. 'section in //base/memory/raw_ptr.md)'.format(
  6629. path=f.LocalPath(), line=line_num)))
  6630. return errors
  6631. def CheckAdvancedMemorySafetyChecksUsage(input_api, output_api):
  6632. """Checks that ADVANCED_MEMORY_SAFETY_CHECKS() macro is neither added nor
  6633. removed as it is managed by the memory safety team internally.
  6634. Do not add / remove it manually."""
  6635. paths = set([])
  6636. # The regex below matches "ADVANCED_MEMORY_SAFETY_CHECKS(" following a word
  6637. # boundary, but not in a C++ comment.
  6638. macro_matcher = input_api.re.compile(
  6639. r'^((?!//).)*\bADVANCED_MEMORY_SAFETY_CHECKS\(', input_api.re.MULTILINE)
  6640. for f in input_api.AffectedFiles():
  6641. if not _IsCPlusPlusFile(input_api, f.LocalPath()):
  6642. continue
  6643. if macro_matcher.search(f.GenerateScmDiff()):
  6644. paths.add(f.LocalPath())
  6645. if not paths:
  6646. return []
  6647. return [output_api.PresubmitPromptWarning(
  6648. 'ADVANCED_MEMORY_SAFETY_CHECKS() macro is managed by ' \
  6649. 'the memory safety team (chrome-memory-safety@). ' \
  6650. 'Please contact us to add/delete the uses of the macro.',
  6651. paths)]
  6652. def CheckPythonShebang(input_api, output_api):
  6653. """Checks that python scripts use #!/usr/bin/env instead of hardcoding a
  6654. system-wide python.
  6655. """
  6656. errors = []
  6657. sources = lambda affected_file: input_api.FilterSourceFile(
  6658. affected_file,
  6659. files_to_skip=((_THIRD_PARTY_EXCEPT_BLINK,
  6660. r'third_party/blink/web_tests/external/') + input_api.
  6661. DEFAULT_FILES_TO_SKIP),
  6662. files_to_check=[r'.*\.py$'])
  6663. for f in input_api.AffectedSourceFiles(sources):
  6664. for line_num, line in f.ChangedContents():
  6665. if line_num == 1 and line.startswith('#!/usr/bin/python'):
  6666. errors.append(f.LocalPath())
  6667. break
  6668. result = []
  6669. for file in errors:
  6670. result.append(
  6671. output_api.PresubmitError(
  6672. "Please use '#!/usr/bin/env python/2/3' as the shebang of %s" %
  6673. file))
  6674. return result
  6675. def CheckAndroidTestAnnotations(input_api, output_api):
  6676. """Checks that tests have either @Batch or @DoNotBatch annotation. If this
  6677. is not an instrumentation test, disregard."""
  6678. batch_annotation = input_api.re.compile(r'^\s*@Batch')
  6679. do_not_batch_annotation = input_api.re.compile(r'^\s*@DoNotBatch')
  6680. robolectric_test = input_api.re.compile(r'@RunWith\((.*?)RobolectricTestRunner')
  6681. test_class_declaration = input_api.re.compile(r'^\s*public\sclass.*Test')
  6682. uiautomator_test = input_api.re.compile(r'[uU]i[aA]utomator')
  6683. test_annotation_declaration = input_api.re.compile(r'^\s*public\s@interface\s.*{')
  6684. missing_annotation_errors = []
  6685. extra_annotation_errors = []
  6686. wrong_robolectric_test_runner_errors = []
  6687. def _FilterFile(affected_file):
  6688. return input_api.FilterSourceFile(
  6689. affected_file,
  6690. files_to_skip=input_api.DEFAULT_FILES_TO_SKIP,
  6691. files_to_check=[r'.*Test\.java$'])
  6692. for f in input_api.AffectedSourceFiles(_FilterFile):
  6693. batch_matched = None
  6694. do_not_batch_matched = None
  6695. is_instrumentation_test = True
  6696. test_annotation_declaration_matched = None
  6697. has_base_robolectric_rule = False
  6698. for line in f.NewContents():
  6699. if 'BaseRobolectricTestRule' in line:
  6700. has_base_robolectric_rule = True
  6701. continue
  6702. if m := robolectric_test.search(line):
  6703. is_instrumentation_test = False
  6704. if m.group(1) == '' and not has_base_robolectric_rule:
  6705. path = str(f.LocalPath())
  6706. # These two spots cannot use it.
  6707. if 'webapk' not in path and 'build' not in path:
  6708. wrong_robolectric_test_runner_errors.append(path)
  6709. break
  6710. if uiautomator_test.search(line):
  6711. is_instrumentation_test = False
  6712. break
  6713. if not batch_matched:
  6714. batch_matched = batch_annotation.search(line)
  6715. if not do_not_batch_matched:
  6716. do_not_batch_matched = do_not_batch_annotation.search(line)
  6717. test_class_declaration_matched = test_class_declaration.search(
  6718. line)
  6719. test_annotation_declaration_matched = test_annotation_declaration.search(line)
  6720. if test_class_declaration_matched or test_annotation_declaration_matched:
  6721. break
  6722. if test_annotation_declaration_matched:
  6723. continue
  6724. if (is_instrumentation_test and
  6725. not batch_matched and
  6726. not do_not_batch_matched):
  6727. missing_annotation_errors.append(str(f.LocalPath()))
  6728. if (not is_instrumentation_test and
  6729. (batch_matched or
  6730. do_not_batch_matched)):
  6731. extra_annotation_errors.append(str(f.LocalPath()))
  6732. results = []
  6733. if missing_annotation_errors:
  6734. results.append(
  6735. output_api.PresubmitPromptWarning(
  6736. """
  6737. A change was made to an on-device test that has neither been annotated with
  6738. @Batch nor @DoNotBatch. If this is a new test, please add the annotation. If
  6739. this is an existing test, please consider adding it if you are sufficiently
  6740. familiar with the test (but do so as a separate change).
  6741. See https://source.chromium.org/chromium/chromium/src/+/main:docs/testing/batching_instrumentation_tests.md
  6742. """, missing_annotation_errors))
  6743. if extra_annotation_errors:
  6744. results.append(
  6745. output_api.PresubmitPromptWarning(
  6746. """
  6747. Robolectric tests do not need a @Batch or @DoNotBatch annotations.
  6748. """, extra_annotation_errors))
  6749. if wrong_robolectric_test_runner_errors:
  6750. results.append(
  6751. output_api.PresubmitPromptWarning(
  6752. """
  6753. Robolectric tests should use either @RunWith(BaseRobolectricTestRunner.class) (or
  6754. a subclass of it), or use "@Rule BaseRobolectricTestRule".
  6755. """, wrong_robolectric_test_runner_errors))
  6756. return results
  6757. def CheckMockAnnotation(input_api, output_api):
  6758. """Checks that we have annotated all Mockito.mock()-ed or Mockito.spy()-ed
  6759. classes with @Mock or @Spy. If this is not an instrumentation test,
  6760. disregard."""
  6761. # This is just trying to be approximately correct. We are not writing a
  6762. # Java parser, so special cases like statically importing mock() then
  6763. # calling an unrelated non-mockito spy() function will cause a false
  6764. # positive.
  6765. package_name = input_api.re.compile(r'^package\s+(\w+(?:\.\w+)+);')
  6766. mock_static_import = input_api.re.compile(
  6767. r'^import\s+static\s+org.mockito.Mockito.(?:mock|spy);')
  6768. import_class = input_api.re.compile(r'import\s+((?:\w+\.)+)(\w+);')
  6769. mock_annotation = input_api.re.compile(r'^\s*@(?:Mock|Spy)')
  6770. field_type = input_api.re.compile(r'(\w+)(?:<\w+>)?\s+\w+\s*(?:;|=)')
  6771. mock_or_spy_function_call = r'(?:mock|spy)\(\s*(?:new\s*)?(\w+)(?:\.class|\()'
  6772. fully_qualified_mock_function = input_api.re.compile(
  6773. r'Mockito\.' + mock_or_spy_function_call)
  6774. statically_imported_mock_function = input_api.re.compile(
  6775. r'\W' + mock_or_spy_function_call)
  6776. robolectric_test = input_api.re.compile(r'[rR]obolectric')
  6777. uiautomator_test = input_api.re.compile(r'[uU]i[aA]utomator')
  6778. def _DoClassLookup(class_name, class_name_map, package):
  6779. found = class_name_map.get(class_name)
  6780. if found is not None:
  6781. return found
  6782. else:
  6783. return package + '.' + class_name
  6784. def _FilterFile(affected_file):
  6785. return input_api.FilterSourceFile(
  6786. affected_file,
  6787. files_to_skip=input_api.DEFAULT_FILES_TO_SKIP,
  6788. files_to_check=[r'.*Test\.java$'])
  6789. mocked_by_function_classes = set()
  6790. mocked_by_annotation_classes = set()
  6791. class_to_filename = {}
  6792. for f in input_api.AffectedSourceFiles(_FilterFile):
  6793. mock_function_regex = fully_qualified_mock_function
  6794. next_line_is_annotated = False
  6795. fully_qualified_class_map = {}
  6796. package = None
  6797. for line in f.NewContents():
  6798. if robolectric_test.search(line) or uiautomator_test.search(line):
  6799. # Skip Robolectric and UiAutomator tests.
  6800. break
  6801. m = package_name.search(line)
  6802. if m:
  6803. package = m.group(1)
  6804. continue
  6805. if mock_static_import.search(line):
  6806. mock_function_regex = statically_imported_mock_function
  6807. continue
  6808. m = import_class.search(line)
  6809. if m:
  6810. fully_qualified_class_map[m.group(2)] = m.group(1) + m.group(2)
  6811. continue
  6812. if next_line_is_annotated:
  6813. next_line_is_annotated = False
  6814. fully_qualified_class = _DoClassLookup(
  6815. field_type.search(line).group(1), fully_qualified_class_map,
  6816. package)
  6817. mocked_by_annotation_classes.add(fully_qualified_class)
  6818. continue
  6819. if mock_annotation.search(line):
  6820. field_type_search = field_type.search(line)
  6821. if field_type_search:
  6822. fully_qualified_class = _DoClassLookup(
  6823. field_type_search.group(1), fully_qualified_class_map,
  6824. package)
  6825. mocked_by_annotation_classes.add(fully_qualified_class)
  6826. else:
  6827. next_line_is_annotated = True
  6828. continue
  6829. m = mock_function_regex.search(line)
  6830. if m:
  6831. fully_qualified_class = _DoClassLookup(m.group(1),
  6832. fully_qualified_class_map, package)
  6833. # Skipping builtin classes, since they don't get optimized.
  6834. if fully_qualified_class.startswith(
  6835. 'android.') or fully_qualified_class.startswith(
  6836. 'java.'):
  6837. continue
  6838. class_to_filename[fully_qualified_class] = str(f.LocalPath())
  6839. mocked_by_function_classes.add(fully_qualified_class)
  6840. results = []
  6841. missed_classes = mocked_by_function_classes - mocked_by_annotation_classes
  6842. if missed_classes:
  6843. error_locations = []
  6844. for c in missed_classes:
  6845. error_locations.append(c + ' in ' + class_to_filename[c])
  6846. results.append(
  6847. output_api.PresubmitPromptWarning(
  6848. """
  6849. Mockito.mock()/spy() cause issues with our Java optimizer. You have 3 options:
  6850. 1) If the mocked variable can be a class member, annotate the member with
  6851. @Mock/@Spy.
  6852. 2) If the mocked variable cannot be a class member, create a dummy member
  6853. variable of that type, annotated with @Mock/@Spy. This dummy does not need
  6854. to be used or initialized in any way.
  6855. 3) If the mocked type is definitely not going to be optimized, whether it's a
  6856. builtin type which we don't ship, or a class you know R8 will treat
  6857. specially, you can ignore this warning.
  6858. """, error_locations))
  6859. return results
  6860. def CheckNoJsInIos(input_api, output_api):
  6861. """Checks to make sure that JavaScript files are not used on iOS."""
  6862. def _FilterFile(affected_file):
  6863. return input_api.FilterSourceFile(
  6864. affected_file,
  6865. files_to_skip=input_api.DEFAULT_FILES_TO_SKIP +
  6866. (r'^ios/third_party/*', r'^ios/tools/*', r'^third_party/*',
  6867. r'^components/autofill/ios/form_util/resources/*'),
  6868. files_to_check=[r'^ios/.*\.js$', r'.*/ios/.*\.js$'])
  6869. deleted_files = []
  6870. # Collect filenames of all removed JS files.
  6871. for f in input_api.AffectedFiles(file_filter=_FilterFile):
  6872. local_path = f.LocalPath()
  6873. if input_api.os_path.splitext(local_path)[1] == '.js' and f.Action() == 'D':
  6874. deleted_files.append(input_api.os_path.basename(local_path))
  6875. error_paths = []
  6876. moved_paths = []
  6877. warning_paths = []
  6878. for f in input_api.AffectedSourceFiles(_FilterFile):
  6879. local_path = f.LocalPath()
  6880. if input_api.os_path.splitext(local_path)[1] == '.js':
  6881. if f.Action() == 'A':
  6882. if input_api.os_path.basename(local_path) in deleted_files:
  6883. # This script was probably moved rather than newly created.
  6884. # Present a warning instead of an error for these cases.
  6885. moved_paths.append(local_path)
  6886. else:
  6887. error_paths.append(local_path)
  6888. elif f.Action() != 'D':
  6889. warning_paths.append(local_path)
  6890. results = []
  6891. if warning_paths:
  6892. results.append(output_api.PresubmitPromptWarning(
  6893. 'TypeScript is now fully supported for iOS feature scripts. '
  6894. 'Consider converting JavaScript files to TypeScript. See '
  6895. '//ios/web/public/js_messaging/README.md for more details.',
  6896. warning_paths))
  6897. if moved_paths:
  6898. results.append(output_api.PresubmitPromptWarning(
  6899. 'Do not use JavaScript on iOS for new files as TypeScript is '
  6900. 'fully supported. (If this is a moved file, you may leave the '
  6901. 'script unconverted.) See //ios/web/public/js_messaging/README.md '
  6902. 'for help using scripts on iOS.', moved_paths))
  6903. if error_paths:
  6904. results.append(output_api.PresubmitError(
  6905. 'Do not use JavaScript on iOS as TypeScript is fully supported. '
  6906. 'See //ios/web/public/js_messaging/README.md for help using '
  6907. 'scripts on iOS.', error_paths))
  6908. return results
  6909. def CheckLibcxxRevisionsMatch(input_api, output_api):
  6910. """Check to make sure the libc++ version matches across deps files."""
  6911. # Disable check for changes to sub-repositories.
  6912. if input_api.PresubmitLocalPath() != input_api.change.RepositoryRoot():
  6913. return []
  6914. DEPS_FILES = [ 'DEPS', 'buildtools/deps_revisions.gni' ]
  6915. file_filter = lambda f: f.LocalPath().replace(
  6916. input_api.os_path.sep, '/') in DEPS_FILES
  6917. changed_deps_files = input_api.AffectedFiles(file_filter=file_filter)
  6918. if not changed_deps_files:
  6919. return []
  6920. def LibcxxRevision(file):
  6921. file = input_api.os_path.join(input_api.PresubmitLocalPath(),
  6922. *file.split('/'))
  6923. return input_api.re.search(
  6924. r'libcxx_revision.*[:=].*[\'"](\w+)[\'"]',
  6925. input_api.ReadFile(file)).group(1)
  6926. if len(set([LibcxxRevision(f) for f in DEPS_FILES])) == 1:
  6927. return []
  6928. return [output_api.PresubmitError(
  6929. 'libcxx_revision not equal across %s' % ', '.join(DEPS_FILES),
  6930. changed_deps_files)]
  6931. def CheckDanglingUntriaged(input_api, output_api):
  6932. """Warn developers adding DanglingUntriaged raw_ptr."""
  6933. # Ignore during git presubmit --all.
  6934. #
  6935. # This would be too costly, because this would check every lines of every
  6936. # C++ files. Check from _BANNED_CPP_FUNCTIONS are also reading the whole
  6937. # source code, but only once to apply every checks. It seems the bots like
  6938. # `win-presubmit` are particularly sensitive to reading the files. Adding
  6939. # this check caused the bot to run 2x longer. See https://crbug.com/1486612.
  6940. if input_api.no_diffs:
  6941. return []
  6942. def FilterFile(file):
  6943. return input_api.FilterSourceFile(
  6944. file,
  6945. files_to_check=[r".*\.(h|cc|cpp|cxx|m|mm)$"],
  6946. files_to_skip=[r"^base/allocator.*"],
  6947. )
  6948. count = 0
  6949. for f in input_api.AffectedFiles(file_filter=FilterFile):
  6950. count -= sum([l.count("DanglingUntriaged") for l in f.OldContents()])
  6951. count += sum([l.count("DanglingUntriaged") for l in f.NewContents()])
  6952. # Most likely, nothing changed:
  6953. if count == 0:
  6954. return []
  6955. # Congrats developers for improving it:
  6956. if count < 0:
  6957. message = f"DanglingUntriaged pointers removed: {-count}\nThank you!"
  6958. return [output_api.PresubmitNotifyResult(message)]
  6959. # Check for 'DanglingUntriaged-notes' in the description:
  6960. notes_regex = input_api.re.compile("DanglingUntriaged-notes[:=]")
  6961. if any(
  6962. notes_regex.match(line)
  6963. for line in input_api.change.DescriptionText().splitlines()):
  6964. return []
  6965. # Check for DanglingUntriaged-notes in the git footer:
  6966. if input_api.change.GitFootersFromDescription().get(
  6967. "DanglingUntriaged-notes", []):
  6968. return []
  6969. message = (
  6970. "Unexpected new occurrences of `DanglingUntriaged` detected. Please\n" +
  6971. "avoid adding new ones\n" +
  6972. "\n" +
  6973. "See documentation:\n" +
  6974. "https://chromium.googlesource.com/chromium/src/+/main/docs/dangling_ptr.md\n" +
  6975. "\n" +
  6976. "See also the guide to fix dangling pointers:\n" +
  6977. "https://chromium.googlesource.com/chromium/src/+/main/docs/dangling_ptr_guide.md\n" +
  6978. "\n" +
  6979. "To disable this warning, please add in the commit description:\n" +
  6980. "DanglingUntriaged-notes: <rationale for new untriaged dangling " +
  6981. "pointers>"
  6982. )
  6983. return [output_api.PresubmitPromptWarning(message)]
  6984. def CheckInlineConstexprDefinitionsInHeaders(input_api, output_api):
  6985. """Checks that non-static constexpr definitions in headers are inline."""
  6986. # In a properly formatted file, constexpr definitions inside classes or
  6987. # structs will have additional whitespace at the beginning of the line.
  6988. # The pattern looks for variables initialized as constexpr kVar = ...; or
  6989. # constexpr kVar{...};
  6990. # The pattern does not match expressions that have braces in kVar to avoid
  6991. # matching constexpr functions.
  6992. pattern = input_api.re.compile(r'^constexpr (?!inline )[^\(\)]*[={]')
  6993. attribute_pattern = input_api.re.compile(r'(\[\[[a-zA-Z_:]+\]\]|[A-Z]+[A-Z_]+) ')
  6994. problems = []
  6995. for f in input_api.AffectedFiles():
  6996. if not _IsCPlusPlusHeaderFile(input_api, f.LocalPath()):
  6997. continue
  6998. for line_number, line in f.ChangedContents():
  6999. line = attribute_pattern.sub('', line)
  7000. if pattern.search(line):
  7001. problems.append(
  7002. f"{f.LocalPath()}: {line_number}\n {line}")
  7003. if problems:
  7004. return [
  7005. output_api.PresubmitPromptWarning(
  7006. 'Consider inlining constexpr variable definitions in headers '
  7007. 'outside of classes to avoid unnecessary copies of the '
  7008. 'constant. See https://abseil.io/tips/168 for more details.',
  7009. problems)
  7010. ]
  7011. else:
  7012. return []
  7013. def CheckTodoBugReferences(input_api, output_api):
  7014. """Checks that bugs in TODOs use updated issue tracker IDs."""
  7015. files_to_skip = ['PRESUBMIT_test.py', r"^third_party/rust/chromium_crates_io/vendor/.*"]
  7016. def _FilterFile(affected_file):
  7017. return input_api.FilterSourceFile(
  7018. affected_file,
  7019. files_to_skip=files_to_skip)
  7020. # Monorail bug IDs are all less than or equal to 1524553 so check that all
  7021. # bugs in TODOs are greater than that value.
  7022. pattern = input_api.re.compile(r'.*TODO\([^\)0-9]*([0-9]+)\).*')
  7023. problems = []
  7024. for f in input_api.AffectedSourceFiles(_FilterFile):
  7025. for line_number, line in f.ChangedContents():
  7026. match = pattern.match(line)
  7027. if match and int(match.group(1)) <= 1524553:
  7028. problems.append(
  7029. f"{f.LocalPath()}: {line_number}\n {line}")
  7030. if problems:
  7031. return [
  7032. output_api.PresubmitPromptWarning(
  7033. 'TODOs should use the new Chromium Issue Tracker IDs which can '
  7034. 'be found by navigating to the bug. See '
  7035. 'https://crbug.com/336778624 for more details.',
  7036. problems)
  7037. ]
  7038. else:
  7039. return []