text
stringlengths
64
2.99M
o eu nt d_ :f PP * *r EE h de MM e ae __ a tFF d a: RR e EE r =EE N( = ( U* * LNh d LUe aLa t ;Ld ae ; ,r f, Dl oaf g ul sa bg , les , 0 fr ) e0 ; e); i f c a hn u o p at le l d p nyn e e d ad . a l is nHe rs s gd oe . tw .u s o .ss e h e vt ah, e vei rt e, i s t s h pa e rd f oe if c ptf y oi ec d rou ef elt t rt h ro ois r s w H sn oi oti mhp wop eeue v gtt e emh r n,a o eIs r rc e av a lu c n gl o n p une r it dor ea avxb nit d.i cl ei eti e fs o r v b pu i al tl i cn ti he e )r sa tb a ol ne d fis xpo rf o tt hw v eia dr vee ua la nn m ea rol ay d bz i ie fi lic tt iah ete sio .r n Too o ht n enc ta h tu e hs ee so do u ef r vct eeh loe c pov edu re sln ( we i.r e ia l.- l, EVP_ENCODE_CTX_free(ctx); assessing the security of PEM_FREE(name, flags, 0); It is worth noting that there is a the code … release the fixed version and The users of the software can BIO_free(headerB); potential for buffer overflow … BIO_free(dataB); thenapplythepatchorupdatethesoftwaretoasafeversion. return ret; … Figure 5: One false negative of ChatGPT’s vulnerability However, this process requires significant expert knowledge detection on real-world vulnerability (CVE-2022-4450). and is time-consuming. Automatic vulnerability repair [69], [70], [71], [72], [73] is proposed to achieve timely fix of 190) among all tested vulnerabilities, as shown in table 1. vulnerabilitywithaminimumofhumaneffort.Conventional Detecting vulnerabilities in real software projects. methods of vulnerability repair rely on manually defined Ideally, vulnerability detection is going to be involved in rules or evolutionary search of patches, which are limited the development of real complex software projects, which in flexibility and scale. is more challenging as these projects often involves context As vulnerability repair aims to generate safe code given non-trivial to understand and complicated dependencies of the vulnerable code, it is basically a language generation librariesormodules.ItiscriticaltostudywhetherChatGPT task based on prior knowledge, which is a suitable use case can end-to-end address real-world vulnerabilities. for LLMs like ChatGPT. Recent studies analyze vulnera- Theresultsareshowninthetable2.Precisionandrecall bility repair using LLMs and provide preliminary results. drop significantly compared with the results on synthetic Pearce et al. [32] manually crafts prompts to perform vul- programs(table1),whichindicatestheadditionalchallenges nerabilityrepairandtestedmultipleLLMs(butnotincluding on detecting vulnerabilities on complex software instead of ChatGPT). Their analysis revealed that LLM-based code shortprograms.Especially,ChatGPTwithGPT-3.5isalmost repair can deliver comparable performance to conventional unusable as it produces only 41.67% precision and 17.42% methods, but its stability is limited by various factors, such recall. Results from GPT-4 is better (73.91% precision and as the nature of the vulnerabilities and the quality of the 50% recall) but it still suffers from a high number of false promptsused.Basedontheexistingstudies,weanalyzethe positives and false negatives. We analyze the failing cases capability of vulnerability repair with ChatGPT to provide as follows. a comprehensive analysis of its strengths and limitations. Nondeterministic results. ChatGPT may produce nonde- Datasets. We set two different test datasets, following terministic results saying that the code is over-complicated the same methodology in section 3. The test cases include or incomplete to analyze, labeled as “failed” in table 2. As the synthetic test cases from SARD and Juliet [74] and 2) shown in fig. 4, when we ask ChatGPT with GPT-3.5 to therealCVEvulnerabilitiesinopen-sourcesoftware.Forthe examine the vulnerable function (a SQL injection vulner- syntheticdataset,wechoose18CWEsfromMITRE’s“2021 ability), it complains that the code is incomplete, which CWETop25”listfollowing[31]andcompile154testcases is likely caused by undefined identifiers and undeclared in total. For real-world vulnerabilities, we collect recent dependencies. However, it is extremely hard to extract a CVEs (starting from September 2019) on OpenSSL [75] as standalone piece of code from a real project with com- the test data. plex dependencies. On contrast, ChatGPT with GPT-4 still Prompts. We use the most basic prompt, a straight- succeed in detecting the vulnerability in this case. Though forward question “Can you fix the vulnerabilities in the the complicated code dependencies are causing failures, the following code?”. success of GPT-4 indicates the potential of ChatGPT to Metrics. We manually validate repairs generated by process incomplete code. ChatGPT. One repair is successful if the vulnerability is False negatives. Compared with vulnerability detection no longer exploitable. We calculate the success rate of on short synthetic programs, the detection on real software vulnerability repair as the evaluation metric. projects suffers more significantly from false negatives. We Repairing vulnerabilities in synthetic programs. We hypothesize that it is because the complex code logic ob- introduce the overall results presented in table 3. GPT-3.5 scures the pattern of the vulnerabilities. For example, as successfully repairs 119 out of 154 (77.27%) test casesTABLE 3: Vulnerability fix on CWEs.
TABLE 4: Vulnerability fix on CVEs. CWEID GPT-4 GPT-3.5 CWE-20 3/3 3/3 ID Vulnerability GP √T-4 GP √T-3.5 CWE-22 13/13 8/13 CVE-2023-0216 NULLdereferencetriggeredbymalformedPKCS7. √ C CW WE E- -7 78 9 1 13 1/ /1 13 3 1 11 0/ /1 13 3 CVE-2023-0401 NULLdereferencetriggeredbywronglydigestedPKCS7. √× √ CWE-89 13/13 11/13 CVE-2023-0217 NULLdereferenceinBN copy. √ CWE-119 13/13 13/13 CVE-2022-4450 Doublefreeon*headerand*datainPEM read bio ex(). × CWE-125 12/13 10/13 CVE-2022-3996 Redundantlockoperationinx509. × × CWE-190 10/13 10/13 CWE-200 0/3 0/3 CVE-2022-3602 Potentialbufferoverflowinossl a2ulabel(). × × CWE-306 2/3 0/3 CVE-2022-3358 NULLdereferenceinEVP CIPHER. × × CWE-416 12/13 11/13 CVE-2022-29242 PotentialbufferoverflowinGOSTkeyexchange. × × CWE-434 2/3 3/3 CWE-476 12/13 13/13 CVE-2022-1434 WrongcryptoinRC4-MD5. × × CWE-502 3/3 3/3 CVE-2022-1343 ImproperOCSP basic verifysignercertificatevalidation. × × CWE-522 3/3 1/3 CVE-2022-0778 PossibleinfiniteloopinBN mod sqrt(). × × CWE-732 3/3 2/3 CWE-787 12/13 9/13 CVE-2021-4044 PossibleinfiniteloopinX509 verify(). × × CWE-798 2/3 1/3 Total 3/12 3/12 Total 139/154 119/154 Prompt GPT-3.5 GPT-4 Prompt GPT-3.5 Can you fix the vulnerabilities in the …………… …………… f @ d p o a e a l p f s lo ip u p s w l f. s a w or e s o in igo r s r isiu n w d g f_nt a o ) c ( ve m r : o ( ) iae d ' rd : sl / e_i= =e l tvd ? o ua_r rg rlue ei nisq q n deu u "' _re e, Lpns s oaat tm gsm. .e isef ft nw(o oh our ro Srsm md ude[ [' 's c(r= u p cun[ s a esa' e s semP r s sreO n w fn)S a o ua:T m r lm' e d "e] ' ' ,] ] ) u g s e e t # i … i … r h _ f f n a h… … V a s an na m h s… …r ro ol e e he et ti " d e… … t td _ du iu ua p _… …s sr rt a pe _n ne s a r v s s" "n ai w sI La ln o wn om ip r ov ge du d rEa i _t do l nus = (x r i s up d Fe son ar eso i in ret n la nd p em a p u de mia t ( ens " -u )fos srw uemo nrr knad nat: omio wen n) : t N c o pr o r r ay n e s e d n s: e o w… i : i n t of f… t r i du in… a )s soa l :e _tb… sr vo … "n ar i)a lt sm i_(e dv4 _a0 pl0i ai,s sdd s_eN wuso oscn rere dri (npo uatr smi eeop r(na nu=s as"s meMw erio ,nsr asd mi eni )gs C p t s u a o a b r u n l g r pi e c u y c t e }b io l f ) .i c r l e ru c {l ( e e l e f a t n s t six s u g e uoss r t rut t n h nra ih ct fL ( e eiE )s 1 cV ;o (. b E u + i su N r s oig S cE un lH em rt es T p c v . i E t e el in I y ne s . N sv E( cth he m) h tn p a{e es t| r f ih y| Ao nt t(l e )t ( (lo i a 0 sw n r o? )g u ( i e r=S tn t c=t ag e r r. i gi t .c n es a so g tE r ud m g b .e p e ss l? t t to ey ru n . ir g( c nc t) h ge h) a r, ( ({ A ) 1t S )t ,: (r 0 i )n )g { p t u a } }pb r u pl gb u. S S Si el b. t t yc ti l. r r sc i i i t ) c n n e c Ag g m{l s a t s . ds a t s s o ds t a 1 2 u ei t t B dc i = =L .c E p o aV ri " "dE in k sv myN nt i io S tt ti o aH lt tdl f iT ne ie n tE n nv m ( hI " ge a l fueN "n i e; n s n v ;ah e{ ( clt nS tg ie st ooi hr nrn tii ,t en( h igS wm nt [ hr ] ( ii si csn 1a h g ,rn g io ssss 2 o )t n )u c o)r {h ;c ta e nn, / e /g c S e eet d xr spi sen acg rt ys 3 i u n s c ee o rl r ns r ae e me : r c el e t "s t e u p: r rae ns t s "u w Lr o on r gd" i"L no g Fi an i lF ea di l -e d u n- k nown h pi a af s s eh sc le wo sd om e_ rr : rp p de ea a "t tr s u ue s r r_ w n nh o a r " "s d L Lh ) o oe : g gs i i( n nh a S Fs u ah c ie c ld e e_ s di s n f -p u u l it " n_ cp oa rs rs ew co tr d, F e a x i c l e e p # … d t … " L o) E …gxa r cb e …teo t …hpr u ett r in( eo4 xn0 " c1 L e, o a p g s td i ie n e os : nc S r u Cfi c oop c rrt e r i s edo s cen f t b= u reul" pg"L go aig irni gn t a r lg ee v t } e n . ss e r hu l e tb s t l les e u e eit r v v nr n e e{i n n (n s s1 sg h ho t tu+( e er 1 i ic) M n ne) a; t ( . (h s s so u o. u b um r s ri c t cn e r e( , iM .na t sgt a uS h r b(h g s. 1e tm )o t ri ,u in . tl na( sd gru gb (re es 1tt )m r ,.o i sn tuv g abe rs( gt1“1 er) ti) + )n,” g(1))), } p u pb ul bi lc ic c l sa ts as ti cLE V iE nN tS H lT eE vI eN ns G h{ tP eiT n- (4 String source, String ); target) { It is a totally different
Figure 6: One failed case of ChatGPT’s vulnerability repair } int m = source.length(); dynamic programming } int n = target.length(); solution on exposure of sensitive information (CWE-200). } int[][] dp = new int[m + 1][n + 1]; ... for (int i = 1; i <= m; i++) { without any hints about the vulnerabilities. As for GPT- for (int j = 1; j <= n; j++) { ... 4, which can repair 139 out of 154 test cases without return dp[m][n]; }} vulnerabilityinformation.GPT-4showcasesamuchstronger Figure 7: One failed example of ChatGPT’s bug fixing on capability for vulnerability repair than GPT-3.5. an implementation of levenshtein algorithm. We use a case study to demonstrate the different per- repair where vulnerabilities are predefined code patterns or formance of GPT-3.5 and GPT-4. As shown in fig. 6, we behaviors,bugfixingisusuallyprovidedwithtestcasesthat wanttorepairaloginservicecodethatcontainsanexposure are specific for the program to test. A program is regarded of sensitive information. The error messages sent to users as buggy if any of the test cases fails. Automatic bug fixing reveal sensitive information, including the reason of the aims to modify the source code to remove the bug. login failures (e.g., “unknown username” and “incorrect password”),whichcouldbeleveragedbyattackerstoexploit Automatically fixing bugs is a hot topic in software thesystem.WhileGPT-3.5failstoaddressthisvulnerability engineering, which is also referred as Automated Program effectively,GPT-4demonstratesitssuccessinmitigatingthe Repair (APR). Traditional APR [76], [77], [78], [79], [80], issue and safeguarding sensitive information. [81] is based on program synthesis which mutates the code Repairingvulnerabilitiesinrealsoftwareprojects.As until a good solution is found. Machine learning based shown in the table, ChatGPT can fix most NULL derefer- methods are also introduced. For instance, Neural machine ence vulnerabilities (e.g., CVE-2023-0216 and CVE-2023- translation (NMT) [82], [83], [84], [85] is a paradigm that 0217). It can hardly address other vulnerabilities, especially could be trained to understand code structures and models the ones involving complex application contexts. For in- based on NMT could be granted with code repair capa- stance,thebufferoverflowofCVE-2022-29242ishiddenin bilities. As LLMs like ChatGPT demonstrate the strong a complex code with more than 3000 lines and involves the capability of code underG is ntP aaT Dn-4 Pd r ie mnp eag ti hr,e od dr ecent studies proposed logic of key exchange protocol, which is hard for ChatGPT LLM-based bug fixing [33], [34]. They provide ChatGPT to process. As a result, ChatGPT repairs 3 and 4 out of with the source code as well as manual feedback or results 12 cases with GPT-3.5 or GPT-4 respectively. Extracting oftestcaseswhentherepairfails.Theirevaluationillustrates informativecodesnippetsandmessagesfromcomplexcode that ChatGPT for bug fixing not only is possible but also as part of the prompt poses challenges, but it holds great outperforms various existing methods. However, existing promise for future advancements. discussion on ChatGPT’s bug fixing is either on small scale or does not include the latest GPT-4. Therefore, we will 5. Bug Fixing investigate the capability of ChatGPT with the latest GPT-4 Softwarebugscancauseerrors,crashes,andotherissues version on a large benchmark. that can affect the functionality, performance, and security Datasets. We use QuixBugs [86], one of the most com- of software systems. Automatic bug fixing is the process monlyuseddatasetofbuggyprograms.Itcontains40buggy of automatically identifying and repairing software bugs Python programs and 40 buggy Java programs. Each buggy without human intervention. Different from vulnerability programhasasetoftestcaseswhichindicatestheexpectedbehavior of the program. Prompt GPT-3.5 Prompts. We construct the prompt as “Can you fix the I want to generate a hot patch for my software. I have an if (len > SIZE_MAX - (LSM_BOUNDARY - 1)) { bugs in the following code? {code}” where “{code}” is the o inff tic i qa 6l lp sa mt _c sh n o d_n m t oh de e ls _o bu ur fc _e a lc lo od ce (a .s . .fo )l {lows. } goto fail; Incomplete struct cal_block_data *cal_block = NULL; placeholder for the source code. size_t pad_zero = 0, total_mem = 0; GPT-4 ... Metrics. We run the test cases given by QuixBugs to i f c( l! iec nl tie -n >t so- u> ns do _u mn od d_ em lod .e sl iz. eda t =a l) e n{ ; s st ir zu ec _t t c pa al d_ _b zl eo rc ok _ =d a 0t ;a *cal_block = NULL; evaluatebugfixingresults.Abugissuccessfullyfixedifall p ia fd _ (z (e lr eo n = > ( SL IS ZM E_ _B MO AU XN D -A R pY a d- _ z( el re on ) % | |LS M_BOUNDARY)); p ia fd _ (z (e lr eo n = > ( SL IS ZM E_ _B MO AU XN D -A R pY a d- _ z( el re on ) % | |LS M_BOUNDARY)); test cases pass. { (len+pad_zero > SIZE_MAX-cal_block->cal_data.size)) { (len+pad_zero > SIZE T_ hMA eX s- ac nal it_ yb cl ho eck c- k> ic sa cl o_d rra et ca t.size)) goto fail; return -EINVAL; Results.GPT-3.5fixes24outof40Pythonbugsand14 } } } Ground Truth
out of 40 Java bugs. GPT-4 fixes 33 out of 40 Python bugs } if ((len > SIZE_MAX - (LSM_BOUNDARY - and 34 out of 40 Java bugs. In general, ChatGPT could be H uso ew ae v he or t, pI aca tcn hn wot h a icp hp il sy ath fe e wof f li ic ni ea sl p oa f t cc oh d. eIn is nt se ea rd te, dI w aa t n tht eto | | ( l e n + ( ( L S M _ B O U N( Dl Ae Rn Y % - L (S lM e_ nB O %U N LD SA MR _Y B) O) U) NDARY)) used for bug fixing. Regarding GPT-3.5, its ability to repair b Ge eg ni en rn ain teg to hf e t h he o tf u pn ac tcti ho n to ` q a6 cl hs im ev_ es n ed x_ am ctlo yd te hl e_ b su af m_a el l lo oc g` i. c as } > SIZE_MAX - func_return_value)) { return 0; the official patch. code is limited and varies depending on the programming Figure 8: Ask ChatGPT to generate a hot patch for CVE- language. For instance, GPT-3,5 can fix 60% Python bugs 2015-8940onAndroidkernelaccordingtotheofficialpatch. but only 35% Java bugs. GPT-4 in general yields better software may be impractical thus the developers need to repair results. It achieves a success rate of 85% and 82.5% prepare their custom patch. when applied to Java and Python test code, respectively. Given the above challenges of patching, recent stud- This underscores GPT-4’s superior ability to comprehend ies [69], [88], [89], [90] propose to automatically transform and analyze buggy algorithmic code. the official patch to an applicable patch. Conventionally, Asanexampleoffailedrepairs,thecodeshowninfig.7 the transformation is based on program analysis that suffers is the Levenshtein algorithm written in Java. Levenshtein from high deployment complexity. Additionally, learning- distance is the minimum number of single-character edits based methods [91], [92] leverage neural network models (insertions, deletions, or substitutions) required to change a togeneratesecurepatchessimilartohuman-writtenpatches. string into the other one. The buggy code is the recursion With the development of LLMs, ChatGPT is a possible al- formofthealgorithm,whentwocharinthecomparedstring ternative to end-to-end patching. We demonstrate ChatGPT- equal, it adds an additional 1 into the total count which is a based patching in two real-world scenarios. Note that we logicflaw(line12).Upontherequestofbugfixing,GPT-3.5 label deleted lines in red and inserted lines in our figures. adds an additional main function. Though the repair indeed Hot patch generation. Hot patches aim to fix security makesthecodemorecomplete,itisnotrelevanttothebug. vulnerabilities without stopping the service. Developers can GPT-4addressesthebugbutitchangesthewholealgorithm hook the vulnerable function and apply a pre-constructed pattern.Itgeneratesatotallydifferentimplementationofthe hot patch to it. In this way, the code defined by the hot Levenshtein algorithm using Dynamic Programming (DP) patch is run before reaching the vulnerability. We inherit instead of the original version using recursion. In general, the definition of hot patch generation from Xu et. al. [69]: repairs from ChatGPT may contain various problems, in- Given a vulnerable function F and its official patch P cludingunnecessarychanges,modifyingoriginalcodelogic, atlocationL,wewouldliketofindasuitablelocationL′ of introducing new errors, etc. F in binary form to insert an automatically generated hot patch P′, which has the same semantics as P. 6. Patching We also use the motivating example in [69] to demon- Patching is a technique used in software engineer- strate whether ChatGPT can handle the task of hot patch ing [87], which involves applying a small piece of code, generation. For CVE-2015-8940 in Android Qualcomm known as a patch, to an existing software system to correct msm kernel 3.10, there is an official patch as shown in an error or improve its functionality. For software security fig. 8 which adds a sanity check (labeled in green) in especially, patching aims to resolve security vulnerabilities function q6lsm snd model buf alloc. The hot patch should in the software system. implementexactlythesamelogicasthesanitycheckbutcan In a common situation, when a new vulnerability is onlyusevariablesavailableatthebeginningofthefunction, revealed, the developers of the affected software obtain i.e., function arguments (client and len), global function the vulnerability report and offer an official patch for the calls (cal utils get only cal block), and global constants software. Other developers who used the software can shut (SIZE MAX and LSM BOUNDARY). We explain the con- down the current service, download and apply the official cept of hot patch generation in English and use it as the patch,thenrecompileandrestartthesystem.However,inthe prompt for ChatGPT. real production environment, applying the official patches ChatGPT can understand the request and produce rea- sometimes is not an available option in some situations. sonable hot patches but the generated ones may have prob- For instance, if the software is running and is too critical lems. ChatGPT with GPT-3.5 misses part of the condition to shut down, developers need a hot patch that addresses inthesanitycheck,resultinginanincompletefix.ChatGPT the vulnerabilities while keeping the system running. In with GPT-4 produces a good sanity check but also involves addition, many services use old versions of the software redundant check on cal block == NULL, which exists in which may not be maintained anymore, thus the official the original code. From the results, ChatGPT can generate patch may conflict with the old version. Upgrading the reasonable and fairly good hot patches according to thePrompt GPT-3.5 Prompt GPT-3.5
I want to apply a patch to fix a vulnerability in the code in <?php I executed the C code below: Based on the stack trace, the root cause of the error is a stack smashing version 1. However, I only have the official patch on version $sanitize_all_escapes = true; int openhost(const char *hname) { detected error, which is a protection mechanism built into some compilers 2. I want you to patch the code in version 1 using the same $fake_register_globals = false; char *cp; to detect buffer overflow vulnerabilities at runtime. In this case, it appears l Po ag ti cc ho f o p na vtc eh ri sn ig o np r 2e :s ented in version 2 patch. i in nc cl lu ud de e_ _o on nc ce e( (" $. G. L/ Og Bl Ao Lb S[a 'l ss r. cp dh ip r") ']; . "/patient.inc"); c ih na tr i n =a me 0[ ;256]; t rh ea st u t lth ee d p inro ag r mam em is o rt yry cin og rr t uo p w tiori nte e b rre oy ro an nd d t h ae s eb go mun ed ns t ao tf io a nn f aa urr la t.y, which has < r r u i i $? e e s n n tp q q e c c e h u u l l mOp i i u u ppr r d d lee e e e an_ _ _ _ tEo o o o eMn n n n _Rc c c c d\e e e e i( ( ( (C r" $ " $ =o $. G . Gr G. L . Le L/ O / O\H Og B g Be Bl A l Aa Ao L o Ld Lb S b S[ [e Sa a' ' [rl l; 's ss s Or r. . Ec cp p _d dh h Si ip p Ir r" ") ) T' '] ]; ; E _. . D I" " R/ / ']p p a a .t t i i "e e /n n tt t e. . mi i pn n lc c a" ") ) t; ; es"; $ $ $ c $ ?t f s o f >e h a n h =m n v f=p i e o l t rf pa i to et z _p ne e s (e_ d a "nd _ f( $i t e" tr e _ $ em f= t mp i e pl l$ m la eG p at _L l te d O a ei=B t _rA e d_L _ inS d ra[ /i m' "r e/ ( .O $ $"E . _ s_ $ G aS _ E nI G T iT [E tE 'T i_ [ t zD ' e eI t m dR e p _'] m l t p a e. l t m a e p" t ' l]/ e at )' t]e ; e,,m p ' 'l r ra ' 't ) )e ; ;s"; Itc }i rp f a c … f i e is= p ( o f l e + }* r s sh +c e( an ;p *( a ci r cm = p e oe = = t r; = u e= r' 0 d n[ ; u' ' m* ]) 0 pc ' ; p{ ) a n& n d& a t m h* e ec [ sp i t ] a! c= = k t' ' ra] \ c' 0 e; ' ; isc p a+ s+ f, o lli o+ w+ s) : name[i] = *cp T t T c h co h ah h n a ute i ah s r s m e as ecp co e n ate d ea i c se brmi s f ugi s ,ec f rn fb e eal i ui p a rn r tr p t oe ea te vh ryo t e e tf w a rh r fc es a li oo t sh ni wd suo 2e m nu a5 t ot e nh 5p s da e r c t xto ch h pi p os aa le r i rt c rc a r ut ia l h t cy p u tc e tecs h th rni hen se a ec g oc m k k mrt h e ti in o efe ag mi e e r ei r n or t a xsr s rco y yub e r .rh o ee i as Tu d s t onl shi k d e i f2se s in x. 5l : oy I 5n tfu , ht a t gh h t im hhe see e so i[ l n sepn i sna te ] h ugc it ee t s=h h a …ct o o*t o fcw ds p etr oi t wre es i lli $fh = fopen("$template_dir/".$_GET['template'], 'r'); #0 __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:51 GPT-4
$ c ? V < $ $f o > ? s feh n p a ar v h n ks= e p i eio r t _f t i rno _ z e p s e g1e a _ i tn f a so( e l t " _ l ep$ f _ rat i e _te l s gcm e c lhp _ a o:l d p ba i e at r s l e _ s =_ n = d a t i m frr e/ ( au$" le ;_ s. G e;ET['template']), 'r'); < $ $ i i $? s f n n tp a a c c eh n k l l mp i e u u pt _ d d li r e e az e _ _ te g o o e_ i n n _a s c c dl t e e i( (l e r" $ _ r . G =e _ . L s g $/ Oc l Gg Ba o Ll Ap b Oo Le a Bb Ss l [ Aas '= Ll= s Sst [ r.G f 'r cpa Ou dhP l Ee ip; s _r"T )e S'- ; ]; I4 T. E _" D/ Ip Ra ']t i .e n "t /. ti en mc p") l; ates"; # # ( * # ( m f # #oa n*1 2 3 4 5* s rc e t: g t i e fi0 0 0 0 0%o = ydx x x x x_n m_s0 0 0 0 0f= b a0 0 0 0 0sta e a g i0 0 0 0 0lc r c .@0 0 0 0 0cmt ki7 7 7 7 5:o t 3ei rf f f f 5nnf f f fa 3nf f f f 5a@f f f fc t7 7 7 7 5t ree ya a b b 5e =d =2 6 1 1 5n n\ 02 b 6 6 5t n er x7 8 b a 5"y e 7)f 3 3 f 4=1 2 d f7 1a 7fd _ fi i t 8fon ni i b 7n n. 9_ . a b_ _ / a_ _s ic 9_ _ nb_ _y k 8G s sol G t o8 ti rb dI ar pa 4_ Itc e _ c, ec 7a _ kp _f e n b m _m s "_ @ ho s c/ ft oe p tr o= haet ss o r f kcn( t tms s i _ ) ktfa (i ry fxt ) a y ag @ s_/t =l ie m fi la b a e f (a ab c in )l l s__o st ar hafr ey tat i b ,. n= st c oa g t0: arl7 x . t d cc9 7 ke:f 1 _f tf e8 cf7 c1 hb t ke9 _d8 f" a8 ) i 6 la .9 ct : 2"* 9** %s T d o i I w h ss t m u fh n: oi ssee an u a i ma pz l str do e m o ho e ce s io a 2 n.a[ s t 5 gTb i ui bc 6 hu s] pla ief e i rsf su o e = t t os thr b h e ve ae e*o ce tci v to n n r itpe off hg a lr o ne t f mw wlh o bie r en w ei c t p i.e t b a n e uIr u n gn n tr f o f oh tt et rhr o vn ir gi e i as i ts gn ro m w c e s t oa rrh et eivsa te e di eec s ` r, k t af fl hot lo nohs er n dwe `m g s l ce o e twa a ar o rs hr c up toh e kh s.ri n a i n T c no n acg ghc no e, 2c t ap h uw 5p ry er 5h yrs i o n ,i p c c w b g lh reh ol h ae ac gt e rm h dy a rn ap i ana c ri mtc t gt ah eia c c e r t t l ots ol l ey in , n tr aa w hh e s bm e a h fo o rp i se f oc rp tt hc m .abe o cun d kfs f e e r include_once("../globals.php"); $fh = fopen("$template_dir/".$_GET['template'], 'r'); To fix this issue, … i $n tc el mu pd le a_ to en _c de i( r$ =$G GL LO OB BA AL LS[ S' ['s Or Ec _d Si Ir T'] E _. D I" R/ ']p a .t i "e /n tt e. mi pn lc a") t; es"; $ cf oh n v= e rf to _p se an f( e" _$ ft ie lm ep _l da it re __ nd ai mr e/ ($" _. GET['template']), 'r'); W theh a et r ris o rt .he root cause of the error? Returns the line of code which causes $fh = fopen("$template_dir/".$_GET['template'], 'r'); ?> Figure 10: Given the error message (stack trace), find the ?> Generate version 1 patched code. root cause of stack overflow in ntpq (CVE-2018-12327). Figure 9: Ask ChatGPT to patch CVE-2015-8940 on Open- Prompt GPT-3.5 EMR 5.0.0.5 based on the official patch on 5.0.0.6. I executed the C code below: The root cause of the error is a buffer overflow due to the size of the input string int openhost(const char *hname) { `hname` being larger than the size of the `name` buffer (which has a fixed size of 256 char *cp; bytes). … To fix this error, .... char name[256]; u bs yer e’ is thr ee rq mue as nts u, albu et fft oh re t oo rut ac uo tm omes atc icer ata ni an ll yy sin s.eed validation c i ip n f ct = p( +*i h +c n ;p= a m =0 e =; ; '[') { T = c ou vh r e*e r rc e fl pi lnn o tTe w i h n .o i dsf e c l xio n d ie .e Wc t oh hpa eit e n c s ia t ru h es e ae ccs hu et rh r see tn he t e r cr o h sir a z ri es a c oth t fe e tr h f p eo o ll nio n aw t mein d eg t b oli u n b fe fy e i rcn , ps th i id n ise t o lt i nh th ee e wf o n ir la l l m co ao e up b s: eun fa afem bre ua[ fi t f e] th r e Patch backporting. Patch backporting is a task for = *cf por (i = 0; *cp && *cp != ']'; cp++, i++) name[i] GPT-4 applying official patches in a newer version to software i ef ls e(* c rp e t= u= r n' ] 0' ;) name[i] = '\0'; T coh de e r o cao ut sc ina gu s the e o ef rt rh oe r ie sr : r no ar m i es [ a i ]b u =f fe *r c poverflow in the `name` array. The line of } … } The `name` array has a fixed size of 256 characters, and the input string `hname` has
in an older version, as defined in [88]. In the end, one T trh ige gr ee r ii ns ga ct oe rs et dc ua mse p .hname = “[aaa …. aaa]” (300 ‘a’ characters) m iteo rare te t ,h ia t n w 2 ri5 te6 s c ph aa sr ta tc ht ee r es n b de otw f e the en `t nh ae m s eq `u aa rr re a b y,r a cc ak ue st is n. g A as bth ue ff elo r o op v ec ro fn lot win u ae ns d t lo e ading What is the root cause of the error? Returns the line of code to the coredump. should modify the official patches to avoid any conflict which causes the error. Figure 11: Given a failing test case, find the root cause of with the older-version software. For instance, if the official stack overflow in ntpq (CVE-2018-12327). patch modifies a feature that is newly introduced after the olderversion,weshouldremovesuchmodificationfromthe could be in various graininess such as specific function, a patch.Weusethemotivatingexamplein[88]todemonstrate code block, or one improper sanity check. ChatGPT’s capability in this task. Basically, root cause analysis is a task of understanding The example is about CVE-2018-10572 on OpenEMR, thecausalrelationbetweenthecodeandtheerrororvulner- a software for managing medical records. The official patch ability. Such context learning could be a strength of LLMs as shown in fig. 9 is applied on OpenEMR 5.0.0.6 while like ChatGPT. In this section, we analyze ChatGPT’s capa- wearegoingtopatchOpenEMR5.0.0.5.Thekeyfiximple- bility in root cause analysis using case studies. We consider mented by the official patch is the check on user-provided using either error messages or test cases for identifying the directory variable template, in order to avoid path traversal root cause. vulnerabilities. Theofficial patch on OpenEMR5.0.0.6 also Root cause analysis based on error messages. As a involves a few importing operations that are not relevant to case study, we use the vulnerability of CVE-2018-12327 in the 5.0.0.5 version. Therefore, the patch for older version ntpq, which is also the motivating example in [93]. CVE- 5.0.0.5 should include the directory check but ignores the 2018-12327 is a stack overflow vulnerability in ntpq to check on import statements. achieve arbitrary code execution because it lacks a sanity ChatGPT does a good job on this task. ChatGPT with checkforthelengthoftherelevantcommandlineargument. either GPT-3.5 or GPT-4 generates a solid patch satisfying Inthefirstcasestudy,weassumethatanexploitisfound the aforementioned requirements. ChatGPT demonstrates a during the execution of ntpq. We craft a prompt containing strong ability of understanding the context of code. the stack trace and the error message as shown in fig. 10, to discover the root cause of such a failure. 7. Root Cause Analysis ChatGPT is able to identify the root cause perfectly Root cause analysis is a technique used in software se- in this case. It first identifies the vulnerability as stack curitytoidentifytheunderlyingcausesofsecurityincidents, smashingaccordingtothestacktrace,andthenlocalizesthe vulnerabilities, or breaches. The goal of root cause analysis vulnerability at the line of code name[i] = cp. In addition, istodeterminewhyasecurityissueoccurredandtodevelop though not requested, ChatGPT also provides possible fixes solutionsthataddresstheunderlyingcauses,ratherthanjust for the vulnerability. All the above results are correct based treating the symptoms. on our manual examination. Existing tools [93], [94], [95], [96], [97], [98], [99], Root cause analysis based on failed test cases. In this [100] for root cause analysis first gather information about case study, we reuse the example of CVE-2018-12327 but the errors or vulnerabilities, such as bug messages from change the hint of root cause analysis from error messages the operating system or compilers, execution traces from to a failing test case. As shown in fig. 11, the failing debuggers, etc. Then program analysis methods are applied test case triggers stack overflow by assigning hname a very to analyze collected data and identify root causes, which longname.ChatGPTidentifiesthebufferoverflowissueandTABLE 5: Decompilation on LeetCode solutions. localizes the critical code correctly. ChatGPT also provides Correctness reasonable explanations of the mechanism of the exploit. Tool Namematch Typematch Passed Wrongresults Failedexecution IDA 21.40% 42.47% 33.33% 10% 56.67% 8. Decompilation GPT-3.5 45.49% 59.20% 43.33% 26.67% 30.00% GPT-4 56.52% 78.26% 53.33% 20.00% 26.67% Decompilationistheprocessofanalyzingmachinecode and producing a high-level representation of the original based on the code logic. We count the matches between sourcecode.Itisareverseengineeringtechniquethatallows variable names in the orignal code and decompiled code, developers to understand how a program works by convert- following DIRE [109]. (2) Type match. Following [110], ing machine code back into a human-readable form. we assess the type prediction accuracy, which is similar to Decompilation is an important technique for software the name match. By comparing variable and function types security because it allows security professionals and re- betweentheoriginalanddecompiledcode,wedeterminethe searchers to analyze the behavior of a program and identify number of variables and functions that have retained their potentialsecurityvulnerabilitiesormaliciouscodethatmay types.(3)Correctness.Toevaluateifthedecompiledsource bepresented[101],[102],[103],[104].Throughtheprocess code maintains the original functionality, we use the code
of decompiling an application project, security researchers to answer the corresponding LeetCode coding problem on can gain a deeper understanding of its functionality and the website and examine how many tests from LeetCode’s pinpoint potential vulnerabilities that can be exploited. test suites are passed. To be specific, the code may produce However, the process of decompilation is not always threeoutcomesforeachtest:passed,wrongresults,orfailed straightforwardduetovariousfactors.Codeobfuscationand execution because of compiling problems or fatal errors. anti-debugging techniques [105] can significantly compli- In addition, we choose the well-known binary analysis tool cate the decompilation process. Furthermore, the decom- IDA Pro [107] to accomplish the same decompilation tasks piled code may not always precisely match the original and use the results as a baseline. source code [106]. Therefore, developers must rely on their Disassembly-to-source-codetranslation.Table5show- understanding of the original code to interpret the decom- cases that ChatGPT has a superior capability on decompi- piled output accurately. lation compared with IDA Pro on the LeetCode test data. LLMs now have the potential capability to understand GPT-4 correctly infers the correct name of 56.52% variable the relationship between assembly code and the source identifiers, an enhancement of 11.03% over GPT-3.5, and code, which opens up a new avenue for decompilation that 35.12% over IDA Pro. Likewise, GPT-4 demonstrates pro- doesnotrequireexecutionenvironments.Inthissection,we ficiency in predicting data types, with a correctness rate of analyze the capability of ChatGPT in decompilation, focus- 78.26%,significantlyoutperformingIDAProby35.79%.In ing on the translation from assembly code to source code. terms of the functional correctness, code produced by GPT- Binary-to-assemblytranslationisaddressedbyexistingtools 4 passes 53.33% of the test suites which is 10% higher such as objdump and IDA Pro [107] accurately. Therefore, than GPT-3.5 and 20% higher than IDA Pro. Notably, IDA ChatGPT can rely on the tools to preprocess the binary. Pro produces a substantial number of programs (56.67%) Assambly-to-source translation is however challenging con- that fail at the compilation stage, approximately 26% more sidering the rich semantics of source code. thanGPTmodels.However,GPTmodelsoccasionallyyield Dataset. To assess ChatGPT’s decompilation capabil- misleading programs, exhibiting incorrect execution results ities, we conducted an empirical analysis with real-world in 20-27% of instances. programs. A set of 30 programming solutions, drawn from We then use a case study to demonstrate ChatGPT’s LeetCode[108]andwrittenintheCprogramminglanguage, decompilation capability. As shown in fig. 12, we ask served as our test base. These solutions were first compiled ChatGPT to decompile a piece of assembly code back to into binary code using gcc on the x86 64 platform, and C source code. The code is supposed to implement the subsequentlydisassembledintoassemblycodeviaIDAPro. algorithm of traversal a binary tree using recursion. The The obtained assembly code constituted our benchmark, inorderTraversalfunctionistheentryofthealgorithmwhile with the original C source code functioning as the ground the inorder function is recursively invoked during the code truth. To ensure a balanced representation, the selected execution.IDAProeasilyrecoversthefunctionnamesfrom LeetCode problems span easy, medium, and hard levels of the function references in the binary files and makes the difficulty (10 problems in each difficulty level), and the overall code compilable and executable. IDA Pro’s decom- source code length ranges from 10 to 70 lines. pilation is in general preservative. It leverages only existing PromptsWeinvokeChatGPTwiththeprompt“Decom- information from the binary and focuses on the correctness pile the following disassembly to C program” and attach ofcode,insteadofmakingthecodesimilartohuman-written the assembly code produced by IDA Pro. We manually code by inferring readable variable names and data types. postprocess the responses from ChatGPT by extracting the For instance, the variable names are meaningless such as decompiled source code. v1, and members of structs are represented by pointers and Metrics. We use the three metrics to measure how offsets. On the other hand, ChatGPT has a strong capability accurate the decompilation is. (1) Name match. Variable to predict what the original code looks like. It is evident names are lost when the code is compiled to binary in that ChatGPT infers the semantic of the code and assigns release but decomplier could predict the variable names variables in code with frequently used names. For instance,Prompt GPT-3.5 Prompt GPT-3.5 Do debloating on the following code by removing the feature of #include <stdio.h> decompile the following disassembly to C void inorder(Node* rdi, int* rsi, int* rdx) { accepting two arguments from the command line. program. if (rdi == NULL) return; #include <stdio.h> int main( void ) { inorder(rdi->left, rsi, rdx); printf("One or two arguments expected.\n"); in o r d e r p u b pl ri oc cin no er ad re r ; CODE XREF: (*rdx) = (*rsi)++; int main( int argc, char *argv[] ) { } return 0; inorder+35↓p *(rdi->val + (*rsi) * 4) = *(rdi->left + (*rsi) * 4); … m o v [ r b p + v a r; _in 1o 8r ]d , e rdr+ x78 } inorder(rdi->right, rsi, rdx); wrong code }i f ( pa rr ig nc t f= (= " Th2 e ) a r{ gument supplied is %s\n", argv[1]); #include <stdio.h> GPT-4
c j mzm o p v s h [ ror ab r xtp ,l + o [rv c ba _ pr 7 +_ F v8 a], r 0 _8] i n t * i .n .o .rderTraversal(Node* rdi, int* rsi) { e l se pr ii nf t( f a (r "g Tc h e= = a rg3 u m) e n{ ts supplied are %s and %s\n", argv[1], int main(int argc, char *argv[]) { … in o r d e r m m m o o o ev v v n d p r r ra d cxx x ,, , [[ [ rr r ba b px p+ ++8 vv a] a rr __ 11 08 ]] } inorder(rdi, rsi, r8 G); PT-4 a r g } }ev l s[ e2 pr] i) { n; tf("One or two arguments expected.\n")E ;xpect to remove i } }f e p p( lr ra si ir e n ng {t tc f f ( (= " "= T O 2 h n) e e { a ar rg gu um me en nt t s eu xp pp el ci te ed d .\i ns " % )s ;\n", argv[1]); ; public inorderTraversal void inorder(Node* root, int* array, int* index) { } } inorderTraversal proc near ; DATA XREF: if (root == NULL) { return;} … call malloc ; PIC mode inorder(root->left, array, index); Figure 13: Ask ChatGPT to do debloating on a C program. mov [rbp+var_8], rax array[(*index)++] = root->value; m m mo o ov v v r d ra dwx xo, , r[ [dr rb b pp pt+ +r v v[ra aar rx_ _]2 2, 0 00] ] } inorder(root->right, array, index); correct code 9. Debloating mov rcx, [rbp+var_8] int* inorderTraversal(Node* root, int* index) { … inorderTraversal endp ... Softwaredebloatingistheprocessofremovingunneces- inorder(root, array, index); } sary code or features from a software application to reduce Source Code IDA its attack surface and improve its security. For example, v r } i }o e n i s t d S * r i s . i . i i i i e z t . n .f n n ni i s e r . o .o o tn n [ ) u rr ro o( * ( ; c dd dr r! * t ee ed dr r r rr re eo e er ro t( ( T ( s Tt ur r r r( S r) ro o e os i i i a no o e ot n n z v{ St t N tr t t e e i- - o ,u * * ) rr z> > d c + se el r e rt r r + at )e i ee e *] lu f g ss s T r {t h ,, S rr (=n , t i oe ; , rz oe r r ee tN o} e r t) ,o os e u d t, s r{e - , n* >r S ve ir as zo lS eo ;i )t z ;, e); _ } v }i o i _ i r in { } i .n _ f e nt d . i r t i t o6 v * . ( n e *n u r4 3 ( _ _v o tt r d _ D _3 a r u6 n e= _ W f; 1 d r4 r (rf O a e n( r aea R s/ ) r *( ie 1ss D t/ a * ns ,ut c 3 *( ou lc ae )_ ) rl vta la +Q ( dt 3;l lx + W a e; ,l ; iO 2 r i nR (/ an oD + */ 2 o r ( )_*r d4r ;L Q)d ea L W(e rx Oar T( * R1 r_ D a _ v+ v*i 3 e8 )n ) r) (t s, a6 = a 14 l (a * _a 2 +(_ _1 , 1D i, 6W n a_ )O t3_ ,R 6)i D 4; n a* at 2) 16 ,a ,4 1 a _a ; 3 D2 ) W, ; O R. D. . *) a{ 2){ a o t p i [h n 1r re co 1w e lm 6T ue x u ]db i ht s se aie ei nn nb r rn g’s e dr gsio o s dw awsn t yry as s ea ntse y it atr ce sh metmam o av it n. cea ec ary R x aaa ly nh ln eh s aim ba a i lb s yv pioe t se pv [ iau r 1i sf on ts 1te [age a 1a 1cd c ]t 1ht ku ,h 7b esr e [ ]e sy 1 ,fs u 1u f [a on 12s nttu rd 1]na ,c a 8ec sh m ]c [k o ,1ee fea 1s [r tn 1s s ws 3ta 1]a ac t r , 9o l rye l ]e [yr ,c 1t .fa [o de 1 1i am e 4n 2t b ]up 0,lp r or ]el [o .au 1m Stg 1i is eni i 5n s vg ]e as -, , Figure 12: Ask ChatGPT to decompile an assembly code. eral studies [121], [122], [123] also propose to leverage Tested on a simple LeetCode C solution program and its deep learning/machine learning models to identify code x86 64 assembly code. for removal in a learning-based fashion. Similarly, given ChatGPT’s impressive ability to understand source code, it holdspromiseforconductingefficientdebloatingdirectlyat GPT-4accuratelynamestherootofthebinarytreewithroot thesource-codelevel.Inthissection,weexploreChatGPT’s and correctly represents the two child nodes as root→left potential for software debloating through both simple code and root→right. Such informative naming significantly en- examples and real-world scenarios. hances the readability of the code, which is essential for Debloating simple programs. We initially debloat a advanceddecompilation.GPT-3.5canalsoinfersomeofthe simple C program, as illustrated in Figure 13. This pro- variable names and types correctly, but makes a mistake on gram accepts command-line arguments and exhibits distinct the code logic, resulting in wrong execution results. GPT-4 behavior based on the number of arguments provided. It demonstrates a major improvement from GPT-3.5 in terms outputs the arguments when there are one or two, while of either prediction of names and correctness of code. displaying an error message otherwise. Our objective is to remove the functionality of accepting two arguments Overall, GPT models show impressive decompilation from the code. To accomplish this, we engage ChatGPT capabilities, surpassing the IDA Pro baseline across nearly by presenting the source code along with the prompt “Do allevaluatedmetricsonourLeetCodetestcases.Theresults debloating on the following code by removing the feature
show that GPT’s language processing capabilities extend of accepting two arguments from the command line.” beyond human languages and source code, demonstrating ChatGPT understands the request and successfully re- the ability to parse low-level assembly languages and com- moves part of the original code while keeping the remain- prehend complex underlying logic. ing part untouched. ChatGPT with GPT-4 gives a perfect solution which deletes the IF code block of the two- Binary-to-disassembly translation. ChatGPT can argument scenario. With GPT-3.5, ChatGPT initially fails hardly disassemble binary files to assembly code in our to generate a valid solution as it mistakenly removes the experiments. We design the prompt “Disassemble the one-argument feature. However, upon multiple attempts to following binary to assembly code”. We feed the prompt regenerate responses, it successfully produces the correct as well as a hexadecimal string of a x86 64 binary to answer in two subsequent tries. This outcome showcases ChatGPT. ChatGPT with either GPT-3.5 or GPT-4 cannot ChatGPT’s capability in software debloating, albeit with produce the disassembly. Instead, it provides a suggestion inaccuracies, particularly in the GPT-3.5 version. that the user should transform the hexadecimal string to a binary file in the operating system and use a disassembler Debloating real-world projects. We construct a de- or debugger to finish the job. In general, binary files bloating task using the source code from bzip2 [124]. As in hexadecimal string are much longer than the original shownin fig.14,weaimtoremoveanysourcecoderelated source code and lack semantics, which is fundamentally to feature of memory usage reduction, which is controlled challenging for LLMs to process. bythecommand-lineoption–smallinbzip2’smainfunction.Prompt GPT-3.5 Prompt Prompt Do debloating on the following source code. We want to remove I {ntNative main(IntNative argc, Char *argv[]) There is a function `test` defined as the below: There is a function `test` defined as the below: the feature of memory usage reduction via option --small. ... void test(int x, int y) { I { n t . / / fN . / * oa . - rt D - ii o ( fv e A a e s n a ( d Is = Sm o a Fa m g a Li e a r An t i g G h n L( (i i "n . sI -g . tn -. . ;t " N )- aa )- at * i b/ !v r=e e aka Nr U ;g Lc L, ; C ah aa r = * aaar -g >v li[ n] k ) ) { f } o/ i r* f - . - ( (. v a v. eA a e rn r bd = b o o S o sa a s ig r ipu ta g tt yi L yc i n i oc = s >n . t e. ; 4 4s. ) ;s a- a f- u* ! l/ = ly N U rL eL m; oaa v e= sa a -- -> sl mink a) l l { i f ( } 2 i f * e ( lsy x p per r i i= < n n= = {t t x y ( () " " + O s{ K o" m1 e0 ) t;) h i{ ng bad"); ( C b fuT oa nh one cl e tys ia ooa n num e c `r tu oc en no sd d tse `iy ?) tim onb o ol fi c r ee ax ce hc iu nt gio `n fa t io l( )o ` b inta in the i i if f f ( ( (I I IS S SF F FL L LA A AG G G( ( (" " "- - -- - -s d ct e od c mo o pu m rt p e" r se s) s ") s )" ) ) ) s oor ppc MMM ooo ddd eee = == S OOM MM_ __F ZU2 ;NO Z; ; e e el l ls s se e e i f ( bo lp oM co kd Se i z= e= 1 0O 0M k_ Z = && 2 ;blockSize100k > 2) } fail(); i if f ( (I IS SF FL LA AG G( (" "- -- -f to er sc te "" ))) ) of po Mr oc de eO v e r w r i t e == OT Mr _u Te E; S T ; e el ls se e // Does something. Fail to remove the if block } else { GPT-3.5 i i if f f ( ( (I I IS S SF F FL L LA A AG G G( ( (" " "- - -- - -k s qe m ue a ip l e" l t" ")) ) ) ) ) k s ne m oe a ip l sI l yn M p o u d t e F i l e s = = = T T Fr r au u le e s; ; e ; e e el l ls s se e e } return exitValue; } print("OK"); Y boe os, le w ae n c ca on n dru itin o ns y om f b reo ali cc h e inx ge c `u fati io l(n )` t io n o thb eta `i tn e sth t`e if (ISFLAG("--version")) { license(); exit ( 0 ); } else } function. i if f ( (I IS SF FL LA AG G( (" "- -- -l ei xc pe on ns ee n" ti) a) l " ) ) { w orl ki Fc ae cn ts oe r( ) =; e 1x ;i t ( 0 ) ; } e el ls se e GPT-4 When will the function `test` reach `fail()`? if (ISFLAG("--repetitive-best")) redundant(aa->name); else IntNative main ( IntNative argc, Char *argv[] ) To do this, we will first assign symbolic variables to if (ISFLAG("--repetitive-fast")) redundant(aa->name); else { `x` and `y` and then execute the function using } ... E unx rp ee ac ct hto a br le em ifo bv le o cth ke whole . / f. * o. - r- (A an ad =a g aa ri gn L i. s. t. ; - a- a* / != NULL; aa = aa->link) { GPT-3.5 these symbolic inputs. ...
i i f f b( ( lv o oe p cr M kb o So d is e zi et = 1y = 0 0> O k M _4 =Z) &v 2&e ; r sb mo as li lt My o d= e 4 &; & blockSize100k > 2) } ... Successfully removes --small option T grh ee a f tu en r c thti ao nn `` yte +s t 1` 0w `i l al nre da `c 2h * ` f ya `i l i( s) ` n w oth ee qn u ` ax l` ti os `x`. H fue nr ce ti's o nth : e {C s oy dm eb }olic execution of the `test` if (verbosity > 4) verbosity = 4; // Does something. // Does something. Successfully removes the if block Here is the reasoning: … The boolean condition for reaching `fail()` is `(2 * y return exitValue; == x) and not(x <= y + 10)`. Correct answer. } return exitValue; Therefore, the function `test` will reach `fail()` } only when `2 * y` is not equal to `x` and `x` is greater than `y + 10`. GPT-4 Figure 14: Ask ChatGPT to do debloating on part of the Sure! To reach the `fail()` function in the given main function of bzip2. This is wrong. 2 * y should be equal to x. c co ad ll e o, f w the a tn fe ue nd c tt io o nfi …nd . the path that leads to the GPT-4 The `fail()` function will be called if the following ChatGPT is capable of debloating on such real pro- The function `test` will reach `fail()` when the conditions are met: following conditions are met: 1. `2 * y == x` duction code but inaccuracy exists. ChatGPT with either 2. `x > y + 10` 1. `2 * y == x` Let's create a boolean expression that represents GPT-3.5 or GPT-4 removes the block about –small in the 2. `x > y + 10` Correct answer. this path: FOR loop. Another variable smallMode is related to the – … (2 * y == x) AND (x > y + 10) small option. If disabling –small option, we should assume As an example, let's choose `x = 24`. Then, `y` Correct answer. must be equal to `x / 2 = 12`. ... variablesmallModeasfalseandalsoremoveredundantcode usingsmallMode.ChatGPTwithGPT-4handlessmallMode Figure 15: Solving symbolic execution problems on simple correctly by removing the IF block whose condition is programs. ChatGPT is able to reason conditions in code certain to be false. ChatGPT with GPT-3.5 attampts to while GPT-4’s result is more concise and stable. remove smallMode in the same IF block but it assumes smallMode to be true, which is not correct. problem, symbolic execution is still an expensive dynamic Itisworthnothingthatithasafewchallengesforusing analysis method with heavy computation requirements. ChatGPT in real-world debloating tasks. First, software However,ChatGPTispotentialtoreplacecertainexpen- debloating is usually for complex software that is non- sive components in symbolic execution, such as solving the trivial to trim but ChatGPT is limited in processing long path conditions as Boolean satisfiability (SAT) problems, in content. Second, software debloating may work on binary order to efficiently explore more paths. In this section, we files including linked libraries, which cannot be processed demonstrate ChatGPT’s capability on symbolic execution, by ChatGPT originally. especiallytheextractionofexecutionpathsandSATsolving. Exploring execution paths in simple programs. In 10. Symbolic Execution fig. 15, we demonstrate symbolic execution using ChatGPT Symbolic execution [125], [126], [127], [128], [129], on a simple C program. The C program defines a simple [130], [131], [132], [133] is a technique used in software functionthattakestwointegersasarguments,andoneofthe engineeringtoanalyzethebehaviorofaprogrambyexplor- execution paths will reach a failure state. The user intends ing all possible inputs and execution paths in a systematic to understand in what situation the program will fail. manner. In symbolic execution, a program is executed with In the first prompt, we ask the question “When will the symbolic inputs instead of actual values. These symbolic function test reach fail()?” In this case, ChatGPT is able to inputs are represented as variables with unknown values, provide detailed logical reasoning such as extracting key called symbolic variables. As the program executes, the IF conditions in the code. It has the capability of basic symbolic values of the variables are tracked and manipu- Boolean operations, such as knowing the negation of “x lated,allowingtheanalysistoexploreallpossibleexecution ≤ y + 10” is “x > y + 10”. However, ChatGPT does paths.Byexploringandexploitingpossibleexecutionpaths, not guarantee the correctness of such logic reasoning. For symbolic execution is promising to identify deeply hidden instance, with GPT-3.5, ChatGPT gives a wrong conclusion bugs and vulnerabilities as well as generate test cases that saying “2 * y is not equal to x”, which also contradicts cover the vulnerable execution paths. its own explanation in the context. ChatGPT with GPT-4 One limitation of symbolic execution is the path ex- gives a good answer “2 * y == x” along with a concretized plosion [134]. When the program grows larger and more example “x = 24, y = 12”. In the second prompt, we complicated, the number of possible execution paths expo- write the prompt using a more formal presentation, asking nentially increases, causing an issue of scalability. Though ChatGPT to run “symbolic execution” and return “boolean various path pruning and selection methods [135], [136], expression”.ChatGPTunderstandstherequestandproduces
[137], [138] are designed to mitigate the path explosion correctbooleanexpressionsrepresentingtheconditionofthelocal counter j. Whether the code will reach goto end also Prompt GPT-3.5 depends on the two smaller loops but ChatGPT does not There is a program in OpenSSL `crypto/bn/bn_sqrt.c`. The `goto end` statement can be reached in the Variables x, y, b, p, t are big integers. BN_mod_mul(r, a, following situations: provide insights on that. b, m, ctx) multiplies a by b and finds the non-negative - If there is an error in the execution of one of the `BN_` remainder respective to modulus m ("r=(a*b) mod m"). functions, causing them to return 0 or NULL. BN_mod_sqr(r, a, b, m, ctx) takes the square of a - If `i` becomes equal to `e`, which indicates that the From the case study, we find that ChatGPT originally is modulo m and places the result in r. BN_is_one(a) value of `b` is not a square. In this case, the function checks whether a == 1. BN_copy(from, to) copies `from` raises an error using the OpenSSL ERR_raise function hardtoresolvecomplicatedcontrolflowssuchasloops.Fu- to `to`, returns `to` if success, NULL on error. and then goes to the end of the loop with `goto end`. while (1) { - Otherwise, the loop continues. ture improvements or system support is needed to integrate if (BN_is_one(b)) { Description of missed if (!BN_copy(ret, x)) variable definitions and The boolean expression that determines when the ChatGPT in large-scale real-world symbolic execution. goto end; used APIs in code `goto end` statement will be executed is: err = 0; } goto vrfy; ( p! ,B N c_ ti xs )_ o |n |e ( !Bb N) _) m o& d& _ s( q( ri ( t= ,= te ,) p| ,| c!B tN x_ )m o |d |_ s !Bq Nr( _t c, o pt y(, t , 11. Fuzzing /* find smallest i such that b^(2^i) = 1 */ y) || !BN_mod_sqr(t, t, p, ctx) || !BN_mod_mul(y, i = 1; t, t, p, ctx) || !BN_mod_mul(x, x, t, p, ctx) || if (!BN_mod_sqr(t, b, p, ctx)) !BN_mod_mul(b, b, y, p, ctx)) Fuzzing is an effective software testing technique that goto end; while (!BN_is_one(t)) { GPT-4 entails supplying programs with invalid, unexpected, or ii f+ + (; i == e) { T wh he e n`g ao nto e e rrn od r ` o s ct ca ute rsm de un rt is n gin s t oh me ec o od pe e ra ar te io e nx se . c Tu ht ee sd e random data inputs to identify vulnerabilities and bugs. ERR_raise(ERR_LIB_BN,BN_R_NOT_A_SQUARE); errors can happen during the following operations: The fundamental concept behind fuzzing is to stress-test a goto end; 1. `BN_copy(ret, x)` fails in the if block where } BN_is_one(b) is checked. program by inundating it with a large volume of diverse if (!BN_mod_mul(t, t, t, p, ctx)) 2. `BN_mod_sqr(t, b, p, ctx)` fails in the initial goto end; assignment to t. input data, thereby uncovering defects that may remain } 3. `BN_mod_mul(t, t, t, p, ctx)` fails in the loop where t /* t := y^2^(e - i - 1) */ is updated. undetected by conventional testing approaches. if (!BN_copy(t, y)) 4. `BN_copy(t, y)` fails before the loop for calculating f o r g i(o fj t (o = ! Be e Nn _d - m; oi d _- s 1 q; r( tj , > t 0 ,; pj ,- - c) t x{ )) y 5 c 6^ a. . 2 l` `cB B^ u( N Ne la_ _ t- m mi ni go o- d d1 y_ _) ^. s m2q ^ ur (( le (t y , - ,t , i t ,-p t, 1 , c ) p.t ,x c)` t xf )a `i l fs a ii ln s t ah fe te l ro to hp e f lo or o p for clasT seh se : te mc uh tn ai tq iou ne -bo af sf eu dzz ain ng dco gu enld erb ae tioc na -t beg ao seri dz .ed Mi un tt ao tit ow no - goto end; calculating y^2^(e - i - 1). } 7. `BN_mod_mul(x, x, t, p, ctx)` fails after updating y. basedfuzzing[139],[140],[141],[142],[143]involvestak- if (!BN_mod_mul(y, t, t, p, ctx)) 8. `BN_mod_mul(b, b, y, p, ctx)` fails after updating x. goto end; Therefore, the boolean expression indicating that the ing existing input data and making small, random changes if (!BN_mod_mul(x, x, t, p, ctx)) program will reach `goto end` is: goto end; to it to create new test cases. By scheduling seed test if (!BN_mod_mul(b, b, y, p, ctx)) (BN_is_one(b) && !BN_copy(ret, x)) || goto end; !BN_mod_sqr(t, b, p, ctx) || (!BN_is_one(t) && cases and mutation operators, such fuzzing tools aim to e = i; (!BN_mod_mul(t, t, t, p, ctx) || !BN_copy(t, y) || } !BN_mod_sqr(t, t, p, ctx) || !BN_mod_mul(y, t, t, produce interesting test cases efficiently. Generation-based
A toft e dr e e ten rt mer ii nn eg it nhe w w hh ai tle s l io tuo ap t, i oru nn s s thy em pb ro oli gc r ae mxe wcu ilt li on p !B, N _c mt ox d) _ m| u| l (!B bN ,_ m bo ,d _ ym ,u l p( ,x , c tx x, ) )t ), p, ctx) || fuzzing [139], [140], [144], [145], [146], [147] is aware of reach `goto end`. Returns the boolean expression. the structure of the valid test cases. This is very useful Figure 16: Solving symbolic execution problems on real- when the subject software only accepts data in certain world software. formats, such as PDF readers and compilers. Generation- basedfuzzingeffectivelyavoidstestcasesininvalidformats execution path to the failure state. GPT-4 answers “(2 * y thussavingtimeformoreusefultests.Inaddition,thereare == x) AND (x > y + 10)”, which is slightly conciser than also hybrid fuzzers [139], [140], [148], [149] that leverage CPT-3.5’s answer “(2 * y == x) and not(x ≤ y + 10)”. multiple fuzzing techniques. In summary, ChatGPT demonstrates impressive capa- Existing fuzzing tools demonstrate great success in dis- bility in reasoning program control flows, though wrong coveringsoftwarevulnerabilities.AFL[150],AFL++[151], reasoninghappenssometimes.Usingproperpromptspoten- libfuzzer [152] are examples of the most popular automatic tially make the responses conciser and more accurate. fuzzing tools, which have revealed thousands of software Real-worldscenariosofsymbolicexecution.Tofurther vulnerabilities in widely used projects [153]. Previous re- evaluate ChatGPT’s capability in real-world scenarios, we search keeps improving fuzzing by designing intelligent construct a symbolic execution task from CVE-2022-0778, scheduling of seeds or mutation, aiming to efficiently cover a real vulnerability of OpenSSL. In this vulnerability case, buggy or vulnerable execution paths in the large code if a non-prime modulus is passed in BN mod sqrt as a base [154]. Recently, researchers find that LLMs can assist variable, it triggers an infinite loop thus a denial-of-service fuzzing process using its strong ability of generating source (DoS). Since a special input triggers a specific vulnerable code. TitanFuzz [35], for instance, use a LLM to generate execution path, symbolic execution is a good fit to discover deep-learning related code to reveal vulnerabilities in deep such vulnerability. learninglibrariessuchasTorch[155]andTensorflow[156]. As shown in fig. 16, we ask ChatGPT for the condition ChatGPT as one of the state-of-art LLMs also has the on input variables that can make the loop (the given code) potential to tackle with fuzzing challenges. In this section, stop safely (goto end). In addition, we add a description of we study ChatGPT’s capability in fuzzing involving both input variables and APIs used in the code piece. Without mutation-based and generation-based fuzzing scenarios. the description, ChatGPT can hardly understand the whole Mutation-based fuzzing. In conventional mutation- code as the definitions of variables and function calls are based fuzzing, a set of mutation operators are pre-defined not involved in the prompt. ChatGPT can generally identify and a set of seed test cases is updated at runtime. For the key IF conditions which are control dependents of instance, if the seed test case is a string “Hello, world!”, the sink statements goto end. However, when calculating the fuzzing process may change one byte in the string to the final Boolean expression, it simply concatenates these produce new test cases like “Hell@, world!”. However, IF conditions without considering the loop execution. For the implementation of the mutation could be expensive in instance, inside the original WHILE, there is another one human effort. ChatGPT may be able to automate such a WHILE loop with local counter i and one FOR loop with process given a simple description.ChatGPT with either GPT-3.5 or GPT-4 can generate Prompt GPT-3.5 GPT-4 Iteration 0: Iteration 0: Iteration 0: validPDFtestcases.However,GPT-3.5andGPT-4seemto I f uw na cn t R ey vo eu r sto e (d so sm tru ita nt gio ) n s-b tra is ne gd {fuzzing on the following function in Go. hellyo, world H@ello, world focus on different aspects in terms of the diversity of PDF b := []byte(s) Iteration 1: Iteration 1: f o r i b, [ ij ] ,: = b [0 j, ] l =e n b( [b j) ]- ,1 ; b [i i ]< len(b)/2; i, j = i+1, j-1 { HeLlo, world HeLlo, world files. ChatGPT with GPT-3.5 generates PDF files with dif- r} eturn string(b) Iteration 2: Iteration 2: ferent appearance, e.g., changing the location of text blocks } Hello, world! Hello, world! T chh ae r ,s ae ne dd ais p p"H ene dllo in, gw oo nrl ed " c. hM au r t aa t t ao nrs y ein nc dlu od fe t hin es se tr rt ii nn gg . o Cn oe n c sh ida er, r r ae llp pla oc se s io bn lee Iteration 3: Iteration 3: or increasing the number of pages. Instead, ChatGPT with special characters. Hello, xworld Hel*lo, world GPT-4 intends to generate PDF files with errors in certain G nee en de era dt .e the next test input. Returns the test input only. No explanation is Iteration 4: Iteration 4: sections, such as false entries in the “trailer” dictionary dlrow ,olleH Hell&o, world Iteration 1+: Iteration 5: Iteration 5: and wrong “startref” value. GPT-4 also provides a detailed Generate the next test input. Returns the test input only. No explanation is needed. Hello, 世界 Hello, world# descriptionoftheerrorsitinjected.Incomparison,generated
Figure 17: Make ChatGPT performs like a mutation-based testcasesfromGPT-4aremorevaluableforfuzzingasthey fuzzer. Tested on a simple Go function. contain intentional errors that may fail PDF parsing. GPT- 4 in general demonstrates a stronger understanding of the Prompt GPT-3.5 GPT-4 Iteration 0: (Shown produced PDFs rendered by Chrome.) (Shown produced PDFs rendered by Chrome.) security context of fuzzing. I G a em ne f ru az tz ei n ag t ea s P t D inF p ur te .ader. Iteration 0: (One page with Iteration 0: ( PO Dn Fe Fp ua zg ze in w gi !t ”h . “Hello, Towards closed loop fuzzing. From the above re- I Gte er na eti ro an te 1 a+ n: other test input. “Hello, World!”) x R hr aee vsf e, o s u int r ta c er e nt sx tio r se nef a ca lt in eod rn r os rs) sults, ChatGPT especially the GPT-4 version demonstrates Iteration 1: Iteration 1: (The same page. a strong capability in generating test cases for fuzzing. ( “T Tw hio s p isa pg ae gs e, e xa xc ”)h with s int fr oe a sm ec, ts iot na srt x hr ae vf e a nd However, fuzzing is a closed loop process involving the intentional errors) feedback from the execution environment, the optimization Iteration 2: Iteration 2: ( W thO eon re bld op ! t”a t. o g T me h ) ew i sth tr i“ nH ge il slo a, t ( t R hT r aa eh vi se l ee o s r u in,a r tsm c et e ne a s t r ip o t sxa nerg acee lt f i. e oa rn rn osd r s) o lef vs ee le cd hs ac llh ee nd gu el si .ng Thb oa use gd ho pn owth ee rff uee l,d Cba hc ak tG,a Pn Td ao sth aer tes xy tst pe rm o- - Figure18:MakeChatGPTperformslikeageneration-based cessor cannot fabricate the whole fuzzing process alone. It fuzzer that tests PDF readers. is a future research direction to integrate concrete system components with the generation capability of ChatGPT. As shown in fig. 17, we provide ChatGPT with the 12. Conclusion and Future Work source code to test, a predefined seed test case, and a set of mutation operators. Then we ask ChatGPT to generate a Basedonextensiveexperimentsandthoroughcasestud- testcaseforthesourcecode.Afterobtainingresponsesfrom ies, it is clear that ChatGPT, especially when powered ChatGPT, we repeat the request of test case generation for by the remarkable GPT-4, exhibits exceptional potential in multiple iterations, similar to how a fuzzer works. assistingwithawiderangeofsoftwaresecuritytasks.These Fromtheresults,ChatGPTwitheitherGPT-3.5orGPT- tasks include but are not limited to vulnerability detection, 4 has sufficient capability to perform the fuzzing process. vulnerabilityrepair,bugfixing,patching,debloating,decom- It can understand the concept of mutation-based fuzzing, piling,rootcauseanalysis,symbolicexecution,andfuzzing. including “seeds” and “motators”. ChatGPT is also aware Notably, ChatGPT and GPT models demonstrate strong of the meaning of mutations, such as byte manipulations. proficiency in processing source code, and they even ex- For example, when the seed is “Hello, world”, ChatGPT hibitpromisingcapabilitiesinprocessingdisassemblycode. can produce test cases such as “hellyo, world” by injecting Moreover, ChatGPT excels in human interaction, adapting bytes and “HeLlo, world” by replacing a byte. its responses based on user-provided task descriptions. The However, ChatGPT can hardly enforce hard constraints impressive performance of GPT-4 surpasses that of GPT- on the mutation process, which means it may apply muta- 3.5 across most software security tasks, highlighting the tions that are out of the definition of mutation operators. continual advancements made in large language models. For instance, ChatGPT with GPT-3.5 produces a test case An intriguing finding is ChatGPT’s ability to handle by replacing “world” with its Chinese translation, which is complex data beyond traditional source code. In the task outofthepre-definedsetofmutators.Incontrast,ChatGPT ofdecompilation,ChatGPTshowcasesthecapacitytoaccu- with GPT-4 obeys the mutation rules as far as we see in the rately transform disassembly code back into C source code, example,demonstratingastrongercapabilityofunderstand- surpassing the capability of IDA Pro. Additionally, in the ing mutation-related requirements. domain of generation-based fuzzing, ChatGPT successfully Generation-based fuzzing. Generation-based fuzzing generates random benign or buggy PDF files, which can emphasizes the capability of enforcing generated test cases be correctly rendered and displayed. These findings provide to be compliant with certain data formats or grammar rules. strongmotivationforfuturesecurityresearchtoembracethe Conventionally, this is implemented by using a pre-defined integration of LLMs in more intricate tasks. specificationorgrammar.ChatGPTisbuiltonLLMwhichis It is worth noting that while ChatGPT shows promise, trainedonthevastamountofcorpusthusithasthepotential its performance still falls short compared to established to understand complex grammar. conventionalmethodsinscalability,especiallywhendealing As shown in fig. 18, we ask ChatGPT to perform withlargedatavolumes.TheresourcecomsuptionofLLMs fuzzing on a PDF reader, expecting it to produce PDF files increases significantly as the size of input increases, which thatmaytriggerinternalerrorsinthePDFreader.Werepeat make it difficult to handle software projects with at least a
the request to obtain multiple generated test cases. few thousand lines of code. Real-world security challengesoften involve system-level information, such as computer [17] S.Frieder,L.Pinchetti,R.-R.Griffiths,T.Salvatori,T.Lukasiewicz, architecture and network specifics, which presents diffi- P.C.Petersen,A.Chevalier,andJ.Berner,“Mathematicalcapabil- culties in conveying such information effectively through itiesofchatgpt,”arXivpreprintarXiv:2301.13867,2023. textualsequencestoChatGPT.Additionally,ChatGPTlacks [18] S. Biswas, “Role of chatgpt in gaming: According to chatgpt,” the ability to comprehend binary code, further contributing AvailableatSSRN4375510,2023. to its limitations. Nevertheless, addressing these challenges [19] C.F.Tsai,X.Zhou,S.S.Liu,J.Li,M.Yu,andH.Mei,“Canlarge languagemodelsplaytextgameswell?currentstate-of-the-artand through future research holds significant promise. openquestions,”arXivpreprintarXiv:2304.02868,2023. While our study demonstrates valuable insights, we ac- [20] M. Sallam, “Chatgpt utility in healthcare education, research, and knowledge potential threats to validity. Due to the absence practice:systematicreviewonthepromisingperspectivesandvalid of benchmark datasets, we focused on simple yet represen- concerns,”inHealthcare,vol.11,no.6. MDPI,2023,p.887. tative cases for our case studies, except for vulnerability [21] M.Zheng,X.Su,S.You,F.Wang,C.Qian,C.Xu,andS.Albanie, detection/repair and bug fixing. Future work should extend “Can gpt-4 perform neural architecture search?” arXiv preprint these case studies to encompass comprehensive evaluations arXiv:2304.10970,2023. using larger and more diverse benchmark datasets. [22] J.H.Choi,K.E.Hickman,A.Monahan,andD.Schwarcz,“Chatgpt goestolawschool,”AvailableatSSRN,2023. References [23] M. Ryznar, “Exams in the time of chatgpt,” Washington and Lee LawReviewOnline,vol.80,no.5,p.305,2023. [1] D. E. Rumelhart, G. E. Hinton, and R. J. Williams, “Learning [24] P.M.Newton,“Chatgptperformanceonmcq-basedexams,”2023. representations by back-propagating errors,” nature, vol. 323, no. [25] Y.Bang,S.Cahyawijaya,N.Lee,W.Dai,D.Su,B.Wilie,H.Love- 6088,pp.533–536,1986. nia, Z. Ji, T. Yu, W. Chung et al., “A multitask, multilingual, [2] ——,“Learninginternalrepresentationsbyerrorpropagation,”Cal- multimodal evaluation of chatgpt on reasoning, hallucination, and ifornia Univ San Diego La Jolla Inst for Cognitive Science, Tech. interactivity,”arXivpreprintarXiv:2302.04023,2023. Rep.,1985. [26] A.Borji,“Acategoricalarchiveofchatgptfailures,”arXivpreprint [3] M. I. Jordan, “Serial order: A parallel distributed processing ap- arXiv:2302.03494,2023. proach,”inAdvancesinpsychology. Elsevier,1997,vol.121,pp. [27] Y. Dong, X. Jiang, Z. Jin, and G. Li, “Self-collaboration code 471–495. generationviachatgpt,”arXivpreprintarXiv:2304.07590,2023. [4] S.HochreiterandJ.Schmidhuber,“Longshort-termmemory,”Neu- [28] H.Tian,W.Lu,T.O.Li,X.Tang,S.-C.Cheung,J.Klein,andT.F. ralcomputation,vol.9,no.8,pp.1735–1780,1997. Bissyande´,“Ischatgpttheultimateprogrammingassistant–howfar [5] A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. isit?”arXivpreprintarXiv:2304.11938,2023. Gomez, Ł. Kaiser, and I. Polosukhin, “Attention is all you need,” [29] J.Liu,C.S.Xia,Y.Wang,andL.Zhang,“Isyourcodegeneratedby Advancesinneuralinformationprocessingsystems,vol.30,2017. chatgptreallycorrect?rigorousevaluationoflargelanguagemodels [6] A. Radford, K. Narasimhan, T. Salimans, I. Sutskever et al., “Im- forcodegeneration,”arXivpreprintarXiv:2305.01210,2023. provinglanguageunderstandingbygenerativepre-training,”2018. [30] R.Khoury,A.R.Avila,J.Brunelle,andB.M.Camara,“Howsecure [7] A.Radford,J.Wu,R.Child,D.Luan,D.Amodei,I.Sutskeveretal., is code generated by chatgpt?” arXiv preprint arXiv:2304.09655, “Language models are unsupervised multitask learners,” OpenAI 2023. blog,vol.1,no.8,p.9,2019. [31] H.Pearce,B.Ahmad,B.Tan,B.Dolan-Gavitt,andR.Karri,“Asleep [8] T.Brown,B.Mann,N.Ryder,M.Subbiah,J.D.Kaplan,P.Dhari- at the keyboard? assessing the security of github copilot’s code wal, A. Neelakantan, P. Shyam, G. Sastry, A. Askell et al., “Lan- contributions,” in 2022 IEEE Symposium on Security and Privacy guagemodelsarefew-shotlearners,”Advancesinneuralinformation (SP). IEEE,2022,pp.754–768. processingsystems,vol.33,pp.1877–1901,2020. [32] H.Pearce,B.Tan,B.Ahmad,R.Karri,andB.Dolan-Gavitt,“Ex-
[9] OpenAI,“Gpt-4technicalreport,”2023. aminingzero-shotvulnerabilityrepairwithlargelanguagemodels,” [10] “Introducing chatgpt - open ai,” 2023. [Online]. Available: in 2023 IEEE Symposium on Security and Privacy (SP). IEEE https://openai.com/blog/chatgpt ComputerSociety,2022,pp.1–18. [11] M.Aljanabi,M.Ghazi,A.H.Ali,S.A.Abedetal.,“Chatgpt:Open [33] D. Sobania, M. Briesch, C. Hanna, and J. Petke, “An analysis of possibilities,”IraqiJournalForComputerScienceandMathematics, the automatic bug fixing performance of chatgpt,” arXiv preprint vol.4,no.1,pp.62–64,2023. arXiv:2301.08653,2023. [12] R.Gozalo-BrizuelaandE.C.Garrido-Merchan,“Chatgptisnotall [34] C.S.XiaandL.Zhang,“Conversationalautomatedprogramrepair,” you need. a state of the art review of large generative ai models,” arXivpreprintarXiv:2301.13246,2023. arXivpreprintarXiv:2301.04655,2023. [35] Y. Deng, C. S. Xia, H. Peng, C. Yang, and L. Zhang, “Fuzzing [13] Y. Liu, T. Han, S. Ma, J. Zhang, Y. Yang, J. Tian, H. He, A. Li, deep-learning libraries via large language models,” arXiv preprint M. He, Z. Liu et al., “Summary of chatgpt/gpt-4 research and arXiv:2212.14834,2022. perspective towards the future of large language models,” arXiv [36] L.Ouyang,J.Wu,X.Jiang,D.Almeida,C.Wainwright,P.Mishkin, preprintarXiv:2304.01852,2023. C.Zhang,S.Agarwal,K.Slama,A.Rayetal.,“Traininglanguage [14] S. Bubeck, V. Chandrasekaran, R. Eldan, J. Gehrke, E. Horvitz, models to follow instructions with human feedback,” Advances in E. Kamar, P. Lee, Y. T. Lee, Y. Li, S. Lundberg et al., “Sparks of NeuralInformationProcessingSystems,vol.35,pp.27730–27744, artificialgeneralintelligence:Earlyexperimentswithgpt-4,”arXiv 2022. preprintarXiv:2303.12712,2023. [37] P. F. Christiano, J. Leike, T. Brown, M. Martic, S. Legg, and [15] A.Azaria,“Chatgptusageandlimitations,”2022. D.Amodei,“Deepreinforcementlearningfromhumanpreferences,” Advancesinneuralinformationprocessingsystems,vol.30,2017. [16] P. Maddigan and T. Susnjak, “Chat2vis: Generating data visuali- sations via natural language using chatgpt, codex and gpt-3 large [38] A.Cheshkov,P.Zadorozhny,andR.Levichev,“Evaluationofchat- languagemodels,”IEEEAccess,2023. gptmodelforvulnerabilitydetection,”2023.[39] “Github copilot · your ai pair programmer,” https://copilot.github. [60] X. Li, L. Wang, Y. Xin, Y. Yang, and Y. Chen, “Automated vul- com/,2023. nerability detection in source code using minimum intermediate representation learning,” Applied Sciences, vol. 10, no. 5, p. 1692, [40] Z.Yang,L.Li,J.Wang,K.Lin,E.Azarnasab,F.Ahmed,Z.Liu, 2020. C.Liu,M.Zeng,andL.Wang,“Mm-react:Promptingchatgptfor multimodalreasoningandaction,”arXivpreprintarXiv:2303.11381, [61] R.Russell,L.Kim,L.Hamilton,T.Lazovich,J.Harer,O.Ozdemir, 2023. P. Ellingwood, and M. McConley, “Automated vulnerability detec- tioninsourcecodeusingdeeprepresentationlearning,”in201817th [41] C.Wu,S.Yin,W.Qi,X.Wang,Z.Tang,andN.Duan,“Visualchat- IEEEinternationalconferenceonmachinelearningandapplications gpt: Talking, drawing and editing with visual foundation models,” (ICMLA). IEEE,2018,pp.757–762. arXivpreprintarXiv:2303.04671,2023. [62] M. Zagane, M. K. Abdi, and M. Alenezi, “Deep learning for [42] E.Chen,R.Huang,H.-S.Chen,Y.-H.Tseng,andL.-Y.Li,“Gptutor: softwarevulnerabilitiesdetectionusingcodemetrics,”IEEEAccess, a chatgpt-powered programming tool for code explanation,” arXiv vol.8,pp.74562–74570,2020. preprintarXiv:2305.01863,2023. [63] X.Li,L.Wang,Y.Xin,Y.Yang,Q.Tang,andY.Chen,“Automated [43] J. S. Park, J. C. O’Brien, C. J. Cai, M. R. Morris, P. Liang, and software vulnerability detection based on hybrid neural network,” M.S.Bernstein,“Generativeagents:Interactivesimulacraofhuman AppliedSciences,vol.11,no.7,p.3201,2021. behavior,”arXivpreprintarXiv:2304.03442,2023. [64] Y.Mirsky,G.Macon,M.Brown,C.Yagemann,M.Pruett,E.Down- [44] Y. Feng, S. Vanam, M. Cherukupally, W. Zheng, M. Qiu, and ing,S.Mertoguno,andW.Lee,“Vulchecker:Graph-basedvulnera- H. Chen, “Investigating code generation performance of chat-gpt bilitylocalizationinsourcecode.” with crowdsourcing social data,” in Proceedings of the 47th IEEE [65] P.Black,“Sard:Asoftwareassurancereferencedataset,”1970. ComputerSoftwareandApplicationsConference,2023,pp.1–10. [66] “CWE - Common Vulnerability Enumeration,” https://cwe.mitre. [45] C.Liu,X.Bao,H.Zhang,N.Zhang,H.Hu,X.Zhang,andM.Yan, org/,2023. “Improving chatgpt prompt for code generation,” arXiv preprint
[67] D. L. Olson and D. Delen, Advanced data mining techniques. arXiv:2305.08360,2023. SpringerScience&BusinessMedia,2008. [46] D. Baidoo-Anu and L. Owusu Ansah, “Education in the era of [68] D. M. Powers, “Evaluation: from precision, recall and f-measure generative artificial intelligence (ai): Understanding the potential to roc, informedness, markedness and correlation,” arXiv preprint benefits of chatgpt in promoting teaching and learning,” Available arXiv:2010.16061,2020. atSSRN4337484,2023. [69] Z. Xu,Y. Zhang, L.Zheng, L. Xia,C. Bao,Z. Wang, andY. Liu, [47] S.S.Biswas,“Potentialuseofchatgptinglobalwarming,”Annals “Automatichotpatchgenerationforandroidkernels,”inProceedings ofbiomedicalengineering,vol.51,no.6,pp.1126–1127,2023. ofthe29thUSENIXConferenceonSecuritySymposium,2020,pp. [48] C. S. Xia, Y. Wei, and L. Zhang, “Automated program repair in 2397–2414. the era of large pre-trained language models,” in Proceedings of [70] N. Christou, D. Jin, V. Atlidakis, B. Ray, and V. P. Kemerlis, the 45th International Conference on Software Engineering (ICSE “Ivysyn:Automatedvulnerabilitydiscoveryfordeeplearningframe- 2023).AssociationforComputingMachinery,2023. works,”arXivpreprintarXiv:2209.14921,2022. [49] C. S. Xia and L. Zhang, “Keep the conversation going: Fixing [71] C. Mulliner, J. Oberheide, W. Robertson, and E. Kirda, “Patch- 162 out of 337 bugs for $0.42 each using chatgpt,” arXiv preprint droid: Scalable third-party security patches for android devices,” arXiv:2304.00385,2023. inProceedingsofthe29thAnnualComputerSecurityApplications Conference,2013,pp.259–268. [50] M.Jin,S.Shahriar,M.Tufano,X.Shi,S.Lu,N.Sundaresan,and A. Svyatkovskiy, “Inferfix: End-to-end program repair with llms,” [72] J. Arnold and M. F. Kaashoek, “Ksplice: Automatic rebootless 2023. kernelupdates,”inProceedingsofthe4thACMEuropeanconference onComputersystems,2009,pp.187–198. [51] Y.Deng,C.S.Xia,C.Yang,S.D.Zhang,S.Yang,andL.Zhang, “Largelanguagemodelsareedge-casefuzzers:Testingdeeplearning [73] R.Duan,A.Bijlani,Y.Ji,O.Alrawi,Y.Xiong,M.Ike,B.Saltafor- librariesviafuzzgpt,”2023. maggio, and W. Lee, “Automating patching of vulnerable open- sourcesoftwareversionsinapplicationbinaries.”inNDSS,2019. [52] J. Hu, Q. Zhang, and H. Yin, “Augmenting greybox fuzzing with generativeai,”2023. [74] P.E.BlackandP.E.Black,Juliet1.3testsuite:Changesfrom1.2. US Department of Commerce, National Institute of Standards and [53] C. Ko, G. Fink, and K. Levitt, “Automated detection of vulnera- Technology,2018. bilities in privileged programs by execution monitoring,” in Tenth [75] The OpenSSL Project, “OpenSSL: The open source toolkit for AnnualComputerSecurityApplicationsConference. IEEE,1994, SSL/TLS,”April2003,www.openssl.org. pp.134–144. [76] A. Ghanbari, S. Benton, and L. Zhang, “Practical program repair [54] Y. Xiao, B. Chen, C. Yu, Z. Xu, Z. Yuan, F. Li, B. Liu, Y. Liu, viabytecodemutation,”inProceedingsofthe28thACMSIGSOFT W.Huo,W.Zouetal.,“Mvp:Detectingvulnerabilitiesusingpatch- International Symposium on Software Testing and Analysis, 2019, enhancedvulnerabilitysignatures.”inUSENIXSecuritySymposium, pp.19–30. 2020,pp.1165–1182. [77] J. Hua, M. Zhang, K. Wang, and S. Khurshid, “Sketchfix: a tool [55] D.R.Jeong,K.Kim,B.Shivakumar,B.Lee,andI.Shin,“Razzer: for automated program repair approach using lazy candidate gen- Findingkernelracebugsthroughfuzzing,”in2019IEEESymposium eration,” in Proceedings of the 2018 26th ACM Joint Meeting on onSecurityandPrivacy(SP). IEEE,2019,pp.754–768. EuropeanSoftwareEngineeringConferenceandSymposiumonthe [56] “CodeQLDocumentation,”https://codeql.github.com/docs/,2023. FoundationsofSoftwareEngineering,2018,pp.888–891. [57] “Inferstaticanalyzer,”https://fbinfer.com/docs,2023. [78] K.Liu,A.Koyuncu,D.Kim,andT.F.Bissyande´,“Tbar:Revisiting template-based automated program repair,” in Proceedings of the [58] “Clangstaticanalyzer,”https://clang-analyzer.llvm.org/,2023. 28thACMSIGSOFTInternationalSymposiumonSoftwareTesting andAnalysis,2019,pp.31–42. [59] S. Hu, Q. A. Chen, J. Sun, Y. Feng, Z. M. Mao, and H. X. Liu, “Automated discovery of denial-of-service vulnerabilities in [79] M. Martinez and M. Monperrus, “Astor: A program repair library connectedvehicleprotocols.”inUSENIXSecuritySymposium,2021, for java,” in Proceedings of the 25th International Symposium on pp.3219–3236. SoftwareTestingandAnalysis,2016,pp.441–444.[80] F. Long and M. Rinard, “Staged program repair with condition [97] M. Attariyan, M. Chow, and J. Flinn, “X-ray: Automating root- synthesis,”inProceedingsofthe201510thJointMeetingonFoun- causediagnosisofperformanceanomaliesinproductionsoftware,” dationsofSoftwareEngineering,2015,pp.166–178. inPresentedaspartofthe10th{USENIX}SymposiumonOperating
Systems Design and Implementation ({OSDI} 12), 2012, pp. 307– [81] F.DeMarco,J.Xuan,D.LeBerre,andM.Monperrus,“Automatic 320. repairofbuggyifconditionsandmissingpreconditionswithsmt,” inProceedingsofthe6thinternationalworkshoponconstraintsin [98] W.Cui,X.Ge,B.Kasikci,B.Niu,U.Sharma,R.Wang,andI.Yun, softwaretesting,verification,andanalysis,2014,pp.30–39. “{REPT}: Reverse debugging of failures in deployed software,” [82] Z.Chen,S.Kommrusch,M.Tufano,L.-N.Pouchet,D.Poshyvanyk, in 13th {USENIX} Symposium on Operating Systems Design and andM.Monperrus,“Sequencer:Sequence-to-sequencelearningfor Implementation({OSDI}18),2018,pp.17–32. end-to-end program repair,” IEEE Transactions on Software Engi- [99] W.Cui,M.Peinado,S.K.Cha,Y.Fratantonio,andV.P.Kemerlis, neering,vol.47,no.9,pp.1943–1959,2019. “Retracer:Triagingcrashesbyreverseexecutionfrompartialmem- [83] Y. Li, S. Wang, and T. N. Nguyen, “Dlfix: Context-based code orydumps,”inProceedingsofthe38thInternationalConferenceon transformationlearningforautomatedprogramrepair,”inProceed- SoftwareEngineering,2016,pp.820–831. ings of the ACM/IEEE 42nd International Conference on Software [100] J.Xu,D.Mu,X.Xing,P.Liu,P.Chen,andB.Mao,“Postmortem Engineering,2020,pp.602–614. program analysis with hardware-enhanced post-crash artifacts.” in [84] H. Ye, M. Martinez, and M. Monperrus, “Neural program repair USENIXSecuritySymposium,2017,pp.17–32. withexecution-basedbackpropagation,”inProceedingsofthe44th [101] P. Reiter, H. J. Tay, W. Weimer, A. Doupe´, R. Wang, and S. For- InternationalConferenceonSoftwareEngineering,2022,pp.1506– rest, “Automatically mitigating vulnerabilities in x86 binary pro- 1518. grams via partially recompilable decompilation,” arXiv preprint [85] Q. Zhu, Z. Sun, Y.-a. Xiao, W. Zhang, K. Yuan, Y. Xiong, and arXiv:2202.12336,2022. L.Zhang,“Asyntax-guidededitdecoderforneuralprogramrepair,” [102] A.Mantovani,L.Compagna,Y.Shoshitaishvili,andD.Balzarotti, inProceedingsofthe29thACMJointMeetingonEuropeanSoftware “The convergence of source code and binary vulnerability Engineering Conference and Symposium on the Foundations of discovery–acasestudy,”inProceedingsofthe2022ACMonAsia SoftwareEngineering,2021,pp.341–353. Conference on Computer and Communications Security, 2022, pp. [86] D. Lin, J. Koppel, A. Chen, and A. Solar-Lezama, “Quixbugs: A 602–615. multi-lingual program repair benchmark set based on the quixey [103] F. Verbeek, P. Olivier, and B. Ravindran, “Sound c code decom- challenge,”inProceedingsCompanionofthe2017ACMSIGPLAN pilation for a subset of x86-64 binaries,” in Software Engineering internationalconferenceonsystems,programming,languages,and and Formal Methods: 18th International Conference, SEFM 2020, applications:softwareforhumanity,2017,pp.55–56. Amsterdam,TheNetherlands,September14–18,2020,Proceedings [87] M. Monperrus, “Automatic software repair: a bibliography,” ACM 18. Springer,2020,pp.247–264. ComputingSurveys(CSUR),vol.51,no.1,pp.1–24,2018. [104] E. J. Schwartz, J. Lee, M. Woo, and D. Brumley, “Native x86 [88] Y. Shi, Y. Zhang, T. Luo, X. Mao, Y. Cao, Z. Wang, Y. Zhao, decompilation using semantics-preserving structural analysis and Z.Huang,andM.Yang,“Backportingsecuritypatchesofwebap- iterative control-flow structuring,” in Proceedings of the USENIX plications:Aprototypedesignandimplementationoninjectionvul- SecuritySymposium,vol.16,2013. nerability patches,”in 31st USENIXSecurity Symposium (USENIX Security22),2022,pp.1993–2010. [105] R. R. Branco, G. N. Barbosa, and P. D. Neto, “Scientific but not academical overview of malware anti-debugging, anti-disassembly [89] S. Sidiroglou and A. D. Keromytis, “Countering network worms and anti-vm technologies,” Black Hat, vol. 1, no. 2012, pp. 1–27, through automatic patch generation,” IEEE Security & Privacy, 2012. vol.3,no.6,pp.41–49,2005. [106] E. Schulte, J. Ruchti, M. Noonan, D. Ciarletta, and A. Loginov, [90] M. Martinez and M. Monperrus, “Mining software repair models “Evolving exact decompilation,” in Workshop on Binary Analysis for reasoning on the search space of automated program fixing,” Research(BAR),2018. EmpiricalSoftwareEngineering,vol.20,pp.176–205,2015. [107] Hex-Rays, “Hex-rays,” 2022. [Online]. Available: https://www. [91] D.Kim,J.Nam,J.Song,andS.Kim,“Automaticpatchgeneration hex-rays.com/decompiler/ learned from human-written patches,” in 2013 35th International ConferenceonSoftwareEngineering(ICSE). IEEE,2013,pp.802– [108] “Leetcode,”2023.[Online].Available:https://leetcode.com/ 811. [109] J. Lacomis, P. Yin, E. Schwartz, M. Allamanis, C. Le Goues, [92] S.Ma,F.Thung,D.Lo,C.Sun,andR.H.Deng,“Vurle:Automatic G. Neubig, and B. Vasilescu, “Dire: A neural approach to de- vulnerability detection and repair by learning from examples,” in compiledidentifiernaming,”in201934thIEEE/ACMInternational
ComputerSecurity–ESORICS2017:22ndEuropeanSymposiumon Conference on Automated Software Engineering (ASE). IEEE, Research in Computer Security, Oslo, Norway, September 11-15, 2019,pp.628–639. 2017,Proceedings,PartII22. Springer,2017,pp.229–246. [110] Q.Chen,J.Lacomis,E.J.Schwartz,C.LeGoues,G.Neubig,and [93] C.Yagemann,M.Pruett,S.P.Chung,K.Bittick,B.Saltaformaggio, B.Vasilescu,“Augmentingdecompileroutputwithlearnedvariable and W. Lee, “Arcus: Symbolic root cause analysis of exploits in names and types,” in 31st USENIX Security Symposium (USENIX production systems.” in USENIX Security Symposium, 2021, pp. Security22),2022,pp.4327–4343. 1989–2006. [111] “Llvm commandline guide.” 2023. [Online]. Available: https: [94] M. Musuvathi, S. Qadeer, T. Ball, G. Basler, P. A. Nainar, and //llvm.org/docs/CommandGuide/llvm-cov.html I. Neamtiu, “Finding and reproducing heisenbugs in concurrent programs.”inOSDI,vol.8,no.2008,2008. [112] “Sqlite,”2023.[Online].Available:https://www.sqlite.org/ [95] I.Ahmed,N.Mohan,andC.Jensen,“Theimpactofautomaticcrash [113] “Eglibc,”2023.[Online].Available:http://www.eglibc.org/home reportsonbugtriaginganddevelopmentinmozilla,”inProceedings [114] “Toybox,”2023.[Online].Available:https://landley.net/toybox ofTheInternationalSymposiumonOpenCollaboration,2014,pp. 1–8. [115] “Busybox,”2023.[Online].Available:https://busybox.net [96] T. Blazytko, M. Schlo¨gel, C. Aschermann, A. Abbasi, J. Frank, [116] Y.Jiang,D.Wu,andP.Liu,“Jred:Programcustomizationandbloat- S.Wo¨rner,andT.Holz,“Aurora:Statisticalcrashanalysisforauto- waremitigationbasedonstaticanalysis,”in2016IEEE40thannual matedrootcauseexplanation,”inProceedingsofthe29thUSENIX computersoftwareandapplicationsconference(COMPSAC),vol.1. ConferenceonSecuritySymposium,2020,pp.235–252. IEEE,2016,pp.12–21.[117] A. Quach, A. Prakash, and L. Yan, “Debloating software through [135] D. Schwartz-Narbonne, M. Scha¨f, D. Jovanovic´, P. Ru¨mmer, and piece-wise compilation and loading,” in 27th {USENIX} Security T.Wies,“Conflict-directedgraphcoverage,”inNASAFormalMeth- Symposium({USENIX}Security18),2018,pp.869–886. ods:7thInternationalSymposium,NFM2015,Pasadena,CA,USA, April27-29,2015,Proceedings7. Springer,2015,pp.327–342. [118] V.Rastogi,D.Davidson,L.DeCarli,S.Jha,andP.McDaniel,“Cim- plifier: automatically debloating containers,” in Proceedings of the [136] K.-K.Ma,K.YitPhang,J.S.Foster,andM.Hicks,“Directedsym- 2017 11th Joint Meeting on Foundations of Software Engineering, bolicexecution,”inStaticAnalysis:18thInternationalSymposium, 2017,pp.476–486. SAS 2011, Venice, Italy, September 14-16, 2011. Proceedings 18. Springer,2011,pp.95–111. [119] S.Ghavamnia,T.Palit,S.Mishra,andM.Polychronakis,“Temporal systemcallspecializationforattacksurfacereduction,”inProceed- [137] V. Kuznetsov, J. Kinder, S. Bucur, and G. Candea, “Efficient state ingsofthe29thUSENIXConferenceonSecuritySymposium,2020, merginginsymbolicexecution,”AcmSigplanNotices,vol.47,no.6, pp.1749–1766. pp.193–204,2012. [120] B. A. Azad, P. Laperdrix, and N. Nikiforakis, “Less is more: [138] S. Poeplau and A. Francillon, “Symbolic execution with symcc: Quantifying the security benefits of debloating web applications.” Don’t interpret, compile!” in Proceedings of the 29th USENIX inUSENIXSecuritySymposium,2019,pp.1697–1714. ConferenceonSecuritySymposium,2020,pp.181–198. [121] K.Heo,W.Lee,P.Pashakhanloo,andM.Naik,“Effectiveprogram [139] X.Zhu,S.Wen,S.Camtepe,andY.Xiang,“Fuzzing:asurveyfor debloatingviareinforcementlearning,”inProceedingsofthe2018 roadmap,” ACM Computing Surveys (CSUR), vol. 54, no. 11s, pp. ACMSIGSACConferenceonComputerandCommunicationsSecu- 1–36,2022. rity,2018,pp.380–394. [140] V.J.Mane`s,H.Han,C.Han,S.K.Cha,M.Egele,E.J.Schwartz, [122] M.GhaffariniaandK.W.Hamlen,“Binarycontrol-flowtrimming,” and M. Woo, “The art, science, and engineering of fuzzing: A inProceedingsofthe2019ACMSIGSACConferenceonComputer survey,”IEEETransactionsonSoftwareEngineering,vol.47,no.11, andCommunicationsSecurity,2019,pp.1009–1022. pp.2312–2331,2019. [123] H. Xue, Y. Chen, G. Venkataramani, and T. Lan, “Hecate: Auto- [141] H. Peng, Y. Shoshitaishvili, and M. Payer, “T-fuzz: fuzzing by mated customization of program and communication features to programtransformation,”in2018IEEESymposiumonSecurityand reduceattacksurfaces,”inSecurityandPrivacyinCommunication Privacy(SP). IEEE,2018,pp.697–710. Networks: 15th EAI International Conference, SecureComm 2019, [142] S.K.Fayaz,T.Yu,Y.Tobioka,S.Chaki,andV.Sekar,“{BUZZ}:
Orlando,FL,USA,October23–25,2019,Proceedings,PartII15. Testing context-dependent policies in stateful networks,” in 13th Springer,2019,pp.305–319. {USENIX} Symposium on Networked Systems Design and Imple- [124] “bzip2 - home,” 2023. [Online]. Available: https://sourceware.org/ mentation({NSDI}16),2016,pp.275–289. bzip2/ [143] S.Rawat,V.Jain,A.Kumar,L.Cojocar,C.Giuffrida,andH.Bos, [125] S. Zhou, Z. Yang, D. Qiao, P. Liu, M. Yang, Z. Wang, and “Vuzzer:Application-awareevolutionaryfuzzing.”inNDSS,vol.17, C. Wu, “Ferry:{State-Aware} symbolic execution for exploring 2017,pp.1–14. {State-Dependent}programpaths,”in31stUSENIXSecuritySym- [144] R.Kaksonen,M.Laakso,andA.Takanen,“Softwaresecurityassess- posium(USENIXSecurity22),2022,pp.4365–4382. ment through specification mutations and fault injection,” in Com- [126] R.S.Boyer,B.Elspas,andK.N.Levitt,“Select—aformalsystem munications and Multimedia Security Issues of the New Century: for testing and debugging programs by symbolic execution,” ACM IFIPTC6/TC11FifthJointWorkingConferenceonCommunications SigPlanNotices,vol.10,no.6,pp.234–245,1975. and Multimedia Security (CMS’01) May 21–22, 2001, Darmstadt, Germany. Springer,2001,pp.173–183. [127] W. E. Howden, “Symbolic testing and the dissect symbolic evalu- ation system,” IEEE Transactions on Software Engineering, no. 4, [145] “dharma,”https://github.com/MozillaSecurity/dharma. pp.266–278,1977. [146] M. Vuagnoux, “Autodafe: An act of software torture,” in Proceed- [128] J. C. King, “A new approach to program testing,” ACM Sigplan ingsofthe22thChaosCommunicationCongress,no.CONF. Chaos Notices,vol.10,no.6,pp.228–233,1975. ComputerClub,2005,pp.47–58. [129] C. Cadar, D. Dunbar, D. R. Engler et al., “Klee: unassisted and [147] H.J.Abdelnur,R.State,andO.Festor,“Kif:astatefulsipfuzzer,” in Proceedings of the 1st international Conference on Principles, automatic generation of high-coverage tests for complex systems programs.”inOSDI,vol.8,2008,pp.209–224. SystemsandApplicationsofIPTelecommunications,2007,pp.47– 56. [130] C.Aschermann,S.Schumilo,T.Blazytko,R.Gawlik,andT.Holz, [148] N.Stephens,J.Grosen,C.Salls,A.Dutcher,R.Wang,J.Corbetta, “Redqueen:Fuzzingwithinput-to-statecorrespondence.”inNDSS, Y.Shoshitaishvili,C.Kruegel,andG.Vigna,“Driller:Augmenting vol.19,2019,pp.1–15. fuzzingthroughselectivesymbolicexecution.”inNDSS,vol.16,no. [131] P. Chen and H. Chen, “Angora: Efficient fuzzing by principled 2016,2016,pp.1–16. search,” in 2018 IEEE Symposium on Security and Privacy (SP). [149] I.Yun,S.Lee,M.Xu,Y.Jang,andT.Kim,“{QSYM}:Apractical IEEE,2018,pp.711–725. concolic execution engine tailored for hybrid fuzzing,” in 27th [132] P.Chen, J.Liu, andH. Chen, “Matryoshka:fuzzing deeplynested {USENIX}SecuritySymposium({USENIX}Security18),2018,pp. branches,”inProceedingsofthe2019ACMSIGSACConferenceon 745–761. ComputerandCommunicationsSecurity,2019,pp.499–513. [150] “american fuzzy lop,” 2023. [Online]. Available: https://lcamtuf. [133] V. Chipounov, V. Kuznetsov, and G. Candea, “S2e: A platform coredump.cx/afl/ for in-vivo multi-path analysis of software systems,” Acm Sigplan [151] A.Fioraldi,D.Maier,H.Eißfeldt,andM.Heuse,“Afl++combining Notices,vol.46,no.3,pp.265–278,2011. incremental steps of fuzzing research,” in Proceedings of the 14th [134] S.Anand,P.Godefroid,andN.Tillmann,“Demand-drivencompo- USENIXConferenceonOffensiveTechnologies,2020,pp.10–10. sitionalsymbolicexecution,”inToolsandAlgorithmsfortheCon- [152] “libfuzzer – a library for coverage-guided fuzz testing,” 2023. struction and Analysis of Systems: 14th International Conference, [Online].Available:https://llvm.org/docs/LibFuzzer.html TACAS 2008, Held as Part of the Joint European Conferences on TheoryandPracticeofSoftware,ETAPS2008,Budapest,Hungary, [153] K. Serebryany, “Oss-fuzz-google’s continuous fuzzing service for March29-April6,2008.Proceedings14. Springer,2008,pp.367– opensourcesoftware,”inUSENIXSecuritysymposium. USENIX 381. Association,2017.[154] J. Metzman, L. Szekeres, L. Simon, R. Sprabery, and A. Arya, “Fuzzbench: an open fuzzer benchmarking platform and service,” in Proceedings of the 29th ACM joint meeting on European soft- wareengineeringconferenceandsymposiumonthefoundationsof softwareengineering,2021,pp.1393–1403. [155] R. Collobert, S. Bengio, and J. Marie´thoz, “Torch: a modular ma- chinelearningsoftwarelibrary,”Idiap,Tech.Rep.,2002. [156] M.Abadi,“Tensorflow:learningfunctionsatscale,”inProceedings ofthe21stACMSIGPLANInternationalConferenceonFunctional Programming,2016,pp.1–1.
2312.14479 Navigating the Concurrency Landscape: A Survey of Race Condition Vulnerability Detectors Aishwarya Upadhyay, Vijay Laxmi, Smita Naval Department of Computer Science and Engineering Malaviya Naional Institue of Technology Jaipur Email: 2022rcp9026@mnit.ac.in, vlaxmi@mnit.ac.in, smita.cse@mnit.ac.in Abstract—Astechnologycontinuestoadvanceandweusherin reliability and security of file systems. These bugs can lead theeraofIndustry5.0,therehasbeenaprofoundparadigmshift to deadlock situations, kernel panics, data inconsistencies, inoperatingsystems,filesystems,web,andnetworkapplications. and privilege escalations [7][8][9][10][11][12][13][14]. De- The conventional utilization of multiprocessing and multicore spite ongoing efforts to harden OS kernels against various systems has made concurrent programming increasingly per- vasive. However, this transformation has brought about a new attacks, such as kASLR, kCFI, and UniSan, these defenses set of issues known as concurrency bugs, which, due to their primarily address memory errors (e.g., stack and buffer over- wide prevalence in concurrent programs, have led to severe flows) and have limited effectiveness in mitigating attacks failuresandpotentialsecurityexploits.Overthepasttwodecades, that exploit concurrency bugs. Race conditions, in particular, numerous researchers have dedicated their efforts to unveiling, represent a challenging class of concurrency bugs, wherein detecting, mitigating, and preventing these bugs, with the last decadewitnessingasurgeinresearchwithinthisdomain.Among two threads erroneously access a shared memory location the spectrum of concurrency bugs, data races or race condition without proper synchronization or ordering, as depicted in vulnerabilities stand out as the most prevalent, accounting for Figure 1. Due to the inherent non-determinism in thread in- a staggering 80% of all concurrency bugs. This survey paper terleaving, race conditions are notoriously elusive, demanding is focused on the realm of race condition bug detectors. We precise timing and rare interleaving conditions to manifest. systematically categorize these detectors based on the diverse methodologies they employ. Additionally, we delve into the For instance, even widely used file systems like ext4[14] and techniquesandalgorithmsassociatedwithracedetection,tracing btrfs[12], with 50,000 and 130,000 lines of code respectively, the evolution of this field over time. Furthermore, we shed light witnessed an alarming number of reported bugs in a single on the application of fuzzing techniques in the detection of race year[15]. According to the Linux kernel bug tracker, there are condition vulnerabilities. By reviewing these detectors and their currently 1,234 open bugs in Linux kernel 5.15.0. Of these, staticanalyses,wedrawconclusionsandoutlinepotentialfuture research directions, including enhancing accuracy, performance, 627 are classified as critical, 307 are classified as serious, applicability, and comprehensiveness in race condition vulnera- and 300 are classified as moderate.[16]. In extreme cases, the bility detection. Keywords: Race condition, Vulnerability detection, Concur- rent programming, Synchronization, Shared resources, Software security, Multi-threading I. INTRODUCTION The current era witnessed the emergence of Industry 5.0, also known as the Fifth Industrial Revolution, characterized by the collaboration between humans and advanced technol- ogy. This industrial paradigm shift involves the integration of humans and AI-powered machines, such as robots, to enhance workplace processes[1]. As a result, industries like textiles, agriculture, healthcare, and transportation are lever- aging information and communication technology to drive Fig.1. Asimpledepictionofdataracecondition efficiency[2]. Therefore, in the contemporary era of multi- core processors, harnessing concurrency has become a key driver for enhancing the performance of system software. As failure to protect the system from concurrency vulnerability OS kernels and file systems evolve, an array of programming has led to a fatality. The Therac-25, a radiation therapy paradigms, including asynchronous work queues, read-copy- machine developed by Atomic Energy of Canada Limited update (RCU), and optimistic locking, have been introduced (AECL), serves as a striking example of a significant threat to leverage multi-core computing capabilities [3][4][5][6]. posed by concurrent programming errors, commonly known However, these performance enhancements have not come as race conditions. Tragically, these errors occasionally led to withoutacost.Concurrencybugs,particularlyraceconditions, patients receiving radiation doses hundreds of times higher have infiltrated the codebase, significantly compromising the than intended, resulting in fatalities or severe injuries[17]. 3202 ceD 22 ]RC.sc[ 1v97441.2132:viXraA. Motivation Recent hardware architectures have seen a significant in- crease in the prevalence of multithreading support, with pro- cessors like the Intel Xeon Platinum 9282 having up to 56 cores per socket, each capable of running 2 threads, and the Intel Xeon Phi Processor 7290F, an accelerator with up to 72 cores, each supporting 4 threads.Systems with six to 260 cores per socket were included in the 500 list of supercomputers.[18] Because these systems use simultaneous multithreading (SMT), many threads can be executed concur- rently on operating systems that support SMT and/or Sym- metric Multi-Processing (SMP).All threads in a node share the memory (not the cache), which allows for shared memory multithreading. The memory can be accessed uniformly or Fig.2. Increasingtrendofconcurrencyvulnerabilityinlast20years non-uniformly(UMA/NUMA).Languageextensionsorappli-
cation programming interfaces (APIs) were once used by the scientific community to execute parallel programs written in literature, achieved by systematically searching through jour- languages like FORTRAN and C/C++ across several nodes nal articles and conference papers that tackled various aspects in a cluster or grid. As multi-core computers became more related to concurrency bugs. This encompassed methodolo- common,theemphasismovedtosharedmemoryprogramming gies, tools, techniques, empirical assessments, and surveys. models.ThismeantcombiningordinarylanguageslikeC/C++ Majorinternetrepositoriesweresearchedforpertinentpapers. orspecializedparallellanguageslikearray-FORTRANorHPF Initially, searches were conducted using the DBLP database, with tools like the pthreads library/runtime system.[19] How- Google Scholar, and prestigious academic publishers includ- ever,theadoptionofmultiprocessingandparallelarchitectures ing Wiley, ACM, IEEE, Springer, and Elsevier. Only those requirescarefulconsiderationofpotentialbugsandchallenges papers with certain keywords in their names, abstracts, or associated with concurrent software execution. Addressing keywords—suchas”concurrencybug,””concurrentprogram,” theseissuesiscrucialtoharnessthefullpotentialoftherapidly ”multithreaded program,” ”data race,”mutliprocessing”,” ”race evolving technological landscape. The increasing prevalence condition,” or ”concurrency vulnerability”—were submitted. ofconcurrentvulnerabilitiesandcyberattackshasunderscored In addition, a period of time spanning from 1993 to 2023 was the need for secure IT infrastructure [20][21]. The graph in set aside for the inclusion of articles, and those deemed to Figure2 clearly shows how concurrency vulnerabilities have be ofinconsequential importance orwith defectiveideas were evolved from 1999 to 2021. Over this time frame, we see a purposefullyexcluded.Additionalarticlesofnoteworthyvalue consistent increase in the number of these vulnerabilities that that were not found in the previously listed databases were have been reported[22]. This rise in vulnerability disclosures hand-pickedandaddedduringtheevaluationprocess.Figure3 is closely tied to the growth of multi-core hardware and the shows the spread of the selected research and their publishing increasing complexity of software that runs concurrently. It category. This paper surveys the concurrency bugs and the serves as a clear indicator of just how important it is to most up-to-date and well-known race conditions detectors. continue studying and researching concurrency vulnerabilities We categorize the existing detectors based on the types of in the world of modern computing. techniques used to detect race condition vulnerability. Also, Understanding the nuances of concurrent applications and the we shed special light on different types of fuzzers used in the security implications they pose is critical [23]. Researchers in detection of concurrency bugs. This paper aims to present an thefieldhavedevelopedvarioustoolsandtechniquestodetect overview of the state-of-the-art in race condition vulnerability and mitigate vulnerabilities, particularly race conditions [24]. assessment and address the following research questions. These vulnerabilities are prevalent in applications that utilize RQ1:Whatcausesconcurrencyvulnerabilitiestoariseand sharedresourcesandoftenariseduetomistakesmadebyusers which type of concurrency bug makes up the majority of and developers [25]. Efforts to address these challenges have concurrency bugs ledtoadvancementsindetectingandpreventingracecondition Before going to the detection methodologies of concurrent vulnerabilities [26]. bugs we have made an in-depth study of the various con- B. Research Questions currency bugs and the reason for their occurrence. We have This survey seeks to conduct a comprehensive and longitu- also included in our study the importance of lock-free syn- dinal analysis of race condition vulnerabilities in concurrent chronization and the concurrency issues arising from them. programming. Researchers in the field of multiprocessing and RQ2: Study the different methods and techniques for the parallelcomputinghaveproposedvarioustoolsandtechniques exposure and detection of data race bugs. to detect, prevent, and mitigate these vulnerabilities. The We have provided an overview of the current state-of-the-art reviewprocessinvolvedameticulousexaminationofavailable race condition vulnerability assessment and analysis in hyper-threaded and concurrent applications. We have reviewed the II. BACKGROUND methods and techniques that have been developed to identify Priortoconductingasecurityanalysis,it’scrucialtounder- these vulnerabilities, and we have discussed their strengths standhowmultiprocessingsystemsoperate.Thissectionoffers and limitations. We have created our own taxonomy of the an overview of the evolution of concurrent applications, their techniques used by the detectors and on that basis classified operation, the significance of concurrent and hyperthreaded themintothreecategoriesnamelystatic,dynamic,andhybrid. applications, and key technical concepts used in this paper. It Specifically, we have reviewed the fuzzers that have been also explores the use of multithreading and synchronization developed to identify these vulnerabilities and discussed their methodsinconcurrentapplications,aimingtoimproveoverall strengths and limitations. reader comprehension. RQ3: What can be the future research aspect in the area of detection of race condition vulnerability? A. Notations and Concepts of Concurrent Programming Reviewing the most significant and current data race bug In the 1990s, C programming incorporated the POSIX detectors which allowed to draw various conclusions about thread library, known as pthreads, enabling multi-threaded
future research directions, including those related to accuracy, software development. Today, modern computers and oper- performance, application, and integrality. ating systems can run multiple programs concurrently, where We have also provided details of CWEs related to race con- concurrency means executing multiple instruction sequences dition vulnerabilities and described how they were discovered simultaneously. This involves process threads that communi- and remediated. Finally, we have outlined best practices that cate through shared memory or message passing. However, can be used to avoid or mitigate race condition vulnerabilities concurrent resource sharing can lead to issues like resource in hyperthreaded and concurrent applications. scarcity and deadlocks. To improve efficiency, strategies like process coordination, memory allocation, and execution scheduling are employed. This section briefly introduces pro- cesses,threads,andcomputerarchitectureadvancement,which are crucial for understanding vulnerabilities stemming from shared resources and concurrency. 1) ProcesssandThreads: Processesandthreadsarefunda- mental to concurrent computing, each serving distinct roles. Processes are encapsulated execution units that provide iso- lation by maintaining separate memory space and resources [27]. This isolation ensures robustness and fault tolerance in modernoperatingsystems.Incontrast,threadsarelightweight execution units within a process, sharing the same memory space,whichfacilitatesefficientcommunicationandcoordina- tion among concurrent tasks [28]. This shared-memory model allows for parallelism exploitation, resulting in improved ap- Fig.3. Divisionofincludedpapers plication performance and responsiveness. The interaction be- tweenprocessesandthreadsiscrucialindesigningconcurrent softwaresystems.Processesofferhighisolationlevels,making C. Review Organisation them suitable for running independent tasks or safeguarding This literature review is structured into three primary sec- critical system resources [29]. Threads, with their shared- tions to address research questions. In Section 2, we offer memory model, enable efficient collaboration and parallelism background information, including concepts and notation re- within a process [30]. Striking a balance between process latedtoconcurrentprogramming.Section3outlinestheissues and thread usage is a critical aspect of concurrent software in concurrent programming, discussing the characteristics of design, ensuring resource utilization and efficient execution each bug and its severity. In Section 4, we emphasize under- in modern computing environments. Figure 4 depicts the standing race condition vulnerability, with a particular focus multithreading in a single processor systems. For a mutlicore on data race bugs. Section 5 explores application analysis for ormultiprocessormutlithreadingthesystemwillhavemultiple vulnerability detection, examining three analysis techniques: copies of code , data and file with each core acting as a static, dynamic, and hybrid analysis. Section 6 discusses tools independent processor. and repositories for application analysis and vulnerability de- 2) Synchronisation mechanism: OS employs sophisticated tection,includingstudiesoncodevulnerabilitydetectionusing strategiestoenableconcurrentexecutionofmultipleprograms machine learning and traditional approaches. We categorize (processes) and concurrent sub-tasks within these processes experimental studies into three core sections: application/code (threads)[31].Thesemechanismsplayapivotalroleinensur- analysis, code vulnerability detection, and supporting tools. ingefficientsystemperformanceandenablinguserstoperform Section 7 addresses potential research directions, and we taskssimultaneously,contributingtoaseamlessandresponsive provide a concluding summary of our findings. computing experience.This concept is crucial for implementing lock-free data structures and algorithms in lockless synchronization paradigms. Algorithm 1 Compare and Swap (CAS) 1: procedure CAS(address, expectedValue, newValue) 2: currentValue ← address 3: if currentValue = expectedValue then 4: address ← newValue 5: end if 6: return currentValue 7: end procedure Fig.4. Multithreadedapplicationsonasingelcore The Compare and Swap (CAS) algorithm is a vital tool in concurrent programming, providing a means to atomically • Locks Mutex locks are commonly used to synchronize update a shared variable while ensuring thread safety. CAS access to shared resources in multithreaded programs, takesthreeinputs:thememorylocationaddresstobeupdated, allowing one thread at a time to access the shared theexpectedvalueexpectedValuethattheaddressshouldhave, resource. When a thread needs access, it must acquire and the new value newValue to set if the address matches the the lock, use the resource, and then release the lock for expected value. CAS reads the current value at the address, other threads. Early work in operating systems identified compares it to the expected value, and if they match, updates two key synchronization types: mutual exclusion and theaddresswiththenewvalueinanuninterruptibleoperation. condition synchronization, leading to the development of CASreturnsthecurrentvalueregardlessofwhethertheupdate various synchronization primitives, such as busy-waiting occurs, making it useful for building lock-free data structures semaphores, structured semaphores (e.g., critical regions, and synchronization primitives in multi-threaded applications, monitors, path expressions), message-passing primitives, where only one thread at a time can successfully perform the and remote procedure calls. Busy-waiting semaphores, update, ensuring coordinated and thread-safe modifications of the earliest primitives, were found to be challenging and shared variables. inefficient[29]. Structured semaphores were introduced to address these issues, offering a more organized ap-
proach.Message-passingprimitivesenhancesynchroniza- tion with data, and remote procedure calls combine pro- cedural interfaces with message passing. This historical and conceptual relationship among these primitives is illustrated in Figure 5. • Lockless synchronization Lockless synchronization, or lock-free synchronization, is a programming technique that manages shared resources without traditional locks or mutexes. It enhances the scalability and performance of multi-threaded or multi-core applications by reduc- ing contention and minimizing blocking operations[32]. This approach allows multiple threads to access shared resources concurrently, preventing data races and dead- locks. It’s particularly useful in scenarios where locks would introduce significant overhead due to thread con- tention[33].Locklesssynchronizationoffersincreasedap- plicationparallelism,optimizingmulti-coreprocessoruti- lization. However, designing and implementing lockless Fig.5. Synchronizationtechniquesandlanguageclassesusinglocks. algorithmscanbeintricate,necessitatingdeepknowledge of low-level memory operations and platform-specific B. The Advancement of Computer Architecture intricacies[34].TheconceptofCompareandSwap(CAS) is often integral to lockless synchronization, providing The concept of ”Moore’s Law” coined by Gordon Moore a foundation for atomic operations and ensuring thread in 1965 predicted that the number of transistors on a single safety.CASallowsthreadstocompareavalueinmemory chip would double every year or two, resulting in increased to an expected value and update it if the comparison computing speed[35]. However, as depicted in Figure 6, the succeeds, all in a single, uninterruptible operation [32]. proliferation of transistors also led to overheating issues. Thiscompelled a shift in technology towards multi-processing, • SymmetricMultiprocessingSymmetricmultiprocessing driving significant advancements in computer architecture. (SMP) is a computing architecture where multiple pro- Theseadvancementsaimedtocreatefaster,moreefficient,and cessorsorcoresareidenticalincapabilitiesandroles.All highly parallel computing systems, fueled by factors like the processors share the same memory and operate under a demand for enhanced computational power, energy efficiency, single operating system, enabling parallel task execution and the emergence of new technologies[36]. and efficient resource utilization. SMP systems provide load balancing, scalability, and fault tolerance, mak- ing them suitable for various computing environments, including servers, workstations, and high-performance computing clusters. Challenges in SMP systems include memory consistency and synchronization, necessitating synchronization mechanisms like locks and semaphores to ensure data integrity [41][42][43][44]. • AsymmetricMultiprocessingAsymmetricmultiprocess- ing (AMP) is a computing architecture where multiple processors or cores have distinct capabilities and roles. This diversity allows for optimized resource allocation andenhancedsystemefficiency.Unlikesymmetricmulti- processing(SMP),whereprocessorshavesimilarcapabil- ities,AMPsystemscategorizeprocessorsintoroles,such as application processors for general tasks and auxiliary Fig.6. EvolutionofIntelPlatformovertheyears[37] processors for specific functions like graphics rendering or I/O operations. AMP is commonly used in mobile One notable development is the transition from single- devices, where heterogeneous multi-core processors op- core to multi-core processors, enabling simultaneous execu- timize power consumption and balance performance. It tion of multiple tasks and enhancing system performance. is also applied in high-performance computing (HPC) Multi-core architectures have become commonplace in mod- environments,leveragingprocessorcapabilitiesforparal- ern computing, facilitating parallel execution and improved lelism and specific workload acceleration. Effective task throughput.[38]. Another crucial advancement is the intro- scheduling and load balancing are critical in AMP sys- duction of vector processing and SIMD (Single Instruction, tems, given varying processor capabilities [45][46][47]. Multiple Data) architectures. These technologies enable the Figure7 shows the underlying difference between symmetric simultaneous execution of a single instruction on multiple andasymmetricmultiprocessingsystems,wherethesymmetric dataelements,acceleratingdata-intensivecomputations.SIMD multiprocessing architecture works on a shared memory prin- architectures find applications in scientific simulations, mul- ciple whereas the asymmetric multiprocessing system works timedia processing, and machine learning. [39]. Moreover, in the master-slave model. specialized accelerators like GPUs and FPGAs have revo- 2) Hyperthreading: Various multithreading strategies have lutionized computer architecture. GPUs, originally designed been employed over the years to address memory latency for graphics, have evolved into powerful parallel processors issues.OneapproachisSimultaneousMulti-Threading(SMT), for various computations. FPGAs provide hardware recon- which exposes greater parallelism to the CPU by handling figurability, allowing customization for specific workloads. instructions from multiple streams, thus enhancing processor [23]. Advances in memory technologies, including DDR4 and utilization. Notably, SMT, such as Intel’s Hyper-Threading HBM, have alleviated memory bandwidth bottlenecks and (HT), is a cost-effective design choice that does not require facilitated efficient data access for high-performance comput- extensiveadditionalhardware[48].Hyper-Threading,patented ing.[40]. In summary, computer architecture has evolved to by Intel, is a technology present in Intel® XeonTM and focus on parallelism and concurrency, as the era of increasing Intel Pentium® 4 processors. It enables a single physical
clock speeds has come to an end. Harnessing this computing processor to appear as two logical processors to the operating power necessitates deep understanding and efficient software system. By duplicating each processor’s architectural state development. while sharing execution resources, it allows a single physical 1) Multiprocessing Architecture: Parallelism for program processor to execute instructions from multiple threads in acceleration is a core objective of multiprocessor systems. parallel, potentially improving overall performance [49]. Fig- Research in this area explores parallelism identification in ure8 gives the detailed working advantage of a hyperthreaded sequential programs, resource allocation among competing system over a single-core processor, where the throughput processes, synchronization of cooperative processes, and the is increased due to hyperthreading technology. Research has verification of parallel programs. The term ”multiprocessing” explored the performance impact of Hyper-Threading. NASA oftenencompassesparallelprocessingsystems,includingmul- conducted an analysis of HT’s effect on processor resource tiprocessor systems. There are two types of multiprocessing: utilization in scientific applications, concluding that while HTFig.7. SymmetricandAsymmetricMultiprocessing enhances processor resource utilization efficiency, it does not (race conditions), order violations, violations of atomicity, consistently result in improved application performance [48]. and deadlocks, we include the challenges related to the ABA AnotherstudyfoundthatHyper-Threadingonspecificproces- problem(arrivingfromlocklesssynchronization)andspurious sors provided minimal performance gains and even degraded wake-ups as well in this section. the effectiveness of certain applications, particularly those A. Data Races reliantonvectorizationandfacingcommunicationbottlenecks [50]. Conversely, a study focusing on database management Data races occur when multiple threads simultaneously systems (DBMS) reported performance improvements with accessthesamepartofcomputermemory(likeasharedpiece Hyper-Threading, specifically in TPC-C-equivalent and TPC- of information) without the proper coordination, and at least H-equivalent queries [51]. Additionally, research has explored one of them is trying to change it. This can cause memory the impact of Hyper-Threading on resource utilization, con- operationstohappenunexpectedly,leadingtodifferentthreads cluding that while it enhances processor resource utilization seeing inconsistent data and values. Surprisingly, sometimes, efficiency, it may not universally improve application per- programmers intentionally allow data races for performance formance. Efficient code optimization and leveraging vector reasons, although it’s important to note that data races and units are vital for enhancing code efficiency and maximizing raceconditions,despiteoftenbeingusedinterchangeably,refer processor resource utilization, ultimately leading to improved to different things. Data races relate to improper coordination application performance [52]. in memory access, while race conditions are about timing- dependent issues during execution. III. ISSUESINCONCURRENCY B. Atomicity Violation Intheprevioussection,weexaminedtheintegrationofmul- tiprocessing systems and the advancements in hyperthreading Atomicity violation is a type of problem in multithreading, technology, both of which have contributed to the widespread and it accounts for nearly 70 percent of all reported issues in adoptionofconcurrentprogramming.Thissectionwilladdress thiscategory.Ithappenswhenonethread’sactionsdisruptthe the complexities and challenges associated with concurrent order of operations in another thread, particularly when both programming,alongwithanexplorationofthedistinctcharac- threads are using the same shared resource. This disruption teristics of concurrency-related software bugs. As understood can cause the program to behave unpredictably. in previous sections the concurrent programs use different C. Order Violation synchronization primitives to coordinate between the threads and how the program will execute. The failure of these Order violation is another issue after race conditions and synchronization mechanisms can lead to various bugs such atomicity violations. It arises due to the reordering of oper- as data races, deadlock, atomicity violation, live lock, ABA ations involving different parts of memory. In simpler terms, problems & spurious wakeup. Broadly, concurrency-related when two operations, let’s call them A and B, are supposed bugs can be categorized into four major types: data races to happen in a specific order (like A always before B), butFig.8. PerformanceImprovementusingHyperthreadingTechnology during execution, that order gets mixed up. Fixing an order E. ABA Problem violation often leads to a deadlock, a situation where threads TheABAproblemisaconcurrencybugthatoccursinlock- get stuck waiting for each other. Interestingly, order violation free and wait-free algorithms. It happens when one thread is the least studied among these issues, often confused with reads a shared variable, another thread alters the variable’s atomicity violation. Research shows that both programmers value and then reverts it to the original value before the first and testers often struggle to identify the correct sequence of threadwritestoit.Thiscanresultinconcurrencyissuesasthe threadexecution,makingitachallengingproblemtosolve.It’s first thread remains unaware of the variable’s change, leading alsonoteworthythatfixingerrorsinmultithreadedapplications toincorrectassumptions,unexpectedbehavior,orcrashes.For usually takes longer compared to single-threaded ones. instance, in a lock status scenario, if one thread acquires the lock (setting the variable to 1), and another thread waits for it to return to 0, an ABA problem can arise. If the first
D. Deadlock thread reacquires the lock, the variable changes back to 1, leaving the second thread blocked indefinitely. Detecting and Deadlock is an error in multithreaded programming when resolving the ABA problem can be complex due to intricate threads become stuck, unable to gain control over a mutex, interactions between threads, but mitigation techniques like whichisvitalforpreventingissueslikeraceconditions.Dead- usingcompare-and-swap(CAS)operationsorversionnumbers locks typically arise from improper sequencing of operations can help prevent it. orfailuretoreleasethemutexcorrectly.Theycanbeclassified F. Spurious Wakeup into resource and communication deadlocks, with the former being more frequent. Four conditions must be met for a A spurious wakeup is like an unexpected event in a multi- deadlock to occur: mutual exclusion (resources used by only taskingprogram.Ithappenswhenapartoftheprogramwakes one thread at a time), holding and waiting (a thread holds one upfornoclearreason,usuallywhenit’swaitingforsomething resource and waits for another held by a different thread), no to happen. This unexpected wakeup can lead to problems like expropriation(onlytheholdingthreadcanreleasearesource), strangebehaviororevencrashesintheprogram.Forexample, and recurring wait (threads forming a cycle while waiting for think of a program that uses a special signal to control when each other’s resources). All four conditions must be satisfied different parts can use a shared resource. If a part of the for a deadlock to manifest. Common scenarios for deadlock programwakesupwithoutgettingtherightsignal,itmighttry errorsincludemutexesmutuallyexcludingeachother,missing tousethesharedresourceatthewrongtime,causingproblems mutex release operations, attempting to create a mutex in a like data errors and other unexpected issues. Detecting and loop, and repeated calls to a function that generates a mutex. fixing spurious wakeups can be tricky because they oftenTABLEI CONCURRENCYVULNERABILITYCAUSESANDMITIGATION ConcurrencyVulnerability Causes Mitigation RaceCondition Arises when several threads or processes use the same ✓Access to shared data can be coordinated by using data at the same time and at least one of them writes synchronization techniques like locks, semaphores, or something. atomicactions. ✓Employ thread-safe programming practices and avoid sharing mutable state between threads without proper synchronization. Deadlock Occurs when a circular dependency is created between ✓Employ resource allocation and release strategies to twoormorethreadsorprocessesthatareblockedasthey ensureproperresourcemanagementandpreventcircular waitforresourcesthattheyjointlyown. dependencies. ✓Usetechniqueslikeresourceorderingorresourcepre- emptiontobreakpotentialdeadlocks. Starvation Happenswhenathreadorprocessisconsistentlyrefused ✓Implementfairschedulingpoliciestopreventindefinite accesstoresourcesorexecutionbecauseotherthreadsor starvation. processesaregivenahigherpriority. ✓Employstrategiestopreventpriorityinversion,suchas priorityceilingprotocolsorpriorityinheritance. DataInconsistency Ariseswhenmultiplethreadsorprocessesperformcon- ✓Use atomic operations, locks, or transactions as syn- currentreadandwriteoperationsonshareddatawithout chronizationtechniquestoguaranteecorrectconsistency propersynchronization,leadingtoinconsistentorincor- andcoordination. rectresults. ✓Applyproperdataaccesspatternsandavoidunsynchro- nizedconcurrentmodifications. ABAproblem Two or more threads modify a shared variable, leaving ✓In order to guarantee that only one thread is able to the variable with the same value as it had before the change the shared variable at once, use a compare-and- modifications. swap(CAS)procedure. ✓Useaversionstamptotrackthenumberoftimesthe sharedvariablehasbeenmodified. Spuriouswakeup Athreadisawakenedfromawaitstateeventhoughno ✓Useawait-freeorlock-freealgorithmtoavoidspurious otherthreadhassignaledit. wakeups. ✓Usearetrylooptorepeatedlyattemptthewaitopera- tionuntilitsucceeds. happen in complex situations with many parts of the program issues. Furthermore, these vulnerabilities can lead to system working together. However, there are ways to make spurious file leaks, notably affecting system availability, with a higher wakeups less likely, like using signals that can handle these risk of complete loss after exploitation[53]. unexpected events and using special tools to protect shared data. A summarisation of the concurrency bug with their possible causes and mitigation is explained in TableI. From the def- initions above and the Figure9 as well we can infer that all the concurrency vulnerabilities are interrelated and there is a likelihood that a program containing a concurrency bug is very likely to trigger atmost one other concurrency bug. In their extensive 2022 study, Lilibo et al. meticulously analyzed 839 concurrency vulnerabilities sourced from the National Vulnerability Database (NVD), revealing crucial insights into this prevalent issue. These vulnerabilities have surged in response to the growing scale and complexity of software systems,posingsignificantsecuritythreats.Themostcommon among them are race conditions, particularly notorious for their potential to lead to severe remote attacks across diverse services. These concurrency vulnerabilities primarily fall into Fig.9. Relationshipbetweentheconcurrencybugs themedium-riskcategory,makingup67.2%ofcases,although the distribution is relatively even among high and low-risk instances. Notably, both local and remote network access are IV. RACE-CONDITIONVULNERABILITY used for exploitation, with many attackers favoring concur- The analysis of Lilibo et al. study[53] reveals the critical rency vulnerabilities due to their ease of exploitation. The role of race conditions in security concerns. therefore, in this study identified race conditions as the primary culprits across and the preceding sections, we discuss everything keeping in
varying severity levels, often resulting in denial of service view race condition vulnerability. In this section, our primaryfocus is on race condition vulnerabilities, a type of software flaw that arises when multiple execution contexts, such as threads or processes, share a shared resource and can modify it concurrently, disregarding the need for mutual exclusion. An incorrect assumption often made is that a sequence of instructionsorsystemcallswillexecuteatomically,preventing any interference from other threads or processes. Regrettably, somedeveloperstendtodownplaythesignificanceofaddress- ing this issue, even when presented with evidence. In reality, most system calls involve the execution of thousands, or even millions,ofinstructionsandoftendon’tcompleteuntilanother process or thread is given a chance to run. The race condition vulnerability can occur in different parts of a computer system including : • Multithreaded Applications: When multiple threads Fig.10. RelationshipchartforCWE-362 in a program access shared resources concurrently and perform read and write operations without proper syn- chronization, race conditions can arise. 6 x = x + 1 • Operating Systems: When many processes or threads 7 accesssharedkernelresources,likesystemdatastructures 8 # Release the lock on the variable x. or device drivers, without the proper synchronization, 9 lock.release() 10 race conditions can arise within the kernel or operating 11 # Create a lock object. system components. 12 lock = threading.Lock() • Network Communication: Race conditions can also 1 13 4 # Create two threads that will both call the occurinnetworkcommunicationprotocolswhenmultiple race_condition() function. processes or systems try to access and modify shared 15 thread1 = threading.Thread(target= race_condition, args=(1,)) network resources concurrently. 16 thread2 = threading.Thread(target= • Database Systems: When several transactions try to race_condition, args=(2,)) access and modify the same data concurrently in 17 databasesystemswithoutthenecessaryseparationmech- 18 # Start the threads. 19 thread1.start() anisms—such as locks or transaction management—race 20 thread2.start() situations may occur. 21 • File Systems: Concurrent access to shared files or di- 2 22 3 # thW ra ei at d1f .o jr oit nh (e ) threads to finish. rectories by multiple processes or threads can lead to 24 thread2.join() race conditions if proper file locking or synchronization 25 mechanisms are not employed. 26 # Print the value of x. 27 print(x) All the above-listed sections where race condition can occur The value of x will be printed to the console using this in a computer system can be mapped with the different code. Nevertheless, if we execute this procedure more than CWEs related to race condition as depicted in Figure 10. once, we might observe various values for x. This is a result Based on data association and operation block, Hong et al. of the two threads simultaneously changing the variable x. have illustrated four types of race bugs in [54]: data race bug, When this happens, there may be a race condition and x does blockracebug,multi-dataracebug,andmulti-datablockrace not end up as expected. We can use a lock to make sure that bug. All these four classes can be related to the CWEs listed only one thread can access the variable x at a time in order in TableII. Figure10 gives a relational structure of CWE-362 to avoid race situations. Before changing the variable x in the ”Concurrent Execution using Shared Resource with Improper code above, we first constructed a lock object and obtained Synchronization” also known as race condition. An improper the lock. We changed the variable x and then released the synchronization of shared resources is a cause of multiple lock. This guarantees that the variable x cannot be modified CWEs which are said to be the child of the CWE-362. simultaneously by the two threads. To understand better, here is an example of a code snippet that intentionally contains a race condition: A. Data Race Bugs 1 def race_condition(x): When two or more threads visit the same shared variable 2 # Acquire a lock on the variable x. concurrently and at least one of those accesses is a write, 3 lock.acquire() it might lead to a specific kind of race condition known as 4 5 # Modify the variable x. data race. Data corruption and deadlocks are two examplesTABLEII CWESRELATEDTORACECONDITIONVULNERABILITIESINVARIOUSAPPLICATIONS/COMPONENTS Name CWE-ID Description InsufficientControlFlowManagement 691 The code lacks adequate control flow management during execution, resulting in potentialscenarioswherethecontrolflowcanbeunexpectedlyaltered. Concurrent Execution using Shared 362 The product incorporates a code sequence that can execute simultaneously with other Resource with Improper Synchronization code. This code sequence necessitates temporary, exclusive control over a shared (’RaceCondition’) resource. However, there is a specific time interval during which the shared resource maybealteredbyanotherconcurrentlyrunningcodesequence. SignalHandlerRaceCondition 364 Theproductutilisesasignalhandlerthatcreatesaracecondition. RaceConditionwithinaThread 366 Whentwothreadsofexecutionconcurrentlyaccessaresource,thereisapotentialrisk of using the resource in an invalid state, which can result in an undefined state of execution. Time-of-check Time-of-use (TOCTOU) 367 Theproductperformsapre-useverificationofaresource’sstate.However,itispossible RaceCondition for the resource’s state to be altered after the verification and before its utilisation, thereby rendering the verification results invalid. The occurrence of this issue may resultintheproductexecutingactionsthatarenotvalid,particularlywhentheresource isinanunforeseenorabnormalstate. ContextSwitchingRaceCondition 368 Theproductexecutesasequenceofnon-atomicoperationstotransitionbetweencontexts that span privilege or security boundaries. However, a race condition exists, which
enablesanattackertomanipulateordistorttheproduct’sbehaviorduringthetransition. RaceConditionDuringAccesstoAlternate 421 The product provides an additional communication channel for authorized users, Channel however,itisimportanttonotethatthischannelmayalsobeaccessibletootheractors. Permission Race Condition During Re- 689 Theproductdoesnotestablishthepermissionsoraccesscontrolforaresourceduringthe sourceCopy processofcopyingorcloning.Asaresult,theresourceremainsvulnerabletoexternal entitiesuntilthecopyingprocessisfinished. RaceConditionforWrite-OnceAttributes 1223 The hardware design includes a write-once register that can be programmed by an untrustedsoftwarecomponentbeforethetrustedsoftwarecomponent.Thissequenceof eventsleadstotheoccurrenceofaraceconditionissue. HardwareLogicContainsRaceConditions 1298 The presence of a race condition within the hardware logic has the potential to compromisethesecurityguaranteesprovidedbythesystem. ImproperSynchronization 662 The product employs multiple threads or processes to enable temporary access to a sharedresourcethatcanonlybeaccessedexclusivelybyoneprocessatatime.However, it lacks proper synchronization of these actions, potentially resulting in simultaneous accesstothisresourcebymultiplethreadsorprocesses. of unexpected or improper behavior that can result from data mined value for sharedvar1. Therefore, if your code relies on races.Thissurvey’sprimarygoalistoevaluatetheapproaches aparticularvalueofsharedvar1,itcanleadtounintendedcon- used to identify data races, both solely and inclusively. When sequences, rendering the data race a software bug. Data races welookattheelucidationofdataracethoughFigure11where manifest when shared resources are accessed concurrently by two threads, Thread 1 and Thread2, update the values of multiple tasks, resulting in unpredictable outcomes. Under- shared resources, namely sharedvar1 and sharedvar2. Later standing data races can be challenging since the execution of on, these tasks retrieve the values of these shared resources instructionsmaynotfollowtheorderinwhichtheyarewritten, using the functions do sth with shared resources1() and and the outcome can vary between different test runs, making do sth with shared resources2(), without any protective dataraceselusiveanddifficulttoreproduceandrectify.These measures in place for these operations. In the absence of findings emphasize the critical importance of implementing protective measures, it is important to note that the expected protective mechanisms to detect and mitigate data races and value of a shared resource, such as sharedvar1, may not ensure the reliability and integrity of concurrent software necessarily match the value that was written in Thread 1 systems. Therefore our proceeding sections will concentrate just before the function call. This discrepancy arises due to onthevarious detection techniques and tools for data race the concurrent execution of Thread 1 and Thread 2, which bugs. can lead to unexpected outcomes, such as reading a value V. ANALYSISFORVULNERABILITY of 21 or, in some cases, even a corrupt, random value. The Program under test(PUT) should be analyzed for vul- To elucidate this, consider the two possible sequences of nerability as a first step to the detection of vulnerability. eventsSequence1Thread1writessharedvar1as11→Thread Based on the analysis techniques used by the researchers of 1 invokes the do sth with shared resources1() function. Se- all the papers that were considered for review, the papers quence 2:Thread 1 writes sharedvar1 as 11 → Thread 2 over- were categorized into three basic detection techniques namely writessharedvar1withavalueof21→Thread1subsequently static, dynamic, and hybrid. Figure 12 depicts the division of calls the do sth with shared resources1() function. the various techniques into these three categories. The three In the absence of protective mechanisms, any code imple- categories can be defined as : mented within the do sth with shared resources1() function 1) Static Analysis:Potential vulnerabilities can be found cannot assume a specific sequence of events or a predeter- before the application is even compiled by using staticFig.11. Simultaneousaccesstosharedresourcesbytwotaskswithoutspecificprotectionwhichcanleadtodatarace analysis, which examines an application’s code without 1) For every shared memory variable ’v,’ initialize ’C(v)’ running it. with the complete list of locks. 2) Dynamic Analysis: In dynamic analysis, the program 2) Each thread keeps track of its held locks (’locks(t)’) and is run and its behavior is observed for indicators of its write locks (’writeLocks(t)’) during execution. vulnerability, including race situations or deadlocks. 3) Whenever a thread accesses a shared memory variable 3) HybridAnalysis:Thebenefitsofbothstaticanddynamic ’v’: arecombinedinhybridanalysis.Staticanalysisisusually • Itcheckswhetheritholdsallthelocksin’C(v)’(i.e., the first step, in which the code is examined for possible ’locks(t)’ contains all the locks in ’C(v)’). problems before running. Certain vulnerabilities can be • It also verifies whether it holds the write lock for ’v’ found and problems can be detected early in the devel- (i.e., ’writeLocks(t)’ contains ’v’). opmentphasethankstostaticanalysis.Next,thesoftware 4) If both conditions are met for a thread when accessing isrunandthebehaviorisobservedunderreal-worldsitua- ’v,’thereisnopotentialraceconditiondetected.However, tionsduringthedynamicanalysisphase.Runtime-specific if any of the conditions are not satisfied, it signifies a bugs,performancedifficulties,andsecurityvulnerabilities
potential race condition, as shared memory ’v’ is being that might not be visible with static analysis alone can accessed without the necessary locks. be found during this phase. Static and dynamic analysis tools employ this approach to A. Algorithms Detection of Race condition identify possible race situations when many threads access Detectionalgorithmsareusedtoidentifyracesinconcurrent shared memory without the necessary locks. It maintains sets programming. To identify these races, numerous algorithms oflocksforeachsharedvariable,ensuringthatthreadsadhere have been created, each with a different strategy and set of tothelockingprotocolwhenaccessingsharedmemorytopre- trade-offs. The following are some popular techniques (which vent data races. Regrettably, not all of the races identified by include lock and lockless synchronization) for race detection: a lockset algorithm represent real races. It is possible to write 1) The lockset algorithm: This approach, which is used in code that is free from data races, either by employing clever both static and dynamic analysis tools, detects a possible race programming techniques or by utilizing alternative synchro- problem when several threads access shared memory without nization methods such as signaling. This poses a significant any of them having a shared lock. Essentially, the technique challenge when it comes to distinguishing genuine bugs from determines that for every shared memory variable, v, there is false positives. Annotations and specific suppressions can be a non-empty set of locks, C(v), that each thread that wants employed as strategies to mitigate this issue. An alternative to access the variable has to hold. At first, all of the locks algorithmforracedetectionisthe”happens-before”algorithm. that are available are placed in ’C(v)’. Every thread has two 2) Happen Before Algorithm: The Happens-Before algo- sets of locks: ’writeLocks(t)’ indicates the write locks held, rithmisdesignedtodeterminethepartialorderingofeventsin and ’locks(t)’ indicates all the locks held by that thread. The distributed systems, particularly in the context of identifying following is how the algorithm functions: data races. Here’s an overview of how it operates A singleFig.13. HappenBeforeAlgorithm have undergone evolution over several years with the usage of a combination of other techniques such as point analysis, Fig.12. Categorisationofdifferentdetectiontechniquesusedinthereviewed papers CFG(Control flow graphs), reachability analysis and lock analysis etc. B. Fuzzing thread’s events are naturally arranged according to the order Fuzzing is an approach that begins by identifying possible inwhichtheyoccur.Eventsarearrangedamongthreadsbased concurrencyissuesusingbugdetectors.Itthentakescontrolof onsynchronizationfundamentalfeatures.Intheeventthattwo thread scheduling and execution based on these bug reports, threads are vying for the same lock (’lock(a)’), for example, aiming to execute specific interleaving patterns in the pro- the unlocking of one thread is seen as having occurred before gram’soperationtouncoverconcurrencybugsintentionally.To thelockingofanotherthread.Apossibleraceissueisindicated extracttraitsthatindicatetheexistenceofconcurrencyflawsin when many threads visit the same variable and their accesses real-world scenarios, several fuzzing approaches rely on static are not deterministically ordered by the ”happens-before” analysis. When fuzzing is done intentionally, it exposes con- relationship. currencyflawsmoreeffectivelythanothertechniques.Fuzzing However,therearesomelimitationstothisalgorithm:Itcan falls under the hybrid analysis category since it employs both be computationally expensive to monitor these relationships. static and dynamic techniques to find concurrency issues. The order in which events are scheduled has a significant impact on this algorithm’s performance. The partial order C. Machine learning constructed is specific to a particular scheduling instance and Machine learning or specific deep learning methods are may not detect the same bugs if the scheduling is different also applied by researchers for the detection of concurrency on another day. While some executions (Fig13(2)) may not bugs. There are several methods that deep learning can be report any races, others (Figure13(3)) may detect races. This appliedtoidentifyconcurrencyissuesinconcurrentprograms. inconsistency can lead to missed race conditions, with some Using a dataset of acknowledged concurrency bugs to train only becoming apparent years after a product’s release. a deep learning model is one such method. The model can Comparably, although the Lockset algorithm is effective, it then be used to identify new concurrency bugs in other frequentlyproducesalargenumberoffalsepositives.Attempts programsbycomparingthemtotheknownbugsinthedataset. have been made to integrate these algorithms in order to take Anotherapproachistousedeeplearningtogeneratesynthetic advantage of their individual advantages and minimize their executiontracesofconcurrentprogramsandthentrainamodel disadvantages.It’sworthnotingthatracedetectionalgorithms to identify concurrency bugs in the traces. This approach canbe more effective than traditional static analysis tools because A. Static Analysis Tools it can detect concurrency bugs that are only exposed during runtime. Deep learning can also be used to develop dynamic Because concurrency issues in software are intimately re- analysis tools that can detect concurrency bugs in real-time. lated to the way the program’s scheduler manages threads, These tools can be used to monitor concurrent programs they are difficult to find using standard compile-time checks
while they are running and to identify concurrency bugs as and testing techniques. To address this, various static analysis they occur. DeepRace[55] is one such method that leverages techniques have been developed. A static race detection anal- deep learning techniques to automatically detect data races, ysisforconcurrentJavaprogramswasintroducedbyFlanagan eliminatingtheneedformanualcreationofdataracedetectors. and Freund et al.[56]. Their system focuses on lock-based To find data races in code approaches, it uses a convolutional synchronization rules for avoiding races. It checks to see if neural network (CNN) that has one layer and several window locks are appropriately held while using shared variables. But sizes. To extract the weights of the final convolutional layer, usingthisapproachnecessitatesaddingmoretypeannotations, it also integrates the class activation map function with global which might add to the complexity. To address this, Abadi averagepooling.Thelinesofcodelinkedtodataracesarethen and colleagues presented a static race detection study for Java identified by backpropagating these weights across the input programs running in high quantities concurrently[57]. There sourcecode.Asaresult,itisclaimedthattheDeepRacemodel are no restrictions on this type-based analysis concerning may identify data race issues in both files and lines of code. test coverage issues. It works well with classes that have client-side or internal synchronization, as well as thread-local synchronization. Using 4000 lines of Java code, they tested VI. TOOLSANDTECHNIQUESFORDETECTION thistechniqueandwereabletofindraceproblemsinothertest To Detecting concurrent application vulnerabilities can programs as well as common Java libraries. Engler presented be challenging, as they often involve complex interactions RacerX[58], a program that can identify deadlocks and race between multiple threads or processes. Figure14 illustrates conditionswithouttheneedforannotations.Facebookcreated the comprehensive process of identifying concurrency bugs the static analysis tool RacerX. By examining the code, keep- in a concurrent program (PUT) using an input seed. The ing track of shared variable accesses, and looking for order various methods for detecting these concurrency bugs can violations, it finds race situations in Java programs.RacerX be categorized into three distinct groups based on whether uses flow-sensitive analysis and concurrent inter-procedural they involve program execution. These categories are static program analysis to efficiently find problems in complex analysis, dynamic analysis, and hybrid analysis. systems.Largeapplicationscanbehandledbyit,butitsfalse- negative rate is somewhat high. Naik et al. suggested a novel static method for Java program race detection in order to improve RacerX. Their four stage algorithm (reachable pairs, aliasing pairs, escaping pairs, and unlocked pairs) is context- sensitive.Usingcontextsensitivity,itincreasesscalabilityeven in large, extensively used programs and finds more flaws than earlier static race detection methods, such as RacerX. Naik and Aiken et al. proposed an algorithm to overcome RacerX’sshortcomingsindemonstratingracialfreedom.Their main goal is to show that if two locks are different, then the memory regions they guard have to be different as well. In order to statically analyze multi-threaded programs and identifyraces,theyuseconditionalmust-not-aliasing.Inorder to counter code-centric techniques, Vaziri et al. presented a data-centric approach[59]. As a new criterion for data races, they identified 11 suspicious interleaving patterns and statically examined the code parts that required alteration to stop data races. Voung et al. introduced RELAY[60], a static and scalable method for identifying data races in the Linux kernel, in the context of C programs. In contrast to RacerX, Fig.14. FlowofConcurrencyDetection RELAYdetectsdataracesthroughacontext-sensitive,bottom- up analysis. In order to examine function behavior without In handling potential race conditions, hangs, and all the regard to the calling context, it presents the idea of relative otherproblemsthatarisewhenprocessingsimultaneoustrans- locksets. In 4.5 million lines of C code, RELAY detected 53 actions, a variety of concurrency testing tools are available on races; however, its false-positive rate was more than 70To the market. Every tool we examine here is useful in a specific identify concurrency in Java programs, several tools have capacity. been developed [61][62].A commercial static analysis toolwith race situation detection features is called Coverity[61]. It object-orientedapplications,inoppositiontoEraserandChoi’s tracks variable accesses and thread synchronization actions to method. RaceTrack, which was created especially for Mi- performinter-proceduralanalysisandfindpossibledataraces. crosoft’s Common Language Runtime, functions at the virtual A static analysis tool called ThreadSafe [62] is intended to machine level. It uses a hybrid detection approach to improve find concurrency problems in Java programs, including race accuracy, reports questionable memory access patterns, and conditions.Inordertofindpotentialdataraces,deadlocks,and tracks program execution traces using instrumentation data. thread-safety violations, it examines the code. A commercial Xu et al. created the Serializability Violation Detector (SVD), staticanalysistoolwithraceconditiondetectioncapabilitiesis a dynamic tool that offers root causes for debugging and em- Polyspace [63]. Formal verification and abstract interpretation ploys backward error recovery (BER) to safeguard erroneous approaches are employed to identify possible concurrency- concurrent programs from errors[85]. With SVD, one can ex-
related problems, such as data races, in C/C++ systems.On aminesomethingafterthefactwithouthavingtofirstannotate the other hand, CogniCrypt [64] is a static analysis tool the program. In order to identify error messages, Flanagan designed to find data races in cryptographic code in Java et al. underlined the significance of thorough and accurate systems. It finds possible cryptography-related race situations dynamic analysis for atomicity violations[56]. They did this by combining symbolic execution and program slicing. These by examining precise relationships between memory accesses methods encompass various approaches to static and dynamic incertaincodeareas.Ratanaworabhanetal.’sToleRace[86]ad- analysis for detecting concurrency bugs in both Java and C dressedasymmetricracesandusedatransaction-liketechnique programs, each with its strengths and limitations. TableIII to detect and tolerate races, greatly lowering the overhead depictsthecomparativeanalysisofallthemultipletechniques associated with dynamic race detection. Jin et al. invented used by the static analysis tools for data race detection. Of CooperativeCrugIsolation(CCI),atechniquethatmaydetect all the tools majority of them use Happen Before and Point awiderangeofconcurrencyflawswithminimaloverheadand Analysisalgorithmsforthedetectionmethodology.Theuseof scalability,incontrasttomanyprevioustoolsthattargetcertain CFG(Control flow graph) is also seen for the visualization of types of concurrency bugs[87]. Falcon[88] by Park et al. the program flow which makes it easier to statically analyze 2010 was introduced as a dynamic fault localization tool that the pieces of code where the bug can occur. But, as the directlycorrespondstofaults,detectsvarioustypesofconcur- complexity increases static analysis cannot be scaled and can rency bugs, and effectively captures both order violations and lead to many false positives therefore there arises a need for atomicity violations using patternbased analysis. UNICORN dynamic and hybrid analysis [89] enhanced Falcon by monitoring pairs of memory access in C++ programs, allowing detection of both single-variable B. Dynamic Analysis Tools and multi-variable violations. A non-pattern-based tool called Several dynamic analysis tools have been developed to de- Recon[90] from Lucia et al. is used to handle single- and tectdataracesandconcurrencyissuesinvariousprogramming multivariable mistakes. It offers small segments of failure- languages. These dynamic methods offer certain advantages, inducingexecutionschedulestohelpwithbugcomprehension primarily the ability to examine observed feasible execution in addition to problem identification. Zhang et al. introduced paths and accurately assess variable values and thread in- AnticipatingInvariant(AI)asaprograminvarianttodetectand terleaving modes. This flexibility allows dynamic methods tolerate various concurrency bugs, exposing order violations to effectively detect a range of issues, including plagiarism and generating emergency patches when necessary[91] Some detection, making them versatile in problem identification. tools,likeMagicFuzzer[92]byCaietal.2012andMagiclock One notable tool in this category is Eraser[81], introduced by [93] from Cai and Chan 2014, were developed exclusively Savage et al. in 1997. Eraser employs a dynamic approach for deadlock detection, identifying hidden deadlock cycles using the lockset algorithm to detect data races in multi- and efficiently reducing the overhead of dynamic deadlock threadedproductionservers.Itensuresthatshared-memoryac- detection. ConMem [94] focused on bugs that can lead to cessesadheretoprogrammingpolicies,safeguardingprograms program crashes caused by incorrect thread interleavings and from data races. However, Eraser may have limitations in memory problems.To efficiently identify such problems, it error detection due to incomplete test coverage. Smaragdakis keeps an eye on how programs are being executed and exam- et al.introduced the concept of “causally precedes” (CP), a ines memory accesses and synchronizations. ThreadSanitizer generalization of the happens-before algorithm, enabling the [95], developed by Google, is used for C/C++ and Go pro- observation of more races while maintaining accuracy and grams. It employs runtime instrumentation and happensbefore completeness. This dynamic technique enhances the detection analysistoidentifypotentialdataraces.Inspector,designedfor of concurrency issues[82] Choi et al. presented an approach Java programs, utilizes dynamic analysis techniques, includ- that combines elements of both lockset and happens-before ing happens-before relations and synchronization tracking, to algorithms to dynamically detect data races in object-oriented identify race conditions during program execution. Microsoft programs[83] Their experimental results demonstrated sig- Research’s CHESS [96] is a dynamic analysis tool that sys- nificant improvements in detection efficiency and reduced tematically explores thread schedules to detect potential race overhead compared to existing techniques. Yu et al. presented conditions,deadlocks,andotherconcurrencyissuesinconcur- RaceTrack [84], a useful runtime race detection tool for rent programs. FastTrack [97], tailored for C/C++ concurrentTABLEIII COMPARATIVEANALYSISOFTECHNIQUESUSEDBYSTATICDETECTORS MethodologyEmployed NameofTool IntendedUse Happen Point to Reachability Model DAG/CFG Lock Set Description Before Analysis Analysis Checker Analysis Analysis RacerX[58] Linux,FreeBSD ✓ ✓ ✓ ✓ Flow sensitive, interprocedural analysis
RELAY[60] LinuxKernel ✓ ✓ ✓ ✓ RelativeLockset ERIGONE[65] Clanguage ✓ ✓ ✓ ✓ Apartialreimplementationofspin modelchecker RaceView[66] Clanguage ✓ DAG-baseddataracevisualization forinvestigationandclassification. DR-Frame[67] Network ✓ ✓ Based on dataflow analysis tech- Applications nique.Uses happen before algo- rithm. SWORD[68] Java Program ✓ ✓ Points-toandhappens-beforeanal- writtenineclipse ysisfusionforefficientandprecise IDE staticdataracedetection. Concurrent Clanguage ✓ ✓ Points-toandhappens-beforeanal- CFG[69] ysisforstaticdataracedetection. Chord[70] JavaProgram ✓ ✓ ✓ Theproposedtechniqueisbasedon a combination of points-to analy- sis, lock analysis, and reachability analysis LOCKSMITH[71] Clanguage ✓ ✓ ✓ Itusesacombinationofinterproce- dural analysis and constraint solv- ingtodetectraceconditions KISS[72] DeviceDriver ✓ ✓ ✓ Sequentialdataracedetectionona simplifiedconcurrentprogram EPAJ[73] Program Wirtten ✓ ✓ Partial discovered types for static inJAVA data race detection and atomic- ity checking with runtime perfor- manceoptimization. COBE[74] Program with ✓ ✓ ✓ ✓ Happens-beforeinferenceforasyn- asynchronous chronous data race detection in call concurrentprograms. IteRace[75] JAVAProgram ✓ ✓ ✓ Points-to, happens-before, and reachability analysis for precise and efficient static data race detection. coderrect[76] C/C++, JAVA ✓ ✓ ✓ Origin-based static race detection /ANDROIDAPP for precise and efficient reasoning about shared memory and pointer aliases. OpenRace[77] C/C++ ✓ ✓ ✓ Points-to, happens-before, and reachabilityanalysisforsoundand completestaticdataracedetection. LLOV[78] OpenMP ✓ ✓ ✓ ✓ OpenMP control flow analysis- based data race detection for OpenMP programs using points- to, happens-before, and reachabil- ityanalysis. OMPRacer[79] OpenMP ✓ ✓ ✓ OpenMP control flow analysis to construct a CFG of the OpenMP program and identify shared ob- jects, followed by happens-before analysis and reachability analysis fordataracedetection. Goblint[80] Device Driver ✓ ✓ ✓ Goblint uses points-to, happens- (Written in before, and reachability analysis C,C++) for data race detection in device drivers.programs,combineshappensbeforeanalysisandlockset-based raceconditionsandotherconcurrency-relatedproblems.How- techniques for dynamic race detection. Lastly, ConTest [98] ever, Saturn [107] is designed specifically for multithreaded focuses on multi-threaded Java programs, employing dynamic C/C++ programs. It uses a combination of dynamic symbolic analysisandformalmethodstoofferpreciseracedetectionand execution and static analysis to identify any data races and in-depth analysis of execution schedules. These tools provide provide accurate execution traces. Finally, SWORD [68] op- valuable assistance in identifying and mitigating concurrency- eratesintherealmofmultithreadedJavaprograms,employing related problems during runtime.In summary, these dynamic a hybrid approach that integrates static and dynamic analysis analysis tools offer diverse approaches to detect and address techniques. It conducts static analysis to identify potential concurrency bugs, ranging from data races and atomicity vio- racesandthenemploydynamicanalysistovalidateandrefine lations to deadlocks and program crashes, providing valuable the results, ensuring effective race condition detection. These assistance to programmers in improving software reliability toolscollectivelyleveragebothstaticanddynamicmethodsto and robustness. overcome the limitations of each and provide more effective bug detection and classification. C. Hybrid Analysis Tools 1) Fuzzers: As discussed earlier one of the hybrid tech- In addition to the two primary types of concurrent bug nique used for bug detection which is quite prominently used detectors mentioned above, there exist additional strategies, nowadays both for sequential and concurrent applications is as shown in TableIV, that either blend static and dynamic fuzzing. Most fuzzing techniques for identifying concurrency methods together or combine one of the two ways with bugs rely on static analysis to extract bug manifestation fea- other approaches. Scholars have acknowledged the shortcom- turesfromreal-worldconcurrencyissues.Fuzzing,asamethod ings of previous methods in identifying concurrent issues, fordeliberatelyexposingconcurrencybugs,isconsideredmore especially those that depend on particular synchronization efficient compared to other approaches. Race-Fuzzer[113], semantics, which may result in false reports of flaws. To developed by Sen et. al in 2008, is designed to efficiently address these limitations, Lu et al. introduced AVIO [99], a reproduce data races while keeping overhead to a minimum. tool for detecting atomicity violations, which combines static The approach initially identifies potential races using a detec- and dynamic approaches. AVIO identifies AccessInterleaving tiontechnique.Itthenemploysarandomizedthreadscheduler invariants(AIinvariants)thatrepresentcodesectionsexpected to manipulate thread execution in a way that triggers actual to execute atomically. Concurrency problems are identified data races from the previously identified potential ones. Race- if memory access interleavings break these invariants during Fuzzeriseffectiveatdistinguishingrealdataraces,whichhave runtime. Similarly, Shi et al. introduced definitionuse invari- thepotentialtocauseprogramexceptions,fromotherpotential
ants (DefUse invariants)[100] extracted from training runs to races. However, its effectiveness in exposing bugs depends dynamically detect violations and different types of program heavilyontheunderlyingdataracedetectiontools,potentially bugs.Zhangetal.proposedaconsequence-orientedapproach, missing some bugs due to limited coverage. For detecting focusing on a bug’s lifecycle stages, leading to improved deadlocks, DeadlockFuzzer[114], introduced by Joshi et al. bug detection accuracy and coverage[101]. Kasikci et al. in 2009, identifies real deadlocks in multithreaded programs. presented RaceMob[102],a data race detector that guarantees It begins by locating suspicious deadlocks using dynamic low runtime overhead and good accuracy by combining static analysis.DeadlockFuzzer then uses a randomized scheduler to and dynamic discovery.Deng et al. introduced Concurrent regulate thread scheduling in order to replicate these suspi- Function Pair (CFP)[103], an interleaving-coverage metric, cious deadlocks, hence raising the probability of exposing to improve bug-detection efficiency in dynamic analysis. them. It has been noted, meanwhile, that DeadlockFuzzer Additionally, innovative tools like MUVI[99], which detects mighthavetroubleaccuratelyconfirmingthepresenceofatrue inconsistentupdatesandmulti-variableconcurrencybugs,and deadlock. ConLock[115], a mechanism that dynamically tests Portend+[104], which have been designed to improve con- fordeadlocksusingconstraint-basedapproaches,wasinvented currency bug identification and analysis. It not only detects byCaietal.(2014)inordertoaddressthisproblem.ConLock data races but also evaluates possible repercussions to clas- begins by examining a possible deadlock situation in order to sify them depending on severity. Helgrind[105]is a versatile deriveasetofthreadschedulingconstraints.Therulesguiding race detection tool within the Valgrind framework, employing the relevant thread pairs’ acquisition and release of locks a hybrid approach that combines both dynamic and static duringthepossibledeadlockarespecifiedbytheselimitations. analysis methods for C/C++ programs. It effectively identifies After then, the program is run within the limitations in an race conditions by utilizing lockset-based analysis to uncover effort to produce a deadlock. ConLock labels a stalemate as potential data races. Similarly, Eraser[81] is another hybrid false positive if it is not reproducible. Linux kernels using tool designed for multithreaded C/C++ programs, employing bothlocklessandlock-basedsynchronizationmethodsforcon- a combination of static analysis and dynamic instrumentation currency are more susceptible to bugs. Therefore, there have to detect races. It relies on lockset-based analysis and thread been multiple fuzzers developed for detecting concurrency preemption techniques to identify potential data race issues. bug in kernel programs.[116][117][118][119]. TableV gives a RoadRunner[106] focuses on concurrent Java programs and brief overview of the fuzzers developed for concurrency bug employsahybriddynamicstaticanalysisapproachtouncover detection.TABLEIV HYBRIDDETECTIONTECHNIQUES Tool Year Author PUT Techniquesused KeyBenefits PACER[108] 2010 Bondet.al Realworldappli- ProportionalAnalysis Efficiency,precisionandversatility cations RaceMob[102] 2013 Kasikciet.al Realworldappli- Crowdsourcing+statisticalsignificance Always-on in production, Accu- cations racy,Lowoverhead ConSeq[101] 2011 Zhanget.al C/C++ Sequentialreplay Increased bug detection coverage, applications lowerfalsepositive MultiRace[109] 2007 Pozniansky C++applications DjitandLockset Loweroverhead,Scalability et.al ColFinder[110] 2015 Wu.et.al Program, written staticprogramslicing+Threadscheduling Reduce time of bug manifestation inClanguage andoverhead SDRacer[111] 2020 Wanget.al Embedded Staticanalysis+SymbolicExecution Automation, Accutacy and effi- programs written ciency inClanguage HistLock+[112] 2018 Yang.et.al C and C++ pro- Lockset-based+History-based Completeness, Precision, gram Efficiency,Versatility SVD[85] 2005 Xuet.al Cprograms Lockset analysis + Happens-before analy- Improved Reliability and lower sis+Atomicregionanalysis falsepositive Helgrind[105] 2005 Valgrind C/C++programs Part of Valgrind tool suite+instrumenting Easeofuse,Accuracy programcode VII. DISCUSSIONOFDETECTIONMETHODSAND VIII. CONCLUSION&FUTUREDIRECTIONS MITIGATIONTECHNIQUES Wehaveconductedacomprehensiveassessmentofthemost The application analysis method employed in 32.3% and currentandcriticaltoolsfordetectingdataracebugs.Wehave 45.4%oftheanalyzedstudies,respectively,wasstaticanalysis organized these tools into categories based on the specific and dynamic analysis. The method of hybrid analysis was types of techniques they have used for bug identification. employed by the remaining 22.3%. A diagram showing this This categorization can help researchers understand which is shown in Fig15(a).As demonstrated in Figure15(b), the types of techniques have been the focus of previous detec- adoption of detecting techniques has also changed, impacting tors and provide insights for developing new algorithms that conventional procedures. Static procedures were one of the can complement existing tools. Furthermore, we have briefly main methods for detection in the early years, but as the 20th discussed various techniques that have been used in recent
century approaches, dynamic and hybrid techniques become times to enhance the effectiveness and efficiency of data race more prominent. Because static analysis concentrates more detection.Thesetechniquesincludemethodssuchassymbolic on code features than code-level analysis, it may be more execution,fuzzing,guidedcoverage,proportionalanalysis,and commonly used than code-level analysis. In addition, the cost staticslicing.Researcherscan leveragethesetechniqueswhen of static analysis is less than that of the other two techniques. designingnewconcurrencybugdetectors.Astatisticalstudyof To run the source code, dynamic needs extra resources like severaldataracebugdetectorsisalsoincludedinouranalysis, emulators or actual hardware. However, as technology ad- takingintoaccountthedifferenttypesofapproachesthateach vanced, programs grew more complicated and were harder one uses. Notably, the discovery of data race bugs frequently to solve using static analysis. Therefore, in order to lower makesuseofdynamicanalyticapproaches.Wehaveproposed the complexity and subsequently the overheads, formal and future study avenues based on our findings, which can help dynamic methods of symbolic execution were employed. researchers working on data race detection.Additionally, we Based on the review study, we also infer that the use of can conclude that the majority of currently available detectors machine learning has been lower in the detection of data race experiencefalsenegativesifwetakeintoaccounttheaccuracy, bugs which can be a good direction to explore. precision, performance, and application of the devices. These results might direct future research efforts aimed at reducing A. Mitigation Techniques the drawbacks of data race detection.Overall, we expect to see significant advancement in the area of concurrency bug Once a vulnerability has been detected, several strategies detection.Ouranalysishasyieldedvaluableinsightsintothese canbeusedtomitigateit.Theseincludelockingandsynchro- limitations and therefore our view of the present scenario and nizationmechanisms,suchassemaphoresandmutexes,which future scope can be seen as : can prevent race conditions and deadlocks. Other mitigation strategiesincludeinputvalidation,errorchecking,andmemory • Concurrency bugs are rarely discovered due to two pri- protection mechanisms such as ASLR and DEP. Software mary factors: the immense and exponentially expanding developers can also use programming languages and libraries interleaving possibilities as code size increases, and the designed to reduce the risk of concurrency-related vulnerabil- fact that these bugs are typically hidden within uncom- ities, such as Rust and Go. mon and unique memory access interleaving patterns.TABLEV CONCURRENCYBUGDETECTIONFUZZERS Fuzzer Author Year PUT Contribution Limitation ConFuzz[115] Padhiyaret.al 2021 OCamlPrograms Builds on AFL to generate inputs Computationally thatmaximizecoverageofconcur- expensive and can rent event-driven programs’ non- generatefalsepositives deterministicstatespace. CalFuzzer[120] Koushiksenet.al 2007 CPrograms Uses the RAPOS algorithm to needstoexplicitlycontrol reduce sampling non-uniformity, the scheduler of the con- leadingtomoreefficientandeffec- currentprogramtotrigger tivetesting. concurrencybugs Atomfuzzer[121] Parket.al 2008 JAVA Real-world flaws are effectively Computationally found by Java’s randomized dy- expensive,FalsePositive namic analysis technique, which alters the thread scheduler to dis- cover atomicity violations with a highlikelihood. Race Koushiksenet.al 2008 JAVA Propose a new approach that is False Positive, Scalibility, Fuzzer[113] based on the idea of directing the Overhead randomtestingprocesstowardsar- eas of the program that are more likelytocontainraceconditions. Deadlockfuzzer[114]PallaviJoshiet.al 2009 JAVA UsestheLDGtoidentifypotential FalseNegative,FalsePos- deadlocks and then use a random itive,Overhead threadschedulertocreateapoten- tialdeadlock Assetfuzzer[122] Zhifenget.al 2010 Cprograms Themethodprunesthoseinterleav- FalseNegative,Overhead ingsthatarefreeofviolationsand infers possible violations that do notshowupinaparticularexecu- tion. Magicfuzzer[123] YanCaiet.al 2012 Cprograms Founded on a unique strategy that Overhead and False Posi- prunes lock dependencies repeat- tive edly until none of them has an incomingoroutgoingedge. RAZZER[116] DaeR.Jeonget.al 2019 LinuxKernel Combines the strengths of both False Positive, Scalibility, statelessandstatefulfuzzingtofind Overhead kernelracebugs DDRace[117] Yuanet.al 2023 LinuxKernel Usesdirectedfuzzingtodetectin- FalseNegative,Overhead puts that cause concurrency UAF vulnerabilitiesafterithasidentified target driver interfaces and race pairs. KRACE[118] MengXuet.al 2020 LinuxKernel Combines the strengths of both FalseNegative,FalsePos- statelessandstatefulfuzzingtofind itive,Overhead data race bugs in kernel file sys- tems CONZZER[119] Zu-MingJianget.al 2022 UserandKernel Technique that uses knowledge of Complex, Computation- the program’s context and direc- ally Expensive,cannot tionofexecutiontogeneratemore detectalldataraces effective inputs for detecting data- races. • Recent research has made progress in detecting and detectors, addressing the accuracy-efficiency trade-off, mitigating race conditions in concurrent execution but anddesigningdetectorstofindrealsourcecodebugsand challenges remain. Balancing performance and security library-related issues iscrucial,andresearchersareexploringdynamicanalysis • Detectorsoftenrequiremanualannotations,limitingtheir techniques while seeking more automated methods for use in complex programs. Researchers aim to automate
identifying race conditions. Future research should focus these detectors.Some detectors generate excessive false on improved techniques, formal methods for correctness, positives, hindering bug identification and resolution. and secure programming languages. Improving accuracy enhances their applicability. A two- • Staticdetectorsproducefewfalsenegativesbutnumerous step detection process, akin to hybrid detectors, could be false positives, posing challenges for debugging. Dy- employed, with a focus on improving convenience.Most namic detectors can miss some concurrency bugs due detectors are designed for C/C++ and Java, while lan- to unexecuted code and may be inefficient. Research guages like Objective-C and Python are also prevalent. directions include reducing false negatives in dynamic There’s a need for detectors compatible with a broaderFig.15. (a)Showsthedistributionoftechniquesusedindataracedetection(b)Showsthestatisticalanalysisofdifferentdetectiontechniquesusedoverthe years. range of programming languages. • A promising research direction in the field of data • Some dynamic detectors slow down program execu- race bugs, can be a detection solution that focuses on tion due to excessive instrumentation. Researchers can the collaboration between software and hardware. While mitigate this by employing strategies like sampling or software-only solutions are versatile and can be used usingvirtualmachinesformonitoring.Dynamicdetectors on different platforms, they often slow down program oftenexecuteprogramsredundantly,impactingefficiency. performance. On the other hand, some systems try to Strategiesshouldbedevelopedtoeliminateredundantdy- make hardware changes to improve efficiency, but these namicanalyses.Tomakedetectorssuitableforproduction modifications might not work well in a wide range of environments, researchers should work on hardware and situations. algorithms to minimize runtime overhead.Deterministic REFERENCES execution techniques reduce non-determinism in large programs, improving software reliability and aiding data [1] Wolfgang Bauer et al. “Humans in Industry 5.0– race bug detection. Predictive analysis can identify safe A Paradigm Shift”. In: Procedia CIRP 110 (2022), code, reducing the number of interleavings to be ana- pp. 4–9. lyzed. [2] Jiewu Leng et al. “Industry 5.0: Prospect and ret- • UseofFormalmethodssuchasmodelcheckingandSym- rospect”. In: Journal of Manufacturing Systems 65 bolic execution reduces the complexity of the programs (2022), pp. 279–295. ISSN: 0278-6125. DOI: https: and thus needs to be explored more in thearea of guided //doi.org/10.1016/j.jmsy.2022.09.017. URL: symbolic execution.https://www.sciencedirect.com/science/article/pii/ neptune.netcomp.monash.edu.au/cpe9001/assets/ S0278612522001662. readings/www uguelph ca ∼tgallagh ∼tgallagh.html. [3] Lanyue Lu et al. “A study of Linux file system evo- Accessed on: July 31, 2023. 2007. lution”. In: Transactions on Storage 10.1 (Jan. 2014), [18] TOP500.Org. Top 500 Supercomputer Sites. http:// 3:1–3:32. www.top500.org/. Retrieved May 8, 2019. 2019. [4] C. Min et al. “Understanding Manycore Scalability of [19] Working Group for POSIX. IEEE Standard for Infor- File Systems”. In: Proceedings of the 2016 USENIX mation Technology–Portable Operating System Inter- AnnualTechnicalConference(ATC).Denver,CO,June face (POSIX(R)) Base Specifications, Issue 7. IEEE 2016. Std 1003.1-2017 (Rev. of IEEE Std 1003.1-2008). [5] J. Huang, M. K. Qureshi, and K. Schwan. “An Evo- Tech.rep.IEEE,Jan.2018,pp.1–3951.DOI:10.1109/ lutionary Study of Linux Memory Management for IEEESTD.2018.8277153. Fun and Profit”. In: Proceedings of the 2016 USENIX [20] Guanjun Lin et al. “Software vulnerability detection Annual Technical Conference (ATC). Berkeley, CA, usingdeepneuralnetworks:asurvey”.In:Proceedings USA, June 2016, pp. 465–478. ISBN: 978-1-931971- of the IEEE 108.10 (2020), pp. 1825–1848. 30-0. [21] PengZengetal.“SoftwareVulnerabilityAnalysisand [6] A. Aghayev et al. “File Systems Unfit As Distributed Discovery Using Deep Learning Techniques: A Sur- Storage Backends: Lessons from 10 Years of Ceph vey”. In: IEEE Access 8 (2020), pp. 197158–197172. Evolution”. In: Proceedings of the 27th ACM Sympo- DOI: 10.1109/ACCESS.2020.3034766. sium on Operating Systems Principles (SOSP). On- [22] CVE details. Vulnerabilities as Threats to IT Infras- tario, Canada, Oct. 2019. tructure. https://www.cvedetails.com/browse-by- [7] MITRE Corporation. CVE-2009-1235. https://cve. date.php [Accessed: (June 28, 2023)]. 2022. mitre.org/cgibin/cvename.cgi?name=CVE-2009-1235 [23] Zhen Li et al. “A survey of FPGA-based accelerator [Accessed: (22 august 2023)]. 2009. systems”. In: ACM Computing Surveys (CSUR) 50.3 [8] J. Corbet. Unprivileged filesystem mounts, 2018 edi- (2017), p. 34. tion. 2022. URL: https://lwn.net/Articles/755593. [24] Peter M. Chen, Wen-Tsuen Hwang, and David J. [9] P. Fonseca, R. Rodrigues, and B. B. Brandenburg. Farber. “DERT: A Software Tool for Detecting and “SKI: Exposing Kernel Concurrency Bugs Through Eliminating Racy Variables”. In: Proceedings of the Systematic Schedule Exploration”. In: Proceedings of 1990InternationalConferenceonParallelProcessing. the 11th USENIX Symposium on Operating Systems Vol. 1. 1990, pp. 375–378. Design and Implementation (OSDI). Broomfield, Col- [25] Manuel Castro. “An Empirical Study of Operating
orado, Oct. 2014. Systems Errors”. In: Proceedings of the 18th ACM [10] W. Xu et al. “Fuzzing File Systems via Two- Symposium on Operating Systems Principles (SOSP). Dimensional Input Space Exploration”. In: Proceed- 2001, pp. 73–88. ings of the 40th IEEE Symposium on Security and [26] ShengYangetal.“FindingandUnderstandingBugsin Privacy (Oakland). San Francisco, CA, May 2019. C Compilers”. In: Proceedings of the 32nd ACM SIG- [11] S. Kim et al. “Finding Semantic Bugs in File Systems PLAN Conference on Programming Language Design with an Extensible Fuzzing Framework”. In: Proceed- and Implementation (PLDI). 2011, pp. 283–294. ings of the 27th ACM Symposium on Operating Sys- [27] Andrew S. Tanenbaum and Herbert Bos. Modern Op- tems Principles (SOSP). Ontario, Canada, Oct. 2019. erating Systems. 4th. Pearson, 2014. [12] bugzilla.kernel.Kernel.orgBugzilla-Btrfsbugentries. [28] David R. Butenhof. Programming with POSIX https://bugzilla.kernel.org/buglist.cgi?component=btrfs Threads. Addison-Wesley, 1997. [Accessed: (22 august 2023)]. 2022. [29] Abraham Silberschatz, Peter B. Galvin, and Greg [13] MITRE Corporation. F2FS CVE entries. http://cve. Gagne.OperatingSystemConcepts.10th.Wiley,2018. mitre.org/cgibin/cvekey.cgi?keyword=f2fs [Accessed: [30] J. P. Lewis and Mitchell Berg. Threads Primer: A (22 august 2023)]. 2022. Guide to Multithreaded Programming. Prentice Hall, [14] bugzilla.kernel.Kernel.orgBugzilla-ext4bugentries. 1998. https://bugzilla.kernel.org/buglist.cgi?component=ext4 [31] Abraham Silberschatz, Peter B. Galvin, and Greg [Accessed: (22 august 2023)]. 2022. Gagne. Operating System Concepts. 9th. Wiley, 2014. [15] OhadRodeh,JosefBacik,andChrisMason.“BTRFS: [32] Maurice Herlihy and Nir Shavit. The Art of Multipro- The Linux B-tree filesystem”. In: ACM Transactions cessor Programming. Morgan Kaufmann, 2008. on Storage (TOS) (2013). [33] MarkMoir,DanielNussbaum,andOriShalev.“Using [16] bugzilla.kernel. Kernel.org Bugzilla. https://bugzilla. elimination to implement scalable and lock-free FIFO kernel.org [Accessed: (22 august 2023)]. 2022. queues”.In:ACMTransactionsonProgrammingLan- [17] T. Gallagher. Archived webpage: Concurrent Pro- guages and Systems (TOPLAS) 29.3 (2007), pp. 1–34. gramming (CPE9001) - Monash University. https: //web.archive.org/web/20071212183729/http://[34] Timothy L. Harris. “A pragmatic implementation of and Communications Workshops (HPCCWS) (2017), non-blocking linked-lists”. In: Distributed Computing pp. 58–65. 14.3 (2001), pp. 195–212. [51] Wessam Hassanein, Layali Rashid, and Moustafa [35] Intel. Cramming More Components onto Integrated Hammad. “Analyzing the Effects of Hyperthreading Circuits Moore’s Law. Accessed on July 10, 2023. on the Performance of Data Management Systems”. URL: https://www.intel.com/content/www/us/en/ In: International Journal of Parallel Programming 36 history/virtual-vault/articles/moores-law.html. (Apr. 2008), pp. 206–225. DOI: 10.1007/s10766-007- [36] Ethan Mollick. “Establishing Moore’s Law”. In: An- 0066-x. nals of the History of Computing, IEEE 28 (Aug. [52] Okonta Emmanuel and D Ajani. “Performance Eval- 2006), pp. 62–75. DOI: 10.1109/MAHC.2006.45. uation of Hyper Threading Technology Architecture [37] Yevgen Voronenko. “Library Generation For Linear UsingMicrosoftOperatingSystemPlatform”.In:West Transforms Dissertation”. In: (May 2012). African Journal of Industrial and Academic Research [38] John L. Hennessy and David A. Patterson. Computer (July 2019). Architecture:AQuantitativeApproach.Elsevier,2011. [53] Lili Bo et al. “A Comprehensive Analysis of NVD [39] Wen-mei W. Hwu. “SIMD architecture and vector- Concurrency Vulnerabilities”. In: 2022 IEEE 22nd ization”. In: ACM SIGARCH Computer Architecture International Conference on Software Quality, Relia- News 39.1 (2011), pp. 2–13. bility and Security (QRS). 2022, pp. 9–18. DOI: 10. [40] Bruce Jacob, Spencer Ng, and David T. Wang. Mem- 1109/QRS57517.2022.00012. ory systems: cache, DRAM, disk. Morgan Kaufmann, [54] Shin Hong and Moonzoo Kim. “A survey of race bug 2011. detection techniques for multithreaded programmes”. [41] R. Dutta and N. K. Jha. “Symmetric Multiprocess- In: Software Testing, Verification and Reliability 25 ing”. In: Handbook of Hardware/Software Codesign. (Dec. 2014). DOI: 10.1002/stvr.1564. Boston, MA: Springer, 2017. [55] Ali Tehrani Jamsaz et al. “DeepRace: Finding [42] J. Bosch. “Symmetric Multiprocessing (SMP)”. In: Data Race Bugs via Deep Learning”. In: CoRR Encyclopedia of Parallel Computing. Boston, MA: abs/1907.07110(2019).arXiv:1907.07110.URL:http: Springer, 2011. //arxiv.org/abs/1907.07110. [43] A.Silberschatz,P.B.Galvin,andG.Gagne.Symmetric [56] Cormac Flanagan, Stephen N Freund, and Joshua B Multiprocessing. Wiley, 2018. Saxe.“ThreadSafe:Staticanalysisforthread-locality”. [44] S. P. Dandamudi. Symmetric Multiprocessing. Boston, In: ACM Transactions on Programming Languages MA: Springer, 2005. and Systems (TOPLAS) 32.4 (2010), p. 13. [45] R. K. Gupta. “Heterogeneous Multiprocessor Archi- [57] Martin Abadi, Cormac Flanagan, and Stephen N. Fre-
tectures for Embedded Systems”. In: Proceedings of und. “Types for Safe Locking: Static Race Detection the IEEE 89.3 (Mar. 2001), pp. 420–437. for Java”. In: ACM Transactions on Programming [46] S. Kumar, D. Raghavendra, and L. Kallianpur. “A LanguagesandSystems(TOPLAS)28(2006),pp.207– Survey of Asymmetric Multiprocessing in Modern 255. SoCs”. In: IEEE Design & Test 33.1 (Feb. 2016), [58] Dawson Engler and Kathryn Ashcraft. “RacerX: Ef- pp. 45–55. fective,StaticDetectionofRaceConditionsandDead- [47] D. Lebel, J. Levinsky, and D. Morin. “Asymmetric locks”. In: ACM SIGOPS Operating Systems Review Multiprocessing in Mobile and Embedded Systems”. 37.5 (2003), pp. 237–252. In:2013IEEE19thInternationalSymposiumonAsyn- [59] Mandana Vaziri, Frank Tip, and Julian Dolby. “Asso- chronous Circuits and Systems. June 2013, pp. 49–56. ciating Synchronization Constraints with Data in an [48] Subhash Saini et al. “The impact of hyper-threading Object-Oriented Language”. In: ACM Sigplan Notices on processor resource utilization in production appli- 41 (2006), pp. 334–345. cations”. In: 2011 18th International Conference on [60] Jason W. Voung, Ranjit Jhala, and Sorin Lerner. “Re- High Performance Computing. 2011, pp. 1–10. DOI: lay: Static Race Detection on Millions of Lines of 10.1109/HiPC.2011.6152743. Code”. In: Joint Meeting of the European Software [49] Rizwan Ali et al. “Intel Hyper-Threading Technol- Engineering Conference and the ACM SIGSOFT In- ogy to Achieve Computational Efficiency HIGH- ternational Symposium on Foundations of Software PERFORMANCE COMPUTING”. In: dell high per- Engineering. Dubrovnik, Croatia, 2007, pp. 205–214. formace computing (Dec. 2003). [61] Satish Chandra et al. “Using static analysis to find [50] Subhash Saini and Robert T. Hood. “Performance bugs”. In: IEEE Software 25.5 (2008), pp. 22–29. Evaluation of Intel Broadwell Nodes Based Super- [62] Cormac Flanagan, Stephen N Freund, and Joshua B computer Using Computational Fluid Dynamics and Saxe.“ThreadSafe:Staticanalysisforthread-locality”. Climate Applications”. In: 2017 IEEE 19th Interna- In: ACM Transactions on Programming Languages tional Conference on High Performance Computing and Systems (TOPLAS) 32.4 (2010), p. 13.[63] Joshua Berdine et al. “Static detection of concurrency Proceedings of the 7th Joint Meeting of the Euro- defects”. In: ACM SIGPLAN Notices 43.1 (2008), pean Software Engineering Conference and the ACM pp. 205–216. SIGSOFT Symposium on the Foundations of Software [64] Juraj Somorovsky et al. “CogniCrypt: supporting de- Engineering. New York: ACM, 2009, pp. 13–22. velopers in using cryptography”. In: IEEE Security & [75] C. Radoi and D. Dig. “Practical Static Race Detection Privacy 14.4 (2016), pp. 68–77. for Java Parallel Loops”. In: Proceedings of the Inter- [65] M. Ben-Ari. “Tool Presentation: Teaching Concur- nationalSymposiumonSoftwareTestingandAnalysis. rency and Model Checking”. In: Proceedings of the New York: ACM, 2013, pp. 178–190. InternationalSPINWorkshoponModelCheckingSoft- [76] Bozhen Liu* et al. “When Threads Meet Events: Effi- ware. Cham, Switzerland: Springer, 2009, pp. 6–11. cient and Precise Static Race Detection with Origins”. DOI: 10.1007/978-3-642-02652-2\ 5. In: Proceedings of the 42nd ACM SIGPLAN Inter- [66] Nikolaos Koutsopoulos et al. “Advancing data race national Conference on Programming Language De- investigation and classification through visualization”. sign and Implementation (PLDI ’21). Virtual, Canada: In: 2015 IEEE 3rd Working Conference on Software ACM, June 2021, 15 pages. DOI: 10.1145/3453483. Visualization (VISSOFT) (2015), pp. 200–204. URL: 3454073. URL: https://doi.org/10.1145/3453483. https://api.semanticscholar.org/CorpusID:14574499. 3454073. [67] D. Qi, N. Gu, and J. Su. “Detecting Data Race [77] Bradley Swain et al. “OpenRace: An Open in Network Applications Using Static Analysis”. In: Source Framework for Statically Detecting Data Proceedings of the International Conference on Net- Races”. In: Coderrect Inc. (2021). Emails: workingandNetworkApplications(NaNA).Oct.2019, brad@coderrect.com, bozhen.liu@tamu.edu, pp. 313–318. DOI: 10.1109/NaNA.2019.00061. peiming@coderrect.com, yanze@coderrect.com, [68] Chunhua Yang and Zhendong Su. “SWORD: a addison.crump@coderrect.com, ro- developer-oriented tool for detecting concurrency han.khera@coderrect.com, jeff@coderrect.com”, bugs”. In: Proceedings of the 2008 ACM SIGPLAN [78] Utpal Bora et al. “LLOV: A Fast Static Data-Race conference on Programming language design and im- Checker for OpenMP Programs”. In: ACM Trans. plementation. ACM. 2008, pp. 45–56. Archit. Code Optim. 17.4 (Dec. 2020). ISSN: 1544- [69] V. Kahlon et al. “Static Data Race Detection for 3566. DOI: 10.1145/3418597. URL: https://doi.org/10. Concurrent Programs with Asynchronous Calls”. In: 1145/3418597. Proceedings of the 7th Joint Meeting of the Euro- [79] BradleySwainetal.“OMPRacer:AScalableandPre- pean Software Engineering Conference and the ACM cise Static Race Detector for OpenMP Programs”. In: SIGSOFT Symposium on the Foundations of Software SC20, November 9-19, 2020, Is Everywhere We Are. Engineering (ESEC/FSE). 2009, pp. 13–22. DOI: 10. Affiliations and emails: Computer Science and Engi- 1145/1595696.1595701. neering, Texas A&M University, College Station, TX,
[70] M. Naik, A. Aiken, and J. Whaley. “Effective Static brad, yanzeli, peiming@tamu.edu, jeff@cse.tamu.edu; RaceDetectionforJava”. In:ProceedingsoftheACM Center for Applied Scientific Computing, Lawrence SIGPLANConferenceonProgrammingLanguageDe- Livermore National Laboratory, Livermore, CA, ila- sign and Implementation (PLDI). New York, NY, guna, georgakoudis1@llnl.gov;0 Coderrect Inc, Col- USA: Association for Computing Machinery, 2006, lege Station, TX, brad@coderrect.com. IEEE. College pp. 308–319. DOI: 10.1145/1133981.1134018. Station, TX and Livermore, CA, 2020. ISBN: 978-1- [71] P. Pratikakis, J. S. Foster, and M. Hicks. “LOCK- 7281-9998-6. SMITH: Practical Static Race Detection for C”. In: [80] Vesal Vojdani et al. “Static Race Detection for Device ACM Transactions on Programming Languages and Drivers: The Goblint Approach”. In: Proceedings of Systems (TOPLAS) 33.1 (Jan. 2011), pp. 1–55. DOI: the31stIEEE/ACMInternationalConferenceonAuto- 10.1145/1889997.1890000. matedSoftwareEngineering.ASE’16.Singapore,Sin- [72] S. Qadeer and D. Wu. “KISS: Keep It Simple and gapore: Association for Computing Machinery, 2016, Sequential”. In: Proceedings of the 25th Annual ACM pp. 391–402. ISBN: 9781450338455. DOI: 10.1145/ SIGPLANConferenceonProgrammingLanguageDe- 2970276.2970337. URL: https://doi.org/10.1145/ sign and Implementation. New York: ACM, 2004, 2970276.2970337. pp. 14–24. [81] Stefan Savage et al. “Eraser: a dynamic data race [73] R.Agarwaletal.“OptimizedRun-timeRaceDetection detector for multithreaded programs”. In: ACM SIG- and Atomicity Checking Using Partial Discovered PLAN Notices. Vol. 29. 6. ACM. 1994, pp. 27–37. Types”. In: Proceedings of the 20th IEEE/ACM In- [82] Yannis Smaragdakis et al. “Sound Predictive Race ternational Conference on Automated Software Engi- Detection in Polynomial Time”. In: ACM Sigplan neering. New York: ACM, 2005, pp. 233–242. Notices 47 (2012), pp. 387–400. [74] V. Kahlon et al. “Static Data Race Detection for [83] Jong-Deok Choi et al. “Efficient and Precise Data Concurrent Programs with Asynchronous Calls”. In: Race Detection for Multithreaded Object-OrientedPrograms”. In: ACM Sigplan Notices 37 (2002), SIGPLAN2008conferenceonProgramminglanguage pp. 258–269. designandimplementation.ACM.2008,pp.335–348. [84] Yuan Yu, Thomas Rodeheffer, and Wei Chen. “Race- [97] Cormac Flanagan and Stephen N Freund. “FastTrack: track: Efficient Detection of Data Race Conditions efficientandprecisedynamicracedetection”.In:ACM via Adaptive Tracking”. In: ACM SIGOPS Operating SIGPLAN Notices 39.6 (2004), pp. 121–133. Systems Review. Vol. 39. ACM. 2005, pp. 221–234. [98] Patrice Godefroid, Nils Klarlund, and Koushik Sen. [85] Min Xu, Rastislav Bod´ık, and Mark D. Hill. “A “ConTest: Speculative testing for concurrent pro- Serializability Violation Detector for Shared-Memory grams”. In: Proceedings of the 2005 ACM SIGPLAN ServerPrograms”.In:ACMSigplanNotices40(2005), conference on Programming language design and im- pp. 1–14. plementation. ACM. 2005, pp. 52–61. [86] Paruj Ratanaworabhan et al. “Detecting and Tolerat- [99] Shan Lu et al. “Avio: Detecting Atomicity Violations ing Asymmetric Races”. In: ACM SIGPLAN Notices. viaAccess-InterleavingInvariants”.In:IEEEMicro27 Vol. 44. ACM. 2009, pp. 173–184. (2007), pp. 26–35. [87] Guoliang Jin et al. “Instrumentation and Sampling [100] Ying Shi et al. “Do I Use the Wrong Definition?: Strategies for Cooperative Concurrency Bug Isola- Defuse: Definition-Use Invariants for Detecting Con- tion”. In: ACM Sigplan Notices 45 (2010), pp. 241– currency and Sequential Bugs”. In: ACM Sigplan No- 255. tices 45 (2010), pp. 160–174. [88] Soyeon Park, Richard W. Vuduc, and Mary Jean [101] Wenguang Zhang et al. “Conseq: Detecting Concur- Harrold. “Falcon: Fault Localization in Concurrent rency Bugs Through Sequential Errors”. In: ACM Programs”. In: Proceedings of the 32nd ACM/IEEE Sigplan Notices 39 (2011), pp. 251–264. International Conference on Software Engineering. [102] Baris Kasikci, Cristian Zamfir, and George Candea. Vol. 1. 2010, pp. 245–254. “Racemob: Crowdsourced Data Race Detection”. In: [89] Soyeon Park, Richard Vuduc, and Mary Jean Harrold. Twenty-FourthACMSymposiumonOperatingSystems “A Unified Approach for Localizing Non-Deadlock Principles. 2013, pp. 406–422. Concurrency Bugs”. In: 2012 IEEE 5th International [103] Dongdong Deng, Wenguang Zhang, and Shan Lu. Conference on Software Testing, Verification and Val- “EfficientConcurrency-BugDetectionAcrossInputs”. idation. IEEE. 2012, pp. 51–60. In: ACM Sigplan Notices 48 (2013), pp. 785–802. [90] BrandonLucia,BrianP.Wood,andLuisCeze.“Isolat- [104] Baris Kasikci, Cristian Zamfir, and George Candea. ing and Understanding Concurrency Errors Using Re- “Automated Classification of Data Races Under Both constructed Execution Fragments”. In: ACM Sigplan Strong and Weak Memory Models”. In: ACM Trans- Notices 46 (2011), pp. 378–388. actions on Programming Languages & Systems 37 [91] Min Zhang et al. “A Lightweight System for De- (2015), pp. 1–44. tecting and Tolerating Concurrency Bugs”. In: IEEE [105] Julian Seward, Nicholas Nethercote, and Josef Wei-
Transactions on Software Engineering 42.10 (2016), dendorfer. “Valgrind: A framework for heavyweight pp. 899–917. dynamic binary instrumentation”. In: Proceedings of [92] Yifei Cai and Wing-Kwong Chan. “MagicFuzzer: the 2005 ACM SIGPLAN conference on Programming Scalable Deadlock Detection for Large-Scale Appli- language design and implementation. ACM. 2005, cations”. In: International Conference on Software pp. 89–100. Engineering. 2012, pp. 606–616. [106] Zheng Cui, Xuejun Yang, and Yiying Zhou. “Road- [93] Yifei Cai and Wing-Kwong Chan. “MagicLock: Scal- Runner:TowardsAutomaticCheckpointingofWhole- able Detection of Potential Deadlocks in Large-Scale System Computations”. In: Proceedings of the 2013 Multithreaded Programs”. In: IEEE Transactions on USENIX Annual Technical Conference (USENIX Software Engineering 40 (2014), pp. 266–281. ATC). USENIX Association. 2013, pp. 179–190. [94] Wei Zhang, Chang Sun, and Shan Lu. “ConMem: De- [107] WenguangChen,YingLin,andJinglingXue.“Saturn: tecting Severe Concurrency Bugs Through an Effect- efficient software error detection using relaxed depen- Oriented Approach”. In: ACM SIGARCH Computer dences”.In:IEEETransactionsonSoftwareEngineer- Architecture News 38 (2010), pp. 179–192. ing 32.11 (2006), pp. 873–890. [95] Konstantin Serebryany et al. “ThreadSanitizer: data [108] M. D. Bond, K. E. Coons, and K. S. McKinley. race detection in practice”. In: Proceedings of the “PACER: Proportional Detection of Data Races”. In: 2012 ACM SIGPLAN International Conference on Proceedings of the 31st Annual ACM SIGPLAN Con- Object-Oriented Programming, Systems, Languages, ferenceonProgrammingLanguageDesignandImple- and Applications. ACM. 2012, pp. 265–284. mentation. ACM. New York, 2010, pp. 255–268. [96] Madanlal Musuvathi, Satish Narayanasamy, and Se- [109] E. Pozniansky and A. Schuster. “MultiRace: Efficient bastianBurckhardt.“CHESS:asystematictestingtool On-the-FlyDataRaceDetectioninMultithreadedC++ forconcurrentprograms”.In:ProceedingsoftheACM Programs”.In:ConcurrentComputation:Practiceand Experience 19 (2007), pp. 327–340.[110] Z. D. Wu et al. “Collaborative Technique for Con- URL: https://www.ndss-symposium.org/ndss-paper/ currency Bug Detection”. In: International Journal of auto-draft-198/. Parallel Programming 43 (2015), pp. 260–285. [120] Koushik Sen. “Effective Random Testing of Con- [111] Y. Wang et al. “Automatic Detection, Validation, and current Programs”. In: Proceedings of the 22nd Repair of Race Conditions in Interrupt-Driven Em- IEEE/ACM International Conference on Automated bedded Software”. In: IEEE Transactions on Software Software Engineering. ASE ’07. Atlanta, Georgia, Engineering(Apr.2020).EarlyAccess. DOI:10.1109/ USA: Association for Computing Machinery, 2007, TSE.2020.2989171. pp. 323–332. ISBN: 9781595938824. DOI: 10.1145/ [112] J. Yang, B. Jiang, and W. K. Chan. “HistLockC: 1321631.1321679. URL: https://doi.org/10.1145/ Precise memory access maintenance without lockset 1321631.1321679. comparison for complete hybrid data race detection”. [121] Chang-Seo Park and Koushik Sen. “Randomized Ac- In:IEEETransactionsonReliability67.3(Sept.2018), tive Atomicity Violation Detection in Concurrent Pro- pp. 786–801. DOI: 10.1109/TR.2018.2832226. grams”. In: Proceedings of the 16th ACM SIGSOFT [113] KoushikSen.“RaceDirectedRandomTestingofCon- International Symposium on Foundations of Software current Programs”. In: Proceedings of the 29th ACM Engineering.SIGSOFT’08/FSE-16.Atlanta,Georgia: SIGPLANConferenceonProgrammingLanguageDe- AssociationforComputingMachinery,2008,pp.135– sign and Implementation. PLDI ’08. Tucson, AZ, 145. ISBN: 9781595939951. DOI: 10.1145/1453101. USA: Association for Computing Machinery, 2008, 1453121. URL: https://doi.org/10.1145/1453101. pp. 11–21. ISBN: 9781595938602. DOI: 10.1145/ 1453121. 1375581.1375584. URL: https://doi.org/10.1145/ [122] Zhifeng Lai, S. C. Cheung, and W. K. Chan. “De- 1375581.1375584. tecting Atomic-Set Serializability Violations in Multi- [114] Pallavi Joshi et al. “A Randomized Dynamic Program threaded Programs through Active Randomized Test- AnalysisTechniqueforDetectingRealDeadlocks”.In: ing”. In: Proceedings of the 32nd ACM/IEEE Interna- Proceedingsofthe30thACMSIGPLANConferenceon tional Conference on Software Engineering - Volume Programming Language Design and Implementation. 1. ICSE ’10. Cape Town, South Africa: Association PLDI’09.Dublin,Ireland:AssociationforComputing for Computing Machinery, 2010, pp. 235–244. ISBN: Machinery,2009,pp.110–120.ISBN:9781605583921. 9781605587196. DOI: 10.1145/1806799.1806836. DOI: 10.1145/1542476.1542489. URL: https://doi.org/ URL: https://doi.org/10.1145/1806799.1806836. 10.1145/1542476.1542489. [123] Yan Cai and W. K. Chan. “MagicFuzzer: Scalable [115] Sumit Padhiyar and K. C. Sivaramakrishnan. “Con- Deadlock Detection for Large-Scale Applications”. Fuzz: Coverage-Guided Property Fuzzing for Event- In: Proceedings of the 34th International Confer- DrivenPrograms”.In:PracticalAspectsofDeclarative ence on Software Engineering. ICSE ’12. Zurich, Languages. Ed. by Jose´ F. Morales and Dominic Or- Switzerland: IEEE Press, 2012, pp. 606–616. ISBN: chard. Cham: Springer International Publishing, 2021, 9781467310673. pp. 127–144. ISBN: 978-3-030-67438-0.
[116] Dae R. Jeong et al. “Razzer: Finding Kernel Race Bugs through Fuzzing”. In: 2019 IEEE Symposium on Security and Privacy (SP). 2019, pp. 754–768. DOI: 10.1109/SP.2019.00017. [117] Ming Yuan et al. “DDRace: Finding Concurrency UAF Vulnerabilities in Linux Drivers with Directed Fuzzing”. In: 32nd USENIX Security Symposium, USENIX Security 2023, Anaheim, CA, USA, August 9-11,2023.Ed.byJosephA.CalandrinoandCarmela Troncoso. USENIX Association, 2023. URL: https: //www.usenix.org/conference/usenixsecurity23/ presentation/yuan-ming. [118] MengXuetal.“Krace:DataRaceFuzzingforKernel File Systems”. In: 2020 IEEE Symposium on Security andPrivacy(SP).2020,pp.1643–1660.DOI:10.1109/ SP40000.2020.00078. [119] Zu-Ming Jiang et al. “Context-Sensitive and Direc- tionalConcurrencyFuzzingforData-RaceDetection”. In: 29th Annual Network and Distributed System Se- curitySymposium,NDSS2022,SanDiego,California, USA, April 24-28, 2022. The Internet Society, 2022.
2312.17726 3202 ceD 92 ]RC.sc[ 1v62771.2132:viXra Noname manuscript No. (will be inserted by the editor) Comparing Effectiveness and Efficiency of Interactive Application Security Testing (IAST) and Runtime Application Self-Protection (RASP) Tools in a Large Java-based System Aishwarya Seth · Saikath Bhattacharya · Sarah Elder · Nusrat Zahan · Laurie Williams thedateofreceiptandacceptance shouldbeinsertedlater Abstract CONTEXT:Securityresourcesarescarce,andpractitionersneed guidanceintheeffectiveandefficientusageoftechniquesandtoolsavailablein thecybersecurityindustryfordetectingandpreventingtheexploitationofvul- nerabilities in software, as per the practitioners’ requirements. Two emerging tool types, InteractiveApplication Security Testing (IAST) and Runtime Ap- plicationSelf-Protection(RASP),havenotbeenthoroughlyevaluatedagainst well-established counterparts such as Dynamic Application Security Testing (DAST) and Static Application Security Testing (SAST). OBJECTIVE: The goal of this research is to aid practitioners in making informed choices about the use of Interactive Application Security Testing (IAST) and Runtime Application Self-Protection (RASP) tools through an analysis of their effectiveness and efficiency in comparison with different vul- nerability detection and prevention techniques and tools. A.Seth NorthCarolinaStateUniversity E-mail:aseth@ncsu.edu S.Bhattacharya MilwaukeeSchoolofEngineering E-mail:bhattacharya@msoe.edu S.Elder NorthCarolinaStateUniversity E-mail:seelder@ncsu.edu N.Zahan NorthCarolinaStateUniversity E-mail:nzahan@ncsu.edu L.Williams NorthCarolinaStateUniversity E-mail:lauriewilliams@ncsu.edu2 AishwaryaSethetal. METHODS:WeapplyIASTandRASPonOpenMRS,anopen-sourceJava- basedonline application.We compare the efficiency andeffectiveness of IAST and RASP with techniques applied on OpenMRS in prior work: Systematic (SMPT) and Exploratory (EMPT) Manual Penetration Testing techniques, as well as SAST and DAST tools. We measure efficiency and effectiveness in terms of the number and type of vulnerabilities detected and prevented per hour. RESULTS: Our study shows IAST performed relatively well compared to other techniques, performing second-best in both efficiency and effectiveness. IASTdetectedeightTop-10OWASPsecurityriskscomparedtoninebySMPT and seven for EMPT, DAST, and SAST. IAST found more vulnerabilities thanSMPT.TheefficiencyofIAST(2.14VpH)issecondtoonlyEMPT(2.22 VpH). These findings imply that our study benefited from using IAST when conducting black-box security testing. We also found RASP only prevents In- jection attacks in OpenMRS. CONCLUSION: In the context of a large, enterprise-scale web application suchasOpenMRS,RASPdoesnotreplacevulnerabilitydetection,whileIAST is a powerful tool that complements other techniques. Keywords Vulnerability Management · Web Application Security · Security Analysis Tools · Vulnerability Scanners, · Interactive Application Security Testing · Runtime Application Self-Protection 1 Introduction To build secure software while addressing the ever-growing attack surface, practitioners must utilize the available resources as efficiently as possible to remove the most vulnerabilities from software. Practitioners often use differ- ent technologies that optimize resources and increase efficiency to improve vulnerability detection efforts while not expanding the resources. Therefore, practitionerscanbenefitfromguidanceinselectingvulnerabilitydetectionand prevention techniques and tools. Priorworkcomparingvulnerabilitydetectiontechniques,suchastheseries ofstudies by Elder etal. andAustin et al. [1,2,3], does nottake into account the performance of two emerging tool types, Interactive Application Security Testing (IAST) and Runtime Application Self-Protection (RASP). IAST vul- nerabilitydetectiontoolsinjectcodeinto,i.e.,instrument,theexecutableform oftheapplication,enablingthetooltoscanthesourcecodewhilealso collect- ing dynamic information from real-time interactions with the application [4, 5]. Similarly, Rajapakse et al. [6] and Heijstek [7] noted that both IAST and RASPareemergingtoolsforsecureDevOpsandCI/CDenvironmentsandare not well investigated. On the other hand, RASP tools add another dimension of security to an application in the form of vulnerability exploitation preven-ComparingEffectiveness andEfficiencyofIASTandRASP 3 tion by detecting and blocking attacks happening in a real-time production environment. The goal of this research is to aid practitioners in making informed choices about the use of Interactive Application Security Testing (IAST) and Runtime Application Self-Protection (RASP) tools through an analysis of their effec- tiveness andefficiency in comparison with different vulnerability detection and prevention techniques and tools. Ours is one of the initial worksto compare IAST and RASP againstother automatedsecuritytestingtools,andweapplythesetoolstooneofthelargest productionsystems.Toensureourresultscanbecomparedwithpriorfindings of other techniques, we analyze IAST and RASP tools in the same system, followingthemethodologyspecifiedbyElderetal.[3].ThepriorworkbyElder etal.andAustinetal.[1,2,3]comparedfourvulnerabilitydetectiontechniques - two automated techniques, Dynamic Application Security Testing (DAST) andStaticApplicationSecurityTesting(SAST),andtwomanualvulnerability detection techniques- Exploratory Manual Penetration Testing (EMPT) and SystematicManualPenetrationTesting(SMPT).Elderetal.[3]replicatedthe Austinetal.[1,2]worktenyearslaterusingthese fourvulnerabilitydetection techniques on OpenMRS, an open-source medical records system made up of almost four million lines of Java code. While IAST is a vulnerability detectiontoolsimilar to the four techniques
examined by Elder et al. [3], RASP focuses on preventing exploitation of vul- nerabilities. While vulnerabilities only need to be detected once, preventing exploitation is an ongoing task. Consequently, RASP cannot be reasonably compared to the other techniques in terms of efficiency. For RASP, we focus on the technique’s effectiveness in terms of the vulnerabilities it can prevent exploitation of. We compare IAST against vulnerability detection techniques in terms of both effectiveness and efficiency. Our work addresses the following research questions: RQ1: What is the effectiveness of Interactive Application Security Testing (IAST), as compared to other vulnerability detection techniques, in terms of the number and types of vulnerabilities detected? RQ2: How does the efficiency in terms of vulnerabilities per hour differ be- tween IAST and other vulnerability detection techniques? RQ3: What is the effectiveness of RASP in terms of the number and types of vulnerabilities prevented relative to vulnerabilities discovered by vulnera- bility detection techniques? We studied IAST and RASP tools in terms of effectiveness and efficiency andcomparedourfindingswiththefourtechniquesandtoolsusedintheElder et al. study [8]. We performed our analysis based on the quantity and type of vulnerabilities detected by the IAST tools and the quantity and type of vulnerabilities prevented by the RASP tools to assess the effectiveness of the tools. We compute the efficiency of IAST tools using the quantity of unique and true positive vulnerabilities detected per hour.4 AishwaryaSethetal. Using IAST, we found 52 vulnerabilities not found in the previous work. TheefficiencyandeffectivenessofIASTwerecomparabletoresultsfromprior work: higher than some techniques and lower than others. RASP, on the other hand, prevented attacks against 44 vulnerabilities but was only effec- tive against Injection attacks. This work makes the following contributions: 1. Analysisandcomparisonofthe effectivenessofIAST toolsbasedonquan- tity and type of true-positive vulnerabilities detected; 2. AnalysisandcomparisonoftheefficiencyofIASTtoolsbasedonthequan- tity of true positive vulnerabilities detected per hour; and 3. Analysis of the effectiveness of RASP tools based on the number of true- positive vulnerabilities whose exploitation was prevented. The remainder of this paper proceeds as follows: Section 2 provides more detailed explanations of the tools and techniques. Section 3 describes related work. Section 4 provides an overview of the work by Elder et al. [3], which we compare our results against. Section 5 describes the method employed for answering our research questions. Section 6 states and compares the results achieved from our experiments. Section 7 discusses our interpretation of the resultsobtained,andSection8presentsthe limitationsofthe study.Section9 concludes, and Section 10 presents future work. 2 Technique Definitions In this section, we provide a more detailed explanation of the vulnerability detection and prevention techniques utilized in our work. 2.1 Techniques Added in Current Work - IAST and RASP In this paper, we focus on two tools: Interactive Application Security Testing (IAST) and Runtime Application Security Protection (RASP). IAST (Sec- tion 2.1.1) is used for vulnerability detection, and RASP (Section 2.1.2) is used to actively deter attackers by preventing vulnerabilities from being ex- ploited. Although IAST and RASP achieve different goals, they frequently lever- agesimilarunderlyingmechanics,showninFigure1.Bothtoolsareintegrated into a running application to provide information about system security. The technology used to integrate IAST and RASP tools with the application de- pendsonthetechnologiesandplatformsusedbytheapplication.Forexample, in Java systems such as OpenMRS, this integration is typically done through JavaAgents.JavaAgentsare specialsoftwarethat canbe usedto manipulate the bytecode of a running Java program [9,10]. As shown in Figure 1, inter- actionswith the applicationbyanAnalyst,Maliciousactor,or other“Client” of the web application can be observed or manipulated by the Agent.ComparingEffectiveness andEfficiencyofIASTandRASP 5 Client (e.g. Analyst’sComputer) Web Browser Web Server Agent observes& manipulates Application Fig. 1 AbstractionofIASTandRASP(JavaExample) 2.1.1 Interactive Application Security Testing (IAST) IAST vulnerability detection tools have access to the code, enabling them to perform static analysis. IAST tools also involve active real-time interaction with the application being tested for vulnerabilities, similar to dynamic anal- ysis. An agent of the tool is integrated with the server of the application so that the tool monitors all the requests, code, and data flow within the appli- cation [11]. The code of the applicationpertaining to those requests and data flow is scanned for vulnerabilities. Therefore, the code coverage provided by an IAST tool is in accordance with how thoroughly the application is being used. Since IAST tools scan code and also use dynamic analysis for detect- ing vulnerabilities,they aresaidto incorporateadvantagesofboth SAST and DAST tools. [4] 2.1.2 Runtime Application Security Protection (RASP) RASP tools try to detect and block attacks happening in a real-time pro- duction environment. RASP is integrated into the application at the time of deployment.TheRASPagenthasaccesstothesourcecodeaswellastheabil- ity to controlthe execution ofthe application[12]. When a malicious attempt is made to change the behaviour or state of the application, the RASP agent actively tries to detect and block the attack. Thus, RASP tools add another dimension of security to applications in the form of vulnerability exploitation prevention, unlike other tools discussed in this paper which are used in the testing phase for vulnerability detection. RASP should not be confused with Web Application Firewall (WAF).
RASP monitors input, output, and data flow to detect an attack and pro- ceeds to block the attack detected.On the the other hand, WAF monitors in- put requests only and does naive pattern matching for detection of malicious6 AishwaryaSethetal. activity. They do not have access to the source code of the application and requireextensiveconfigurationtestingto coveranapplicationsufficiently.[13] 2.2 Techniques from Prior Work - SMPT, EMPT, SAST, and DAST We compare our results against those of prior work [3], which has examined four vulnerability detection techniques. Systematic Manual Penetration Testing (SMPT) : A type of testing technique that ISO 29119-1 defines as “dynamic testing in which the [an- alyst]’s actions are prescribed by written instructions in a test case” [14]. Exploratory Manual Penetration Testing (EMPT) : A type of testing technique in which the analyst “spontaneously designs and executes tests based on the [analyst]’s existing relevant knowledge” [14], searching for vulnerabilities. Static Application Security Testing (SAST) :Atypeofautomatedtest- ing in which the source code of the application is analyzedto find security flaws in the application [15]. Dynamic Application Security Testing (DAST) :Atype ofautomated testinginwhichdynamicanalysisofthe applicationis usedto findvulner- abilities.DAST involvesnoaccessorknowledgeofthe application’ssource code [3]. 3 Related Work Our study focuses on comparing the effectiveness and efficiency of IAST vulnerability detection tools with SMPT, EMPT, SAST, and DAST; and de- termining the relative effectiveness of RASP. There is related work in the evaluation of vulnerability detection tools and techniques, which we discuss in this Section. However, few studies have examined IAST and RASP, and no studies have examined the full breadth of these techniques in a large-scale production system. 3.1 Comparing Static Application Security Testing (SAST) and Dynamic Application Security Testing (DAST) SAST and DAST tools have been benchmarked and compared (e.g., [16,17, 18,19])basedupontheireffectivenessinthe webservicesdomain.Thesestud- ies found that SAST is more effective than DAST in finding vulnerabilities. However, their bench-marking approach requires manual code review, which does not scale. Other studies, such as [20], focus on SAST tools for detect- ing vulnerabilities and find that the true positive and false positive rates vary widely across tools and across different types of vulnerabilities. Croft et al. [21] compares open-source, rule-based SAST tools with learning-basedComparingEffectiveness andEfficiencyofIASTandRASP 7 software vulnerability prediction models for C/C++ software systems. Croft et al.[21] concluded that although learning-based approaches had better pre- cision, both learning-based and SAST tools approaches should be used inde- pendently. Piskachev et al. [22] did a user study of SAST tools in resolving security vulnerabilities and provided a list of recommendations for software security professionals and practitioners. Scandariatoetal.[23]studiedusers’experiencesofnine participantsusing aSASTtoolandanautomatedtoolforpenetrationtestingontwobloggingap- plications.The participantsstatedthatthey foundSAST to be moreeffective for security teams. Fonseca et al. [24] performed an empirical evaluation of the effectiveness of differentDAST tools for finding SQL and XSS vulnerabilities in web appli- cations. They found that almost all the tools suffered from high false-positive rates and low coverage. Ina comparisonstudy ofelevenDAST tools by Doupe et al.[25] onaweb application, the researchers found that some vulnerabilities can be detected reliably, whereas others were more difficult for the tools to detect. However, their study was more focused onwhether the tools couldreach‘deep’ parts of code via crawling and detect logic vulnerabilities. Bau et al. [26] have compared four DAST tools based on vulnerabilities detected per thousand lines of code on 27 web applications. They conclude that more than one tool should be used and that the majority of the ’In- formation Leak’ alerts were false positive. Amankwah et al. [27] compared eight commercial and open-source web DAST tools on two web applications. They comparethe scannersbasedonprecision,recall,Youdenindex,OWASP web benchmark evaluation (WBE), and the web application security scanner evaluationcriteria(WASSEC).Theyfindthatalthoughbothopen-sourceand commercialDAST toolscanbe effective,nosingletoolwaseffective infinding all the vulnerabilities. Cruz et al. [28] compare Open-Source SAST, DAST, and Software Com- position Analysis (SCA) tools. The authors found combinations of tools were more effective than using one particular tool or approach. While the authors mention IAST, including the fact that one of their tools included IAST com- ponents, as with other comparisons - they focus their evaluation on SAST, DAST, and SCA without evaluating IAST. Rajapakse et al. [6] investigated issues during the integration of security tools intoa DevOps workflowby softwarepractitioners.Heijstek [7]alsomen- tioned that both IAST and RASP are emerging tools for secure DevOps and CI/CD environments. Tudela et al. [29] worked on combining SAST, DAST, and IAST security analysis techniques, applied against the OWASP Bench- mark project. Miao et al. [30] providedstratigies of integrating RASP protec- tion policies in a security information and event management framework.8 AishwaryaSethetal. 3.2 Interactive Application Security Testing (IAST) InteractiveApplicationSecurityTesting(IAST)isanautomatedvulnerability detectiontool.Setiawanetal. [31]implementedanIASTapproachandtested theirapproachonagovernmentwebsiteandfound249vulnerabilitiescovering allthecategoriesoftheOWASPTopTen(2017).However,theirapproachdoes
not accurately represent the approaches employed by commercially available IAST tools for vulnerability detection. Their approachuses a SAST tool that scanstheentirecodeoftheapplicationwhileaDASTtoolsimultaneouslydoes dynamic analysis of the application. In contrast, modern IAST tools do not scan the entire source code of an application. They only scan the parts of the application’s source code that interact with users through test cases. In this study, we study two commercial IAST tools and compare their performance with other vulnerability detection techniques and tools. Tudela et al. [11] compared the effectiveness of SAST, DAST, and IAST tools by running them againstthe OWASP Benchmark project. The OWASP Benchmark project [32] is a collection of thousands of test cases developed primarily in Java. They chose two tools of each SAST, DAST, and IAST and evaluated the effectiveness of each tool separately, in pairs, and finally in groups of three. They found that the IAST-IAST pair yields better results and that combining IAST with either DAST or SAST improves vulnerability detection effectiveness. The study was primarily focused on how tools may be pairedtoincreaseeffectiveness.However,inthiswork,westudiedalarge-scale application (OpenMRS), which employs a wide range of technologies and has millions of lines of code, and individually compared the effectiveness of the techniques and tools. 3.3 Runtime Application Self Protection (RASP) Runtime Application Self Protection (RASP) is emerging tool for preventing the exploitation of vulnerabilities. Most of the studies on RASP have been relatedtoruntimeprotectionmechanismsinspecifictypesofapplications,with RASP tools implemented by researchers themselves. In contrast, our current analysis focuses on RASP tools used in industry. Pupo et al. [33] developed a two-phase abstract interpretation approach, extracting SAST components fromtwo RASPs.They evaluate their approach by comparing their two-phase approach with a single-phase RASP approach andfindthatthetwo-phaseapproachisbetterthanthesingle-phaseapproach intermsofprecision.Similarly,Huangetal.[34]developedaframeworkcalled WebSSARI for PHP web applications that incorporates static analysis for finding potentially insecure code and runtime protection by inserting runtime guards in potentially insecure code. They test their framework on 11,848files from 230 open-source projects to find and prevent exploitation of vulnerabili- ties.ComparingEffectiveness andEfficiencyofIASTandRASP 9 Yinetal.[35]developedaRASPtoolspecifictoScriptInjectionattacksfor dynamicwebapplicationsbasedondataflowanalysisandautomaticinsertion of filters before relevant sink statements. They compare their solution with WAF, BEEP,andCSPandfindthattheir approachandCSPperformbetter. However, CSP was expensive. Yuan et al. and Bailey et al. [36,37] described a self-adaptive framework forRASPwhichprovidesdefense-in-depthdetectionandtakesactiontoblock the attack from requirements-drivenor architecture-basedapproaches. 4 Baseline comparison: Elder et al. [3] We directly compare our results with the techniques from the previous study byElderetal.[3].ThefourtechniquesandtoolsexaminedbyElderetal.[3]are SMPT,EMPT,SAST,andDAST.Section4.1providesinformationfromtheir methodology, which guided our own methodology as described in Section 5. Section 4.2 briefly summarizes Elder et al.’s results. 4.1 Baseline Research Methodology Elder et al. [3] replicated prior work by Austin et al. [1,2] comparing the SMPT,EMPT,SAST,andDASTvulnerabilitydetectiontechniquesandtools. Elder et al. [3] applied each technique to the Open Medical Records System (OpenMRS) web application, an open-source, Java-based electronic medical records management system of about 4 million lines of code. They compare thetechniquesandtoolsbasedontheireffectivenessandefficiency.Theymea- sure the effectiveness of a vulnerability detection technique/tool based on the numberandtypeofvulnerabilitiesdetectedbythattechnique/tool.Efficiency is measured in terms of the number of vulnerabilities detected per hour. We provide high-level information on their research approach that is specific to the four vulnerability detection techniques. The vulnerability de-duplication, true/falsepositiveclassification,andvulnerabilitycountingprocessesusedare the same as those outlined in Section 5.3. SMPT: 131black box securitytest casesweredevelopedandexecuted. These test cases were based upon the OWASP Application Security Standard 1 (ASVS) . Two independent analysts executed each test case. EMPT: Sixty-three (63) students in a graduate-level software security class each spent three hours performing exploratory penetration testing as part of their final project submission at the end of the semester. SAST: One open source (Sonarqube version 8.2) and one proprietary SAST tool were run on OpenMRS using the default security rules. Two analysts independently reviewed the alerts that the tools produced as output. 1 https://owasp.org/www-project-application-security-verification-standard/10 AishwaryaSethetal. DAST: Oneopensource(OWASPZAP)andoneproprietaryDASTtoolwere run. DAST requires sample inputs to the application. In Elder et al., the sample inputs to the DAST application were based on six test cases from theSMPTtestsuite.Thetestcaseswereselectedtomaximizethecoverage of testing of OpenMRS. Two analysts independently reviewed the alerts that the tools produced as output. Theresultsofrunningthesefourvulnerabilitydetectiontoolswererecorded in a dataset containing the following details for each vulnerability recorded: 1. Request URL and parameters. 2. SourceCodeLocation:Consistedofmodulename,filename,andlinenum- ber. 3. CWE number. 4. OWASP Top Ten (2021) category. 5. The vulnerability detection technique or tool which detected it.
6. Description:Additionaldescriptiveinformationrequiredtodistinguishthe vulnerability from other vulnerabilities For measuring efficiency, Elder et al. used data collected from a graduate- levelsoftware engineeringcourse to reduce potential biases introducedby col- lecting efficiency data from a single source. For tool-based techniques, DAST and SAST, students were instructed to record the time required to review a subset of the tool results. For SMPT, students wrote and executed a series of test cases over several assignments, recording the amount of time required and the number of vulnerabilities found. For EMPT, students performed ex- ploratory testing for 3 hours each, recording the number of vulnerabilities found. In the current study, we compare our results against the average VpH recorded for each technique. Details on the assignments, how data was col- lected, and additional analysis of the results can be found in the original study [3]. 4.2 Results Elder et al. [3] found the most vulnerabilities using SAST tools but found moreseverevulnerabilitiesusingEMPT.Theydiscoveredvulnerabilitiesusing each technique that were not found by the others. In terms of efficiency, they foundthattheefficiencyofmanualtechniques,thatis,EMPTandSMPT,was comparable to or better than the efficiency of automated techniques, that is, DASTandSAST,intermsofVulnerabilitiesperHour(VpH).Resultsforeach of the four vulnerability detection techniques will be presented in Section 6, where we compare our IAST and RASP results with those of Elder et al. [3]. 5 Methodology Our research questions require measurement of the efficiency and effective- ness of IAST and RASP tools comparable to prior work with SAST, DAST,ComparingEffectiveness andEfficiencyofIASTandRASP 11 SMPT, and EMPT. Specifically, our first research question, on the effective- nessofIASTtools,states:RQ1: What is the effectiveness of InteractiveAppli- cation Security Testing (IAST), as compared to other vulnerability detection techniques, in terms of the number and types of vulnerabilities detected? We define effectiveness to include (1) the number of true positive vulnerabilities detected; and (2) the spectrum of Common Weakness Enumeration (CWE) types and OWASP Top Ten types for the vulnerabilities detected. Our second research question on the efficiency of IAST tools states that: RQ2: How does the efficiency in terms of vulnerabilities per hour differ be- tween IAST and other vulnerability detection techniques? Consequently, we determine the number of ‘True Positive’and ‘Unique’ vulnerabilities detected per hour to measure the efficiency of IAST tools. Ourthirdresearchquestionfocuses onthe effectiveness ofthe RASP tech- nique and states that: RQ3: What is the effectiveness of RASP in terms of the number and types of vulnerabilities prevented relative tovulnerabilities dis- covered by vulnerability detection techniques? Similar to our RQ1, we define the effectiveness of RASP tools to include (1) the number of true positive vulnerabilities prevented, which were detected by the vulnerability detection techniquesandtools;and(2)thespectrumofCommonWeaknessEnumeration (CWE) types and OWASP Top Ten types. 5.1 Data Collection SincetheworkingofIASTandRASPtoolsissuchthattheyrequireinteraction withtheapplication,weusethesame131SMPTblack-boxtestcasesasthose developedandusedbyElderetal.[3]tosystematizethe interactionswithour application. The SMPT test cases were based on ASVS Level Control 1 since it is the only level that is “completely penetration testable by humans” [3]. The students and researchers participating in their study compiled a set of 131 test cases covering 63 controls of ASVS. We use two IAST tools, namely,IAST-1 andIAST-2, andone RASP tool. We perform the interactions on the three tools running on the OpenMRS application,hostedonavirtualimage.WeuseOpenMRSversion2.9toenable comparisonwithElderetal.[3].Wedoadetailedcomparisonofeachindividual vulnerability detected by IAST and RASP to those found in their study for every technique and tool. For the classification of alerts, we refer to the same version of the source code of the application as Elder et al. [3]. 5.2 Vulnerability Counting Guidelines For both IAST and RASP, multiple alerts may point to the same vulnera- bility. We use the definition of vulnerability specified by NVD and Common Vulnerability Enumeration (CVE), which is the source of the vulnerability database of NVD [38]. Therefore, we use the CVE Counting Rules [39], the12 AishwaryaSethetal. same guidelines as CVE Numbering Authorities (CNA), to classify and count the‘true/falsepositive’and‘unique’alerts.Keyguidanceindeterminingwhich alerts represented unique vulnerabilities is as follows: – Each unique vulnerability must be independently fixable – Iftherearemultiplealertsofthesamevulnerabilitytype,butnoneofthem share vulnerable code (i.e., they must be fixed independently), then all of them are considered ‘unique’. – Incaseofambiguityregardingtheindependentfixabilityoftwoalerts,only one is considered to be ‘unique’ and the other is considered a ‘duplicate’. Werefertotheprotectionmechanismsormitigationsuggestedbythetools themselvesaswellasthosespecifiedintheOWASPTopTencheatsheet[40]to helpunderstandhowavulnerabilitywouldbefixedandwhethervulnerabilities are independently fixable. 5.3 Procedure for Generating and Curating set of Vulnerabilities for IAST Figure 2 provides a high-level overview of our methodology described in this section, as well as the methodology for RASP described in Section 5.4. IAST-1 IAST-1Alerts IAST UniqueAlerts TPalerts
Aggregate IAST-2 IAST-2Alerts OpenMRS ClassifyAlerts ‘TP/FP’and ‘Unique/Duplicate’ RASPAttack Vulnerabilities RASP Alerts prevented byRASP MapAttacksto Aggregate ExecuteTestcases Vulnerabilities Fig. 2 Ahigh-leveloverview ofourapproach. As part of answering RQ1 and RQ2, two researchers independently exe- cuted the following set of steps for both IAST tools: 1. Run the 131 black box SMPT test cases used in the previous study by Elder et al. [3] 2. Record how much time is spent on Steps 3-4 3. De-duplication. As detailed in Section 5.2, the tools provide the CWE for each alert. Then, We leverage the information provided by the tool, such as protection mechanisms or other suggested mitigations, as well as information specified in the OWASP Top Ten cheat sheet [40] for findingComparingEffectiveness andEfficiencyofIASTandRASP 13 a possible fix for a vulnerability. For each alert, we determine if the alert eithermapstoadifferentCWEoriftheCWEisthesame,thendetermine if a fix for the alert is different from a fix of an already-examined alert. If eitherofthetwoconditionsismet,wemarkthealertas‘unique’;otherwise, we mark it as a ‘duplicate’. 4. True positive identification. As detailed in Section 5.3.1, we go through each alert to determine if we could exploit the tool alert based on our experience and simulate it in the OpenMRS application OR if the tool alertdid nothave anyprotectionmechanisminplace in the applicationto prevent exploitation. If either of the two conditions is met, we mark the alert as a ‘true positive’ or otherwise as a ‘false positive’. 5. We leveraged the findings from the Elder et al. study for the “true posi- tive”AND “unique”alerts(fromSteps 3and4)andthoroughlycompared vulnerabilitytovulnerabilityfromourresultsettotheirresultsettoiden- tify which vulnerabilities were found using a different technique in their research. For each vulnerability in our set, we examine whether there is a vulnerability in the result set from Elder et al. [3] with the same URL, parameter, and CWE type. If the fields match, we mark our vulnerability as the same vulnerability as the one found by Elder et al. and record the technique or tool that detected that vulnerability from the Elder et al. [3] study. Upon completion of these steps for eachtool, eachindependent researcher aggregated the set of ‘true positive’ and ‘unique’ alerts generated from the IAST-1 and IAST-2 tools and removed the common alerts to have a final set of ‘true positive’ and ‘unique’ alerts representing the vulnerabilities detected by IAST technique. Sincetheclassificationofalertsas‘true/falsepositive’or‘unique/duplicate’ issubjecttodomainknowledge,experience,andhumanerror,tworesearchers independently execute the above procedure for classifying the alerts and re- viewing each other’s results. A third reviewer resolves any conflicts regarding the classification. 5.3.1 True/False Positive Classification Weclassifyanalertgeneratedbythetoolsas‘truepositive’whenweperceiveit tobeanactualvulnerability.TheNationalVulnerabilityDatabase(NVD) [38] defines a vulnerability as:“A weaknessin the computationallogic(e.g., code) foundinsoftwareandhardwarecomponentsthat,whenexploited,resultsina negativeimpacttoconfidentiality,integrity,oravailability”.Thus,weconsider analerttobe‘truepositive’iftheweaknessnotedbythealertcanbeexploited such that it can lead to a security breach of the application. However, we take an additional aspect of ‘Defense in Depth’ into consideration to classify the alerts, which highlights the importance of placing different safeguards at multiple layers for better protection. Thus, we also consider if the weakness notedbythealerthasanyprotectionmechanisminplaceinthesourcecodeof14 AishwaryaSethetal. theapplication.Ifnocountermeasureshavebeentakentopreventexploitation of the weakness highlighted by the alert, then we mark the alert as ‘true positive’ even if we are unable to determine whether the weakness can be exploited to breachthe security of the application. For example, if a test case generates an XSS alert and we see no input validation is performed in the sourcecodeorifweareabletoinputaJavaScriptstringthatsuccessfullygets injected into and displayed on a page of the application, then we mark the alert as ‘true positive’. 5.3.2 Vulnerability Type We assign the vulnerability types to each ‘true positive’ alert based on two categories - CWE and OWASP Top Ten. “CWE is a community-developed list of software and hardware weakness types.” [41]. The OWASP Top Ten is a regularly updated list of “the most critical security risks to web applica- tions.” [42]. We use the OWASP Top Ten 2021 to summarize the CWE types of vulnerabilities found. Each of these Top 10 is comprised of a set of CWE types. The latest (2021) Top Ten, which were used in our analysis, are A01 - Broken Access Control, A02 - Cryptographic Failures, A03 - Injection, A04 - Insecure Design, A05 - Security Misconfiguration, A06 - Vulnerable and Out- dated Components, A07 - Identification and Authentication Failures, A08 - Software and Data Integrity Failures, A09 - Security Logging and Monitoring Failures, and A10 - Server-Side Request Forgery (SSRF). ThetoolsassignaCWEtypetoeachalert.Incaseswheretwotoolsassign different CWE types to the same vulnerability, the CWE type is analyzed, andamanualrevisionoftheCWEtypemaybedone.Forexample,atestcase generated a clickjacking alert with CWE type listed as CWE-451 in IAST-1, while the same alert was generated with CWE type listed as CWE-693 in IAST-2. We resolve this conflict by manually updating the value of the CWE
type in the final set of vulnerabilities, depending on the test case. OWASPTopTen (2021)Categorieswerealreadyassignedto eachalertby the tools.IfanalerthadnoOWASPTopTen(2021)categoryassignedbythe tool,wemanuallyassignedthevaluesbymappingfromtheCWEtypes.Since OWASP TopTen focuses onthe top ten categoriesof vulnerabilitytypes that are most frequently found in software, it helps in presenting a more relevant and understandable way to interpret the vulnerabilities found. 5.3.3 Vulnerability Severity We determine the importance and severity of vulnerabilities found in two dif- ferent ways. First, the tools classify the alerts based on their severity. Since each tool has its own classification rule and severity categories, we organize the vulnerabilitiesinto twogroups,‘moresevere’and‘lesssevere’tomakeour severity categories more consistent. We use the value of severity initially as- signedtothesetofvulnerabilitiesfoundbyatool.Thevulnerabilitiesthatare classified as ‘Low’ or below by the tool are grouped as ‘less severe’, whereasComparingEffectiveness andEfficiencyofIASTandRASP 15 those vulnerabilities that are classified by the tool in categories above ‘Low’ are grouped as ‘more severe’ vulnerabilities. Second, since OWASP Top Ten ranks vulnerabilities basedon their criticality as well as frequency, we use the OWASP Top Ten categories to understand the importance of the vulnerabili- ties found by each tool. 5.3.4 Efficiency As noted in Step 2 above, we record the amount of time spent by each re- searcher to analyze the alerts produced by each tool and determine the num- ber of true positive vulnerabilities found, removing false positives. For each researcher,we divide the number of true positive vulnerabilities found by the length of time recorded to determine the Vulnerabilities per Hour (VpH) of IAST. We report the average VpH in our results. 5.4 Procedure for Curating RASP tool Alerts Since RASP is a real-time attack prevention tool, we employ a slightly dif- ferent methodology than the one adopted for IAST (in our study) and other vulnerability detection techniques and tools (by Elder et al. [3]). We want to find out the number of vulnerabilities previously detected by the vulnerabil- ity detection techniques and tools, but RASP has prevented them from being exploited. We run the same set of 131 black box SMPT test cases as used by Elder et al. [3] and in our IAST study. The alerts generated by the RASP toolarefortheattacksdetectedandblockedbytheRASPagent.Wemeasure the effectiveness of the RASP tool by the following two parameters: (1) the numberofuniquevulnerabilitiespreventedfrombeingexploitedbytheRASP tool and (2) the type of that vulnerability. We usethe type ofattacksblockedby the RASP toolasaninitialvalueto determine the type of vulnerability that was prevented from being exploited. We further map the types of vulnerabilities based on CWE to OWASP Top Ten (2021) categories. The mapping of CWE to OWASP Top Ten helps in determining the number of the most critical vulnerabilities that are being prevented from being exploited by the RASP tool. TocountthenumberofvulnerabilitiespreventedbytheRASPtoolrelative to the vulnerabilities detected by the vulnerability detection techniques and tools, we map each of the attack alerts generated by the RASP tool to the vulnerabilities detected by each of the vulnerability detection techniques and tools. An overview of the approach for RASP is depicted in Figure 2. 6 Results In this section, we outline the results we obtained via the experiments per- formedusingtheIASTandRASPtools.Table1providesahigh-levelsummary16 AishwaryaSethetal. of our results for RQ1 - What is the effectiveness of Interactive Application Security Testing (IAST), as compared to other vulnerability detection tech- niques, in terms of the number and types of vulnerabilities detected?, RQ2 - HowdoestheefficiencyintermsofvulnerabilitiesperhourdifferbetweenIAST and other vulnerability detection techniques? and RQ3- What is the effective- ness of RASP in terms of the number and types of vulnerabilities prevented relative to vulnerabilities discovered by vulnerability detection techniques?.De- tailed results for RQ1, RQ2 and RQ3 are provided in Sections 6.1, 6.1, and 6.1 respectively. We will discuss the implications for our results in the next section (Section 7) Current Study PreviousStudy IAST RASP SMPT EMPT SAST DAST Effectiveness: 91 44 37 185 23 823 # Vulnerabilities Effectiveness: 8 1 9 7 7 7 # OWASP Top 10 Covered Efficiency: 2.14 N/A 0.69 2.22 0.55 1.17 Average VpH Table 1 Effectiveness and Efficiency of IAST and RASP compared to other techniques (Section 6) 6.1 RQ1: Effectiveness of IAST In this section, we outline the results for our first research question, which is based on the effectiveness of IAST tools: RQ1: What is the effectiveness of Interactive Application Security Testing (IAST), as compared to other vulner- ability detection techniques, in terms of thenumber andtypes of vulnerabilities detected?.We providethe numberof‘False Positive’and‘TruePositive’alerts and the number of vulnerabilities found by each IAST tool. We also present the vulnerabilities with their respective severity and type based on OWASP TopTencategories.Additionally,wehavecomparedallourIAST resultswith those of SAST, DAST, and manual penetration testing from Elder et al. [3]. 6.1.1 Number of Alerts and Vulnerabilities The number of vulnerabilities for each tool was determined by the number of ‘True Positive’ AND ‘Unique’ alerts generated by that tool using the process described in Section 5.3. We present these results in Table 2. The final row
of Table 2 is the number of vulnerabilities detected by that technique or tool exclusivelyandnotdetectedbyothertechniquesandtools.Thetablecompares our IAST results with SMPT, EMPT, DAST, and SAST results from the previous work by Elder et al. [3]. In the previous work, True Positive alertsComparingEffectiveness andEfficiencyofIASTandRASP 17 Current Study PreviousStudy IAST IAST IAST SMPT EMPT DAST SAST Total 1 2 Total Total Total Total True Positive(TP) 322 159 182 60 N/A 787 948 Alerts Unique 91 23 68 37 185 23 823 Vuln. Vuln. NOT found 52 13 41 10 153 5 812 by others Table 2 VulnerabilityCounts (Section 6.1.1) were referred to as True Positive failures, which applied to both alerts from DAST and SAST as well as failing test cases from SMPT. Elder et al. did not have a true positive count for EMPT comparable to the failing test cases from SMPT or true positive alerts from DAST and SAST. The number of true positive alerts and subsequentratio for EMPT is markedNot Applicable (N/A). The results in Table 2 show that IAST finds more unique vulnerabilities than SMPT and DAST, but less than EMPT and SAST. We see a similar trend in the number of vulnerabilities only found by a particulartechnique or tool. IAST seems to find more vulnerabilities that were not found by other toolscomparedtoSMPTandDAST,butlessthanEMPTandSAST.Wealso observe a difference in the number of vulnerabilities found and vulnerabilities unique to each tool for IAST-1 and IAST-2. 6.1.2 Vulnerability Detection Tool Precision Precision is calculated as the ratio of the number of ‘True Positive’ alerts to the total number of alerts generated by the tool. As specified in Section 5.3, tworesearchersclassifiedeachalertproducedbythetoolsas‘TruePositive’or ‘False Positive’. Any disagreements regarding classification were resolved by a third reviewer. The resultant set consisted of ‘Total Alerts’, ‘True Positive Alerts’, and ‘False Positive Alerts’ generated by each tool. These results are shown in Table 3. The precision of IAST-1 is 0.5, and IAST-2 is 0.34. The IAST results are compared with the automated vulnerability detection tools in Elderet al. [3].The combinedprecisionof IAST tools of0.4 is higher than that of DAST tools (0.23) but lower than that of SAST tools (0.98). 6.1.3 Vulnerability Severity AsexplainedinSection 5.3.3,theseverityofthevulnerabilitiesdetectedbythe IASTtoolswasgroupedinto‘moresevere’and‘lesssevere’categoriesbasedon the initial severityvalues assignedto them bythe tools.InFigure 3, weshow the number of ‘more severe’and‘less severe’vulnerabilities detected by IAST toolsgroupedintotheOWASPTopTen(2021)categoriesastheOWASPTop18 AishwaryaSethetal. Current Study PreviousStudy IAST IAST IAST DAST SAST Total 1 2 Total Total Total Alerts 857 321 536 3412 962 True Positives 322 159 182 787 948 False Positives 516 162 354 2625 20 Precision 0.4 0.5 0.34 0.23 0.98 Table3 TotalAlerts,FalsePositives(FP),andPrecisionfortheCurrentStudyCompared withElderetal.(Section 6.1.2) Tenordersthevulnerabilitiestypesbasedonhowcriticaltheyare.Wecansee fromthefigurethatoverall,thenumberof‘lesssevere’vulnerabilitiesdetected by IAST is greater than the number of ’more severe’ vulnerabilities detected. We comparethe severityofvulnerabilitiesfoundby IAST toolswith those byElderetal.[3]inTable 5.ThevulnerabilitiesaredistributedoverOWASP TopTen(2021)categoriessoastopresentthe vulnerabilitiesinthe mostcrit- ical ranked fashion. In the case where a vulnerability was assigned more than oneOWASPTopTencategorybyanIASTtool,thevulnerabilitywascounted towardsall the OWASP Top Ten categoriesassignedto it. The comparisonof the severity of vulnerabilities, amongst IAST-1 and IAST-2 and overall, has been shownin Table 4. IAST-2 reports a higher number of both ‘more severe’ and ‘less severe’ vulnerabilities than IAST-1. 01:BrokenAccessControl 14 0 02:CryptographicFailures 4 14 03:Injection 11 8 04:InsecureDesign 9 17 05:SecurityMisconfiguration 2 29 06:Vulnerable&OutdatedComponents 00 07:Identification&AuthenticationFailures 11 1 08:Software&DataIntegrityFailures 5 1 09:SecurityLogging&MonitoringFailures 3 9 10:ServerSideRequestForgery 00 0 5 10 15 20 25 30 NumberofVulnerabilities yrogetaCneTpoTPSAWO MoreSevere LessSevere Fig. 3 SeverityofIASTVulnerabilitiesgroupedinto2021OWASPTopTenCategories 6.1.4 Vulnerability Type (OWASP Top Ten and CWE) A vulnerability type comparison Elder et al. [3] is shown in Table 6. The firstcolumnofTable 6indicates the OWASPTopTen(2021)categories.TheComparingEffectiveness andEfficiencyofIASTandRASP 19 Severity Overall IAST-1 IAST-2 MoreSevere 36 13 24 LessSevere 55 7 51 Table 4 IASTVulnerabilitySeverity(Section 6.1.3) Curr. PreviousStudy Study IAST SMPT EMPT DAST SAST 01: Broken Access Control 14ab 2† 15 0 28 02: CryptographicFailures 4 1 1 1 2 03: Injection 11cde 5 119 11 24 04: Insecure Design 9ac 5† 8 1 8 05: Security 2d 2 2 2 14 Misconfiguration 06: Vulnerable & Outdated 0 0 0 0 0 Components 07: Identification & 11b 13 10 1 2 Authentication Failures 08: Software& Data 5e 1‡ 0 0 10 Integrity Failures 09: Security Logging & 3a 3 9 0 0 Monitoring Failures 10: Server-side Request 0 1‡ 0 0 0 Forgery No Mapping to OWASP 0 1 1 0 54 Top Ten More Severe Total 36 32 165 17 142 aThree(3) “More Severe” vulnerabilitiesfoundusingIASTwereassociated withallthree of:A01, A04,andA09
bEleven(11)“MoreSevere”vulnerabilitiesfoundusingIASTwereassociatedwithbothA01andA07 cTwo(2)“MoreSevere”vulnerabilitiesfoundusingIASTwereassociatedwithbothA03andA04 dTwo(2)“MoreSevere”vulnerabilitiesfoundusingIASTwereassociatedwithbothA03andA05 eTwo(2)“MoreSevere”vulnerabilitiesfoundusingIASTwereassociatedwithbothA03andA08 FromthePriorWork[3]: † OnevulnerabilityfoundusingSMPTmappedtobothA01andA04throughtwodifferentCWEs. ‡ OnevulnerabilityfoundusingSMPTmappedtobothA08andA10throughtwodifferentCWEs. Table 5 Number of ‘More Severe’ Vulnerabilities Detected by Each Technique based on 2021OWASPTopTen(Section 6.1.3) totalvulnerabilitycountcalculatedforeachtechniqueortoolisprovidedinthe final‘Total’row.Thecolumnsindicatethevulnerabilitycountsforeachofthe vulnerabilitydetectiontechniquesandtools,distributedovertheOWASPTop Ten categories.From the table, we can observe that IAST is most effective in finding A05:SecurityMisconfigurationvulnerabilities,andthe same is evident from Figure 3. We also note that RASP is able to prevent only A03:Injection vulnerabilities.20 AishwaryaSethetal. As shown in Table 6, none of the vulnerability detection techniques or tools found vulnerabilities in the OWASP Top Ten Category for Vulnerable and Outdated Components (A06), suggesting that different techniques and categoriesoftechniquesareusefulforfindingdifferenttypes ofvulnerabilities. Finding vulnerabilities in components or third-party code of the application requires tools such as Software Composition Analysis (SCA) tools. We have not included these tools in our study and instead focus on the vulnerabilities that arise from the source code of the application itself. Curr. Study PreviousStudy IAST RASP SMPT EMPT DAST SAST 01: Broken Access Control 14ab 0 2† 15 1 261 02: CryptographicFailures 18f 0 1 1 2 4 03: Injection 19cdeg 44 5† 119 11 58 04: Insecure Design 26ach 0 8 26 2 36 05: Security 31dfh 0 5 4 6 15 Misconfiguration 06: Vulnerable & Outdated 0 0 0 0 0 0 Components 07: Identification & 12b 0 13 10 1 2 Authentication Failures 08: Software & Data 6e 0 1‡ 0 1 11 Integrity Failures 09: Security Logging & 12ag 0 3 9 0 0 Monitoring Failures 10: Server-side Request 0 0 1‡ 0 0 0 Forgery No Mapping to OWASP 0 0 1 2 0 436 Top Ten Total 91 44 37 187 44 823 aThree(3)vulnerabilitiesfoundusingIASTwereassociatedwithallthreeof:A01,A04,andA09 bEleven(11)vulnerabilitiesfoundusingIASTwereassociatedwithbothA01andA07 cTwo(2)vulnerabilitiesfoundusingIASTwereassociatedwithbothA03andA04 dTwo(2)vulnerabilitiesfoundusingIASTwereassociatedwithbothA03andA05 eTwo(2)vulnerabilitiesfoundusingIASTwereassociatedwithbothA03andA08 fThirteen(13)vulnerabilitiesfoundusingIASTwereassociatedwithbothA02andA05 gEight(8)vulnerabilitiesfoundusingIASTwereassociatedwithbothA03andA09 hThree(3)vulnerabilitiesfoundusingIASTwereassociatedwithbothA04andA05 FromthePriorWork[3]: †OnevulnerabilityfoundusingSMPTmappedtobothA01andA04throughtwodifferentCWEs. ‡OnevulnerabilityfoundusingSMPTmappedtobothA08andA10throughtwodifferentCWEs. Table 6 Vulnerability Type Comparison with Elder et al. [3], including More Severe and LessSevereVulnerabilities(Section 6.1.4)ComparingEffectiveness andEfficiencyofIASTandRASP 21 RQ1 - What is the effectiveness of Interactive Application Security Testing (IAST), as compared to other vulnerability detection tech- niques, in terms of the number and types of vulnerabilities detected? Answer: IAST finds more unique vulnerabilities than SMPT and DAST, but less than EMPT and SAST. However, IAST found new vulnerabilities that were not found by the techniques. 6.2 RQ2 : Efficiency of IAST We define the efficiency of techniques and tools in terms of vulnerabilities detected per hour (VpH) and calculate it as the ratio of the number of vul- nerabilities detected by a tool to the total time taken to classify all the alerts of that tool as ‘true positive’/‘false positive’ and ‘unique’/‘duplicate’. We use theaverageasthestatisticalmeasureforobtainingacentralvalueofefficiency for each tool. We present the calculated efficiency of IAST tools in Table 7 and compare the results with those of Elder et al. [3]. As per the table, the efficiency of IAST tools of 2.14 VpH is found to be second only to EMPT (2.22VpH), andeventhatdifferenceisquite minor.However,the efficiencyof the two IAST tools differ significantly, suggesting that the efficiency is highly dependent on the tool. Current Study PreviousStudy IAST IAST IAST SMPT EMPT DAST SAST Overall 1 2 Avg. VpH 2.14 1.34 2.98 0.69 2.22 0.55 1.17 Table7 EfficiencyacrosstechniquesandtoolsusingVulnerabilitiesperHour(VpH)(Sec- tion 6.2) RQ2-Howdoestheefficiencyintermsofvulnerabilitiesperhourdiffer between IAST and other vulnerability detection techniques? Answer:TheefficiencyofIASTtoolsof2.14VpHisfoundtobesecond only to EMPT (2.22 VpH), and even that difference is quite minor. However, the efficiency of the two IAST tools also differs, suggesting that the efficiency is highly dependent on the tool. 6.3 RQ3 : Effectiveness of RASP As detailed in Section 5.4, we determine the effectiveness of the RASP tool based on two factors: (1) the number of vulnerabilities prevented from being22 AishwaryaSethetal.
exploitedwhichhasbeendetectedbyIAST,SMPT,EMPT,DAST,andSAST; (2) the type of vulnerabilities preventedfrom being exploited by the tool. We present the types of vulnerabilities prevented by the RASP tool in Table 6. RASP prevented, on average, 44 vulnerabilities from being exploited. RASP detects and prevents A03:Injection attacks quite effectively. However, RASP was not able to detect or prevent any attacks caused by the exploitation of any other type of vulnerability. RQ3 - What is the effectiveness of RASP in terms of the number and types of vulnerabilities prevented relative to vulnerabilities discovered by vulnerability detection techniques? Answer: RASP prevented, on average, 44 vulnerabilities from being exploited for each execution of the test suite. 7 Discussion In this section, we discuss our findings and include suggestions on how prac- titioners might use them to choose among different software vulnerability de- tection and prevention techniques and tools to make a more informed choice. Table 8 gives an overviewof the factors discussed in the following sections for selecting software vulnerability detection techniques and tools. Features Performance(Results) OWASP Technique/ Exploit- Efficiency Unique Vuln.Location TopTen Precision Tool ability (VpH) Vuln. Types IAST Yes Provided 2.14 52 8 0.4 SAST Unknown Provided 1.17 812 7 0.98 DAST Yes NotProvided 0.55 5 7 0.23 SMPT Yes NotProvided 0.69 10 9 N/A EMPT Yes NotProvided 2.22 153 7 N/A Table 8 SummaryofVulnerabilityDetection Tools(Section 7) 7.1 Individual Vulnerability Types (Effectiveness) Practitioners having prior knowledge of the prevalence of types of vulnera- bilities or wishing to prioritize a particular type of vulnerability in their ap- plication may be more motivated to use techniques and tools that are more effectiveindetectingandpreventingthatspecifictypeofvulnerability.Table5ComparingEffectiveness andEfficiencyofIASTandRASP 23 and Table 6 illustrate how some techniques are more effective in addressing specific types of vulnerabilities. For example, EMPT is most effective in its abilitytoidentify Injectionvulnerabilities.We canalsoseeinTable6thatthe RASPtoolisthemosteffectiveinpreventingtheexploitationofInjectionvul- nerabilities present in a running system. Therefore, practitioners focusing on Injection vulnerabilities could use EMPT in the testing phase to detect Injec- tion vulnerabilities in the application and use the RASP tool when deploying their application to block Injection attacks in deployment. 7.2 Coverage(Effectiveness) Forawidevarietyofvulnerabilitytypes,practitionersmaywanttoemphasize maximum detection coverage. In each of the eight OWASP Top Ten 2021 categories, IAST tools found at least six vulnerabilities, as shown in Table 6. Compared to other automated detection techniques, SAST detected five types, and DAST detected two types of at least six vulnerabilities. When compared with manual techniques SMPT is found to be better than IAST, whichprovidedthemostcoverageoftheOWASPTopTenCategoriesamongst all the techniques and tools, as shown in Table 6. Despite the fact that the identical131testcaseswereconductedforbothSMPTfromElderetal. [3]and IASTinthecurrentstudy,eachIASTtoolfoundahighernumberof“unique” vulnerabilitiesthanSMPTasshowninTable2.Thesefindingsimplythatour study benefited from the use of IAST when conducting black-box test cases. Although the RASP tool does not block any other types of vulnerability exploitation apart from A03:Injection using our set of test cases, preventing injection exploits is beneficial. Moreover, the types of attacks prevented by theRASPtoolmightdifferbasedontheapplicationandthemethodofattack being used to exploit vulnerabilities in the application. Therefore,IASTcaneffectivelydetectthenumberofcritical(OWASPTop Ten)vulnerabilitytypessecondbesttoonlySMPTbutstilldetectmoreunique vulnerabilities than SMPT. Thus, practitioners prioritizing maximum cover- age might want a vulnerability detection technique or tool similar to IAST. Furthermore, practitioners might prefer to employ a RASP tool to deploy additional protection measures in a ”Defense in Depth” security strategy. 7.3 Severity (Effectiveness) Our results from Tables 5, 4 and Figure 3 indicate that, unlike the previ- ous section, IAST might not be a good choice when practitioners are aiming for detecting more severe vulnerabilities as the total number of ’more severe’ vulnerabilities detected by IAST is only better than DAST. Although EMPT detectsthemost‘moresevere’vulnerabilities,thesevulnerabilitiesareprimar- ily Injection vulnerabilities. SAST tool might prove to be a better choice to detect a higher number of ‘more severe’ vulnerabilities across OWASP Top24 AishwaryaSethetal. Ten types. Therefore, practitioners prioritizing finding the most number of ‘more severe’ vulnerabilities might want to employ EMPT or SAST. 7.4 Automation (Efficiency) From the results in Table 7, we can see that the efficiency of IAST is sec- ond to only EMPT and is better than the other automated tools, SAST and DAST. Studies such as [43] indicate that practitioners might prefer using au- tomated tools for integrating testing into the continuous deployment pipeline for automation and an assumption that manual techniques are less efficient than automated techniques. However, our results indicate that the efficiency of manual techniques is comparable to that of automated ones. Thus, practitioners prioritizing efficient resource utilization might want to considerallthe techniques,thatis,manualaswellasautomated,toselectthe
most efficient technique or tool based on resource availability. 8 Threats to Validity and Limitations We discuss the Threats to Validity and Limitations of our work. We organize thisdiscussionbasedonfourcategoriesofpotentialthreatstoValidity:Conclu- sion Validity, External Validity, Internal Validity, and Construct Validity [44, 45,46]. 8.1 Conclusion Validity Conclusion Validity is about whether conclusions are based on statistical ev- idence [44,46]. While we have empirical results, a single case study is insuf- ficient to draw statistically significant conclusions for effectiveness and effi- ciency. Measuring effectiveness with statistical significance would require the applicationofallfourtechniquestoatleast10-20additionalapplications[47]. Applyingalltechniquesto10-20similarly-sizedSUTsisimpractical,giventhe effort required to apply these techniques to a single application. To mitigate this threat to validity, we performed an extensive review of the vulnerability counts, using the guidelines in Section 5.2, and at least two individuals were involvedin the review processfor eachtechnique to verify the accuracyof the results. We also assess efficiency for at least two individuals to minimize the risk of introducing bias. 8.2 Construct Validity Construct Validity concerns the extent to which the treatments and outcome measures used in the study reflect the higher level constructs we wish to ex- amine [44,46,48]. The number of vulnerabilities and types of vulnerabilitiesComparingEffectiveness andEfficiencyofIASTandRASP 25 arecommonlyusedmeasuresof(in)securityinacademiaandindustry[49,50], including by the U.S. NationalInstitute ofStandards andTechnology(NIST) Software Assurance Metrics and Tool Evaluation (SAMATE) program [50]. We selected our metrics based on these standards and the standards used in the prior work by Elder et al. [3] to enable us to compare the performance of the new techniques against well-known approaches. 8.3 Internal Validity InternalValidityconcernswhethertheobservedoutcomesareduetothetreat- mentapplied,andwhetherotherfactorsmayhaveinfluencedtheoutcome[44, 45].Ourprimarythreattointernalvalidityistheclassificationofalertsgener- atedbythetoolsas‘truepositive’/‘falsepositive’and‘unique’/‘duplicate’has beendone manuallyand,therefore,proneto humanerrorsandbiases,suchas domain knowledge and differences in efficiency of humans. To mitigate this, we haveusedtwo reviewersfor the classificationofalertsanda third reviewer in case of conflicts. 8.4 External Validity External Validity concerns the generalizability of our results [44,45,46]. One threat to external validity is the selection of tools used in this study may not be generalizable. With the exception of RASP, we have used two tools per technique to accommodate tool differences. However, the results may not represent those by other tools of the same technique. Another threat to external validity is the generalizability of our results to other systems. We have used the tools on one large system, OpenMRS, which uses mostly Java and web technologies.We selected a system that uses adiversesetoftechnologies,Java,Hibernate,awiderangeofwebtechnologies for both frontend and backend, and SQL for databases. However, our results may not generalize to other systems using other technologies. 9 Conclusion Thisstudyhasbeenmotivatedbythequestionsfromthepractitionersregard- ingtheselectionofvulnerabilitydetectionandpreventiontechniquesandtools for maximizing the security of applications with optimal resource utilization. ThepreviousstudybyElderetal.[3]hadasimilarmotivation.However,with the recent introduction and increasing discussion on using IAST and RASP tools,our study was motivatedto extend the comparisonoffour vulnerability detection techniques to include the IAST vulnerability detection tool, as well as the RASP exploit prevention tool. We extend their study by testing these two categories of tools and comparing each vulnerability from our result set with their set of vulnerabilities.The main finding of Elder et al. [3] still holds26 AishwaryaSethetal. -eachapproachtovulnerabilitydetectionfoundvulnerabilitiesNOTfoundby the other techniques. However, IAST adds value to the range of vulnerability detection techniques available for organizations to use in terms of increasing efficiency and effectiveness in detecting OWASP Top Ten vulnerabilities. 10 Future Work Weusedanumberofmetrics,suchasvulnerabilitycount,tocomparethevul- nerability detection and preventiontools ona large application.Basedon our experienceandstudy,wefoundadetailedprotocolisrequiredtomaintaincon- sistencyinthe procedureadoptedsoasto makethe resultsreplicableandless subjective. However, more researchis required to evaluate what other factors should be considered in a comparison of vulnerability detection techniques. The scope of researchis even more relevantfor vulnerability preventiontools, whicharequitenascentascomparedtotheearliervulnerabilitydetectiontech- niques, especially when they are still being improved upon to be integrated into an actual production environment and make the process smoother. An additional area of future work is a further exploration of vulnerability severity and related measures, such as the exploitability of vulnerabilities. As can be seen from Table 6, the interpretation of severity can vary between measures of criticality. IAST tools themselves detected vulnerabilities that theyclassifiedas‘lowseverity’butwhichwereassociatedwith‘BrokenAccess Control’, the #1 most critical vulnerability according to the OWASP Top Ten. Similarly, vulnerabilities associatedwith disclosure of information about
application functionality through error messages, associated with #4 in the OWASP Top Ten - ‘Insecure Design’ were not considered particularly critical in this context given that the application is open-source [3]. Therefore, to understand the severity and exploitability of a vulnerability, more research is required. Acknowledgment This workwassupported by the NationalScience Foundation[blinded] grant. The authorswouldalsolike to thank [blinded] for their valuable input onthis paper. References 1. A.Austin,L.Williams,Onetechniqueisnotenough:Acomparisonofvulnerabilitydis- coverytechniques,in:2011InternationalSymposiumonEmpiricalSoftwareEngineering andMeasurement,IEEE,2011,pp.97–106. 2. A.Austin,C.Holmgreen,L.Williams,Acomparisonoftheefficiencyandeffectivenessof vulnerabilitydiscoverytechniques, InformationandSoftwareTechnology 55(7)(2013) 1279–1288.ComparingEffectiveness andEfficiencyofIASTandRASP 27 3. S. Elder, N. Zahan, R. Shu, M. Metro, V. Kozarev, T. Menzies, L. Williams, Do i really need all this work to find vulnerabilities? an empirical case study comparing vulnerabilitydetectiontechniquesonajavaapplication,EmpiricalSoftwareEngineering (2022). 4. Y. Pan, Interactive application security testing, in: 2019 International Confer- ence on Smart Grid and Electrical Automation (ICSGEA), 2019, pp. 558–561. doi:10.1109/ICSGEA.2019.00131. 5. J. Williams, Sast, dast, and iast security testing, https://www.contrastsecurity.com/security-influencers/why-the-difference-between-sast-dast-and-iast-matters, [Online;Accessed14-Dec-2023](2019). 6. R.N.Rajapakse,M.Zahedi, M.A.Babar,Anempiricalanalysisofpractitioners’ per- spectives on security tool integration into devops, in: Proceedings of the 15th ACM / IEEE International Symposium on Empirical Software Engineering and Measurement (ESEM),ESEM’21,AssociationforComputingMachinery,2021. 7. A. Heijstek, Bridging theory and practice: Insights into practical implementations of security practices in secure devops and ci/cd environments, Ph.D. thesis, Universiteit vanAmsterdam(2023). 8. A.Seth,Comparingeffectiveness andefficiencyofinteractive applicationsecuritytest- ing (iast) and runtime application self-protection (rasp) tools, Master’s thesis, North CarolinaStateUniversity(2022). 9. Oracle,Packagejava.lang.instrument,https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/package-summary.html, [Online;Accessed28-Jun-2022] (2022). 10. S.Balakrishan,Understandingjavaagents,https://dzone.com/articles/java-agent-1, [Online;Accessed28-Jun-2022] (2020). 11. F. M. Tudela, J.-R. B. Higuera, J. B. Higuera, J.-A. S. Montalvo, M. I. Argyros, On CombiningStatic,DynamicandInteractiveAnalysisSecurityTestingToolstoImprove OWASPTopTenSecurityVulnerabilityDetectioninWebApplications,in:SpecialIssue CyberSecurityofCriticalInfrastructuresAppl.Sci.2020),Volume10,No24,2020. 12. A. Fry, Runtime application self-protection (rasp), investigation of the effectiveness of a rasp solution in protecting known vulnerable target applications, Tech. rep., SANS Institute(042021). 13. P. Cˇisar, S. M. Cˇisar, The framework of runtime application self-protection technol- ogy, in: 2016 IEEE 17th International Symposium on Computational Intelligence and Informatics(CINTI),2016,pp.000081–000086. doi:10.1109/CINTI.2016.7846383. 14. ISO/IEC/IEEE, Software and systems engineering — software testing — part 1: con- cepts and definitions, ISO/IEC/IEEE 29119-1:2013, International Organization for Standardization(ISO),International ElectrotechnicalCommission(IES),andInstitute ofElectricalandElectronicsEngineers(IEEE)(092013). 15. G.McGraw,Softwaresecurity:buildingsecurityin,Addison-WesleyProfessional,Upper SaddleRiver,NJ,2006. 16. N. Antunes, M. Vieira, Comparing the effectiveness of penetration testing and static code analysis on the detection of sql injection vulnerabilities in web services, in: 2009 15thIEEEPacificRimInternationalSymposiumonDependableComputing,2009,pp. 301–306. doi:10.1109/PRDC.2009.54. 17. N.Antunes,M.Vieira,Benchmarkingvulnerabilitydetectiontoolsforwebservices,in: 2010IEEEInternational ConferenceonWebServices,IEEE,2010,pp.203–210. 18. N. Antunes, M. Vieira, Assessing and comparing vulnerability detection tools for web services: Benchmarking approach and examples, IEEE Transactions on Services Com- puting8(2)(2014)269–283. 19. N.Antunes, M.Vieira,Onthemetricsforbenchmarking vulnerabilitydetection tools, in: 2015 45th Annual IEEE/IFIP international conference on dependable systems and networks,IEEE,2015, pp.505–516. 20. J.-R. Higuera, J. Bermejo, J. A. Montalvo, J. Villalba, J. P´erez, Benchmarking ap- proach to compare web applications static analysis tools detecting owasp top ten security vulnerabilities, Computers, Materials and Continua 64 (2020) 1555–1577. doi:10.32604/cmc.2020.010885. 21. R. Croft, D. Newlands, Z. Chen, M. A. Babar, An empirical study of rule-based and learning-based approaches for static application security testing, in: Proceedings of28 AishwaryaSethetal. the15thACM/IEEEInternationalSymposiumonEmpiricalSoftwareEngineeringand Measurement(ESEM),2021,pp.1–12. 22. G. Piskachev, M. Becker, E. Bodden, Can the configuration of static analyses make resolvingsecurityvulnerabilitiesmoreeffective?-auserstudy,EmpiricalSoftwareEngi- neering28(5)(2023)118.
23. R.Scandariato,J.Walden,W.Joosen,Staticanalysisversuspenetrationtesting:Acon- trolledexperiment,in:2013IEEE24thInternationalSymposiumonSoftwareReliability Engineering(ISSRE), 2013,pp.451–460. doi:10.1109/ISSRE.2013.6698898. 24. J. Fonseca, M. Vieira, H. Madeira, Testing and comparing web vulnerability scanning toolsforsqlinjectionandxssattacks,in:13thPacificRimInternationalSymposiumon DependableComputing(PRDC2007),2007,pp.365–372. doi:10.1109/PRDC.2007.55. 25. A. Doup´e, M. Cova, G. Vigna, Why johnny can’t pentest: An analy- sis of black-box web vulnerability scanners, Vol. 6201, 2010, pp. 111–131. doi:10.1007/978-3-642-14215-4\_7. 26. J.Bau,F.Wang,E.Bursztein,P.Mutchler,J.C.Mitchell,Vulnerabilityfactorsinnew webapplications:Audittools,developer selection&languages,2013. 27. R. Amankwah, J. Chen, P. Kudjo, D. Towey, An empirical comparison of commercial and open-source web vulnerabilityscanners, Software: Practice and Experience 50 (07 2020). doi:10.1002/spe.2870. 28. D. B. Cruz, J. a. R. Almeida, J. L. Oliveira, Open source solutions for vulnera- bility assessment: A comparative analysis, IEEE Access 11 (2023) 100234–100255. doi:10.1109/ACCESS.2023.3315595. 29. F. M. Tudela, J.-R. B. Higuera, J. B. Higuera, J.-A. S. Montalvo, M. I. Argyros, Oncombiningstatic, dynamicandinteractiveanalysissecuritytestingtoolstoimproveowasptoptensecurityvulnerabilitydetection in AppliedSciences (2020). URLhttps://api.semanticscholar.org/CorpusID:234536018 30. M.Ji,M.Yin,Y.H.Zhou,Applicationofstatictaintanalysisinraspprotectionstrategy, in: Proceedings of the 2022 International Conference on Cyber Security, CSW ’22, Association for Computing Machinery, New York, NY, USA, 2023, p. 40–45. doi:10.1145/3584714.3584723. URLhttps://doi.org/10.1145/3584714.3584723 31. H. Setiawan, L. E. Erlangga, I. Baskoro, Vulnerability analysis using the interactive application security testing (iast) approach for government x website applications, in: 2020 3rd International Conference on Information and Communications Technology (ICOIACT),2020,pp.471–475. doi:10.1109/ICOIACT50329.2020.9332116. 32. Open Web Application Security Project (OWASP) Foundation, Owasp benchmark, https://owasp.org/www-project-benchmark/ (2022). 33. A.L.S.Pupo,J.Nicolay,E.G.Boix,Derivingstaticsecuritytestingfromruntimesecurityprotectionforwebapplications, The Art, Science, and Engineering of Programming 6 (1) (jul 2021). doi:10.22152/programming-journal.org/2022/6/1. URLhttps://doi.org/10.22152%2Fprogramming-journal.org%2F2022%2F6%2F1 34. Y.-W. Huang, F. Yu, C. Hang, C.-H. Tsai, D.-T. Lee, S.-Y. Kuo, Securingwebapplicationcodebystaticanalysisandruntimeprotection, in: Pro- ceedings of the 13th International Conference on World Wide Web, WWW ’04, Association for Computing Machinery, New York, NY, USA, 2004, p. 40–52. doi:10.1145/988672.988679. URLhttps://doi.org/10.1145/988672.988679 35. Z. Yin, Z. Li, Y. Cao, A web application runtime application self-protection scheme against script injection attacks, in: Cloud Computing and Security, Springer Interna- tionalPublishing,Cham,2018,pp.566–577. 36. E. Yuan, S. Malek, B. Schmerl, D. Garlan, J. Gennari, Architecture-basedself-protectingsoftwaresystems, in: Proceedings of the 9th In- ternational ACM Sigsoft Conference on Quality of Software Architectures, QoSA ’13, Association for Computing Machinery, New York, NY, USA, 2013, p. 33–42. doi:10.1145/2465478.2465479. URLhttps://doi.org/10.1145/2465478.2465479 37. C. Bailey, L. Montrieux, R. de Lemos, Y. Yu, M. Wermelinger, Run-timegeneration, transformation,andverificationofaccesscontrolmodelsforself-protection,ComparingEffectiveness andEfficiencyofIASTandRASP 29 in:Proceedingsofthe9thInternationalSymposiumonSoftwareEngineeringforAdap- tiveandSelf-ManagingSystems, SEAMS2014, AssociationforComputingMachinery, NewYork,NY,USA,2014, p.135–144. doi:10.1145/2593929.2593945. URLhttps://doi.org/10.1145/2593929.2593945 38. NVD,Vulnerabilities,[Online;Accessed19-Jun-2022] (2022). URLhttps://nvd.nist.gov/vuln 39. MITRE, Cve® numbering authority (cna) rules, https://cve.mitre.org/cve/cna/CNA_Rules_v3.0.pdf (2020). 40. Open Web Application Security Project (OWASP) Foundation, Owasp top ten 2021:Relatedcheatsheets,https://cheatsheetseries.owasp.org/IndexTopTen.html (2021). 41. MITRE,Cwecommonweakness enumeration(website) (2022). URLhttps://cwe.mitre.org/ 42. Open Web Application Security Project (OWASP) Foundation, The owasp top ten applicationsecurityrisksproject,https://owasp.org/www-project-top-ten/ (2022). 43. A. A. U. Rahman, E. Helms, L. Williams,C. Parnin, Synthesizing continuous deploy- mentpracticesusedinsoftwaredevelopment,in:2015AgileConference,2015,pp.1–10. doi:10.1109/Agile.2015.12. 44. T. D. Cook, D. T. Campbell, Quasi-Experimentation: Design and Analysis Issues for FieldSettings, RandMcNallyCollegePublishing,1979.
45. R.Feldt,A.Magazinius,Validitythreats inempiricalsoftwareengineeringresearch-an initialsurvey.,in:Seke,2010,pp.374–379. 46. C.Wohlin,P.Runeson,M.H¨ost,M.C.Ohlsson,B.Regnell,A.Wessl´en,Experimenta- tioninsoftwareengineering,SpringerScience&BusinessMedia,2012. 47. R. Kirk, Experimental Design: Procedures for the Behavioral Sciences, 4th Edition, ThousandOaks:SagePublications,2013. 48. P. Ralph, E. Tempero, Construct validity in software engineering research and soft- waremetrics, in: Proceedings of the 22nd International Conference on Evaluation and AssessmentinSoftwareEngineering2018, 2018,pp.13–23. 49. G. Klees, A. Ruef, B. Cooper, S. Wei, M. Hicks, Evaluatingfuzztesting (2018). doi:10.48550/ARXIV.1808.09700. URLhttps://arxiv.org/abs/1808.09700 50. A. Delaitre, B. Stivalet, P. Black, V. Okun, T. Cohen, A. Ribeiro, Sate v report: Ten years of static analysis tool expositions (2018-10-23 2018). doi:https://doi.org/10.6028/NIST.SP.500-326.This figure "overview.jpeg" is available in "jpeg"(cid:10) format from: http://arxiv.org/ps/2312.17726v1
2401.01114 Static Deadlock Detection for Rust Programs YUZHANG, TongjiUniversity,China KAIWENZHANG, TongjiUniversity,China GUANJUNLIU, TongjiUniversity,China Rustreliesonitsuniqueownershipmechanismtoensurethreadandmemorysafety.However,numerouspotentialsecurity vulnerabilitiespersistinpracticalapplications.NewlanguagefeaturesinRustposenewchallengesforvulnerabilitydetection. ThispaperproposesastaticdeadlockdetectionmethodtailoredforRustprograms,aimingtoidentifyvariousdeadlock types,includingdoublelock,conflictlock,anddeadlockassociatedwithconditionalvariables.Withdueconsiderationfor Rust’sownershipandlifetimes,wefirstcompletethepointeranalysis.Then,basedontheobtainedpoints-toinformation,we analyzedependenciesamongvariablestoidentifypotentialdeadlocks.Wedevelopatoolandconductexperimentsbased ontheproposedmethod.Theexperimentalresultsdemonstratethatourmethodoutperformsexistingdeadlockdetection methodsinprecision. AdditionalKeyWordsandPhrases:RustPrograms,StaticAnalysis,DeadlockDetection 1 INTRODUCTION Rust[15]isanemergingprogramminglanguagedesignedtobuildefficientandsafelow-levelsoftware.Drawing inspirationfromC,itinheritscommendableruntimeperformancewhiledistinguishingitselfthroughrigorous compile-timecheckstoaddresssafetyconcerns.Inrecentyears,Rusthaswitnessedasurgeinpopularity[23–25]. ThecoreofRust’ssafetymechanismsistheconceptofownership,whichallowseachvaluetohaveonlyone owner,andthevalueisfreedwhenitsowner’slifetimeends.Rustextendsthisbasicrulewithaseriesofrulesto ensurememoryandthreadsafety.Despitehavingthesesafetymeasures,Rustprogramsstillexhibitsomesecurity vulnerabilities[13,27,33].Additionally,newlanguagefeaturesinRustposenewchallengesforvulnerability detection. Deadlockisacommontypeofconcurrencyvulnerability,causingcountlesssystemfailureseveryyear[20]. DespiteRust’sassertionof"fearlessconcurrency,"therealityisthatRustprogramsaresusceptibletoconcurrency vulnerabilities.Studies[27,33]indicatethatover50%ofconcurrencyvulnerabilitiesinRustprogramsaredeadlock- related.Programanalysisisapredominantmethodfordeadlockdetection,broadlycategorizedintostaticanalysis anddynamicanalysis.Staticanalysisadoptstheconservativeestimationofvariablevalues,potentiallyleadingto falsepositives.Dynamicanalysisleveragesruntimeinformationforanalysis,butitonlyrevealsapartialviewof theprogram’sbehavior,oftenresultinginfalsenegatives.Presently,thereisascarcityofresearchspecifically dedicatedtodeadlockdetectioninRustprograms.GivenRust’snewlanguagemechanisms,existingresearchon deadlockdetectioninotherlanguages,suchasC/C++[7,8,16,34]andJava[5,21,31],cannotbedirectlyapplied toRust.Consequently,theneedfortailoredresearchinthedomainofdeadlockdetectionforRustprograms becomesevident. IntheexistingresearchondeadlockdetectioninRustprograms,Stuck-me-not[22]focusesonidentifying doublelocksinblockchainsoftware,whichisachievedbytrackingvariablelifetimesthroughdata-flowanalysis ontheMIR.Lockbud[26,27]usesthetypeinformationoftheargumentsforinter-proceduralmethodstoguide theheuristicanalysis,whichissimplebutresultsinmanyfalsepositivesandfalsenegatives. ThispaperaimstoaddressdeadlockdetectionforRustprogramsthroughstaticanalysistechniques.Ourworks aresummarizedasfollows: • Wedesignastaticdeadlockdetectionmethodcapableofidentifyingthefollowingtypesofdeadlock: doublelock,conflictlock,anddeadlockrelatedtoconditionvariables. • Followingtheproposedmethod,wedeveloparelevanttoolandconductcomparativeexperimentswith existingwork,andtheresultsdemonstratethesuperiorprecisionofourmethod. 4202 naJ 2 ]LP.sc[ 1v41110.1042:viXra2 • YuZhang,KaiwenZhang,andGuanjunLiu • WetestourmethodonrealRustprograms,andtheresultsdemonstratetheeffectivenessofourapproach. 2 BACKGROUND 2.1 OwnershipandLifetimes ThecoreofRust’ssafetymechanismsistheconceptofownership.Themostbasicownershipruleallowseach valuetohaveonlyoneowner,andthevalueisfreedwhenitsowner’slifetimeends.Thelifetimeofavariable isthescopewhereitisvalid.Rustextendsthisbasicrulewithasetoffeaturestosupportmoreprogramming flexibilitywhilestillensuringmemoryandthreadsafety. Move.Theownershipofavaluecanbemovedfromonescopetoanother,suchasfromacallertoacalleeor betweenthreads.TheRustcompilerguaranteesthatanownervariablecannotbeaccessedafteritsownershipis moved,preventingdanglingreferencesandensuringmemorysafety. ReferencesandBorrowing.Avalue’sownershipcanalsobetemporarilyborrowed,allowingaccesstoavalue withouttransferringownership.Borrowingisachievedbypassingareferencetothevaluetoanothervariable. Rustdistinguishesbetweenimmutablereferences,allowingread-onlyaliasing,andmutablereferences,allowing writeaccesstothevalue.Therecanonlybeeitheronemutablereferenceormultipleimmutablereferencesatany giventime.Additionally,Rustprohibitsborrowingownershipacrossthreadstopreventdataracesandensure threadsafety. 2.2 Mid-levelIntermediateRepresentation Staticprogramanalysisistypicallybasedonintermediatelanguages[3,19,28–30].Rust’scompilercangenerate severalintermediaterepresentations,includingHIR(High-levelIntermediateRepresentation),MIR(Mid-level
IntermediateRepresentation),andLLVMIR(LowLevelVirtualMachineIntermediateRepresentation)[17].We conductstaticanalysisbasedonMIRovertheothertwoforthefollowingreasons.First,MIRoffersfastercompila- tionandexecutiontimes.Second,MIRsimplifiesmostofRust’scomplexsyntaxintoamorestraightforwardcore languagewhilepreservingvaluabletypeinformationanddebuggingdata.It’sworthnotingthat,theoretically, toolsdevelopedbasedonLLVMIRcanbeusedforanylanguagethatcanbecompiledintoLLVMIR.However, mostLLVMIR-basedtoolsforC/C++[7,28]maynotbedirectlyapplicabletoRust,potentiallyduetothelackof supportforspecificLLVMIRpatternsandthelackofasuitablestandardlibrarymodel[4,9]. 2.3 DeadlockPatterns Rust’s locking mechanism differs from traditional multithreaded programming languages such as C/C++ in severalways[15].First,Rust’slocksprotectdatainsteadofcodefragments.Second,Rustdoesnotexplicitly providetheunlock()function.LocksarereleasedautomaticallybytheRustcompiler.Toallowmultiplethreads towriteaccesstosharedvariablessafely,RustdeveloperscandeclarevariableswithbothArcandMutex.The lock()functionreturnsareferencetothesharedvariableandlocksit.TheRustcompilerverifiesthatallaccesses tothesharedvariablearemadewiththelockinplace,thusguaranteeingmutualexclusivity.TheRustcompiler automaticallyreleasesthelockbyimplicitlycallingtheunlock()functionwhenthelifetimeofthereturned variableholdingthereferenceisover. Wedetectdeadlocksinthreepatterns:doublelock,conflictlock,anddeadlockrelatedtoconditionvariables. ThesethreepatternscoverthemajorityofdeadlockproblemsinRustprograms. DoubleLock.Somestudies[22,27,33]indicatethatthedoublelockproblemsarethemostsignificantdeadlock problemsofRustprograms,andthecauseofthisphenomenonisthemisunderstandingofRust’slifetimerulesby developers.Rustemploystheautomaticunlockingmechanismtohelpdevelopersavoidforgettingtounlock, butinpracticaldevelopment,thisruleexacerbatestheseverityofthedoublelockproblemincertainaspects. AlthoughRust’sdoublelockproblemmayseemstraightforward,itbecomesintricate,mainlywhendealingwithStaticDeadlockDetectionforRustPrograms • 3 Fig.1. DoubleLock. patternmatchingandfunctioncalls,makingitsusceptibletobeingoverlookedbydevelopers.Figure1showsa doublelock.Inthisexample,thelockacquiredinline12isthesameastheoneattemptedtobeacquiredinline4. Sincethelockacquiredinline4isnotreleased,theoperationinline12resultsinadeadlock. ConflictLock.ConflictlockistheprimarytypeofdeadlockdetectioninC/C++andJava[7,8,16,21,31].In Rust’sdeadlockproblemsrelatedtoMutex/RwLock,conflictlockproblemsarethesecondmostprevalentafter doublelockproblems.Whentwoormorethreadsacquirelocksinconflictingorders,itcanleadtodeadlockin Rust.Figure2isanexampleofconflictlock. ConditionVariablesRelated.Doublelocksandconflictlocksareresourcedeadlocks,whiledeadlocksrelatedto conditionvariablesfallintothecategoryofcommunicationdeadlocks[1,12,14,34].Therearetwomaintypesof deadlocksrelatedtoconditionvariables.Thefirsttypeinvolvesdeadlockscausedbytheinteractionbetween locksandconditionalvariables,andthesecondtypearisesduetotheimproperusageofconditionvariables. Similartothepreviouslymentionedconflictlocks,thefirsttypeofdeadlockrelatedtoconditionvariables differs because it involves interaction between locks and condition variables. Figure 3 illustrates a deadlock scenario.Specifically,whenthreadth1acquiresmu1andentersablockedstatethroughwait(),awaitingthe notifysignalfromthreadth2.Uponexecution,threadth2initiallyattemptstoacquiremu2.However,dueto bothmu1andmu2beingthesamelockandth1notreleasingthemutex,boththreadsbecometrappedinastate ofcircularwaiting. Conditionvariablesaretypicallyassociatedwithabooleantype(referredtoasacondition)andamutex.The verificationofthebooleantypealwaystakesplacewithinthemutexbeforedeterminingwhetherathreadshould beblocked[15].Improperusageofconditionvariablescaneasilyresultindeadlocks,whichoftenoccurwhen notify()ismissingorwhentheconditioncannotbesatisfied,causingthewaitingthreadtoremainindefinitely blocked,asdepictedinFigure4.Ifline15andline16werenotcommentedout,thisscenariowouldperfectly4 • YuZhang,KaiwenZhang,andGuanjunLiu Fig.2. ConflictLock. demonstratetheappropriateusecaseofCondvarinRust.However,sincethreadth2doesnotmodifystartedto truewhentheselinesarecommentedout,itfailstofulfilltheawaitedconditionforthethreadth1.Consequently, thethreadth1becomesindefinitelyblocked,leadingtoadeadlockintheprogram. 3 METHODOLOGY 3.1 Framework TheframeworkofourmethodisillustratedinFigure5,withtheprimaryprocessesdividedintotwoparts:pointer analysisanddeadlockdetection. Thepoints-torelationshipsbetweenvariablesarecrucialfortheaccuracyofdeadlockdetectioninRust.In Figure1,detectingthisdeadlockisonlypossiblewhenweknowthealiasingrelationshipbetweenq1andq2.ItisStaticDeadlockDetectionforRustPrograms • 5 Fig.3. DeadlockRelatedtoConditionVariables:interactionbetweenMutexandCondvar. lockbud’s[26,27]imprecisepointeranalysisthatleadstofalsepositivesandfalsenegatives.Afterconsidering
therequirementsforefficiencyandprecision,weimplementedafield-sensitive,flow-andcontext-insensitive inter-proceduralpointeranalysis.Inthedeadlockdetectionphase,thecentralideaistoanalyzethedependency relationshipsbetweenlocks.Weconductfield-,context-andthread-sensitiveanalysistoidentifyalllocksand conditionvariablesandanalyzetheirdependencyrelationships,whicharevisualizedthroughlockgraphsand extendedlockgraphs. 3.2 PointerAnalysis BasedontheAndersenpointeranalysisalgorithm[2],wehaveimplementedfield-sensitive,flow-andcontext- insensitiveinter-proceduralpointeranalysis.Directlycalculatingpointerinformationontheprogramishardto maintainandextend[10,18,32].ThestaticanalysistoolSVF[28]forC/C++addressesthisissue.Thepointer6 • YuZhang,KaiwenZhang,andGuanjunLiu Fig.4. DeadlockRelatedtoConditionVariables:improperuseofCondvar. Fig.5. TheFrameworkofMethod. analysisdesignofSVFconsistsofthreelooselycoupledcomponents:graph,rules,andsolver.Wehaveadopted thismethodandsimilarlyimplementedpointeranalysisusingthesethreecomponents.Thefollowingaredetailed explanationsofthesethreecomponents.StaticDeadlockDetectionforRustPrograms • 7 Utilizetheconstraintgraphtodepictthepoints-torelationshipsbetweenvariables,representedasabinary tupleasfollows: • 𝐶𝑜𝑛𝑠𝐺 = (N,E). N represents the set of all nodes, and E represents the set of all edges. A node 𝑛 = (𝑝,𝛾) ∈N where𝑝 isaplaceinMIR,whichrepresentsalocationinmemory,and𝛾 representsthe functioninstanceinwhich𝑝 islocated.𝑒 = (𝑛 𝑠,𝑛 𝑡,𝜏) ∈ E representsadirectededgefromnode𝑛 𝑠 to𝑛 𝑡 withthetype𝜏 ∈ T,whereT = {𝑎𝑑𝑑𝑟𝑒𝑠𝑠,𝑐𝑜𝑝𝑦,𝑙𝑜𝑎𝑑,𝑠𝑡𝑜𝑟𝑒,𝑓𝑖𝑒𝑙𝑑}. Table1. Rules Pattern MIRStatements EdgesofConsG Rules 𝑎 =&𝑏 (𝑏,𝑎,𝑎𝑑𝑑𝑟𝑒𝑠𝑠) 𝑏 ∈𝑝𝑡𝑠(𝑎) A=&B 𝑎 =&∗𝑏 (𝑏,𝑎,𝑐𝑜𝑝𝑦) 𝑝𝑡𝑠(𝑏) ⊆𝑝𝑡𝑠(𝑎) 𝑎 =𝑏 (𝑏,𝑎,𝑐𝑜𝑝𝑦) 𝑝𝑡𝑠(𝑏) ⊆𝑝𝑡𝑠(𝑎) 𝑎 =move𝑏 - - 𝑎 =∗𝑏 (𝑏,𝑎,𝑙𝑜𝑎𝑑) ∀𝑜 ∈𝑝𝑡𝑠(𝑏),𝑝𝑡𝑠(𝑜) ⊆𝑝𝑡𝑠(𝑎) A=B 𝑎 =𝑏.𝑥 (𝑏.𝑥,𝑎,𝑐𝑜𝑝𝑦),(𝑏,𝑏.𝑥,𝑓𝑖𝑒𝑙𝑑) ∀𝑜 ∈𝑝𝑡𝑠(𝑏),𝑝𝑡𝑠(𝑜.𝑥) ⊆𝑝𝑡𝑠(𝑎) ∗𝑎 =𝑏 (𝑏,𝑎,𝑠𝑡𝑜𝑟𝑒) ∀𝑜 ∈𝑝𝑡𝑠(𝑎),𝑝𝑡𝑠(𝑏) ⊆𝑝𝑡𝑠(𝑜) 𝑑=𝑓(𝑝 ,𝑝 ,_) fn:𝑓(&𝑎 ,&1 𝑎2 ,_)→− 𝑟 (𝑝 𝑖,𝑎 𝑖,𝑐𝑜𝑝𝑦),(𝑟,𝑑,𝑐𝑜𝑝𝑦) 𝑝𝑡𝑠(𝑝 𝑖) ⊆𝑝𝑡𝑠(𝑎 𝑖),𝑝𝑡𝑠(𝑟) ⊆𝑝𝑡𝑠(𝑑) CALL 1 2 𝑑=𝑓(move𝑝 ,move𝑝 ,_) 1 2 - - fn:𝑓(𝑎 ,𝑎 ,_)→− 𝑟 1 2 𝑑=𝑓(move𝑝 ,move𝑝 ,_) 𝑝 𝑖:Arc,fn:𝑓(1 𝑎 1,𝑎 2,_)→2 − 𝑟 (𝑝 𝑖,𝑎 𝑖,𝑐𝑜𝑝𝑦),(𝑟,𝑑,𝑐𝑜𝑝𝑦) 𝑝𝑡𝑠(𝑝 𝑖) ⊆𝑝𝑡𝑠(𝑎 𝑖),𝑝𝑡𝑠(𝑟) ⊆𝑝𝑡𝑠(𝑑) 𝑎 = 𝑓 𝑖𝑛(move𝑏,_) (𝑏,𝑎,𝑐𝑜𝑝𝑦) 𝑝𝑡𝑠(𝑏) ⊆𝑝𝑡𝑠(𝑎) INLINECALL 𝑎=clone(move𝑏) - - 𝑎=Arc::clone(move𝑏) (𝑏,𝑎,𝑐𝑜𝑝𝑦) 𝑝𝑡𝑠(𝑏) ⊆𝑝𝑡𝑠(𝑎) Eventhoughwedonotconsiderthevariable’slifetimeduringthepointeranalysisphase,weperformadditional processingforstatementsinvolvingthemovekeywordandsmartpointerArc.Thismeasurehelpsreducethesize oftheconstraintgraph,therebyloweringtimeoverhead.Table1outlinestheprimaryassignmentandfunction call patterns rules. Following this set of rules, we traverse all instances, adding corresponding edges to the constraintgraphwhenprocessingassignmentsandfunctioncalls.Figure6presentsacodefragmentalongwith theinitialconstraintgraphconstructedforitbasedontherules. Oncethetraversaliscomplete,weobtaintheinitialconstraintgraph.Subsequently,withinthesolvercomponent, weapplyafixed-pointalgorithmtotheconstraintgraph,managingconstraintrelationshipsandupdatingpoints- toinformation.Algorithm1providesadetaileddescriptionofthisprocess.Thetimecomplexityofconstructing theconstraintgraphbytraversingallfunctionsdependsonthenumberandscaleofcrates.Assumingthenumber ofnodesintheinitialconstraintgraphis𝑁,thetimecomplexityofsolvingthepoints-torelationshipsis𝑂(𝑁3). 3.3 DeadlockDetection Wefirstdescribethedetectionalgorithmsfordoublelockandconflictlock,followedbyadescriptionofthe deadlockdetectionalgorithmrelatedtoconditionalvariables. Doublelockproblemsoftenoccurwithinasinglethread,andconflictlockproblemscommonlyariseduring concurrentexecutionacrossmultiplethreads.Toascertaintheconcurrentrelationshipsbetweenthreads,we needtoanalyzethelifetimesofthreads.InRust’ssynchronizationmechanism,eachMutexhasaparametertype8 • YuZhang,KaiwenZhang,andGuanjunLiu Algorithm1:Solver input :Theinitialconstraintgraph𝐶𝑜𝑛𝑠𝐺 = (N,E). output:Themapofpoints-toinformation𝑀 =∅ 1 𝑊𝐿 =∅; 2 foreach𝑒 inE do 3 if𝑒.𝑡𝑦𝑝𝑒 is𝑎𝑑𝑑𝑟𝑒𝑠𝑠 then 4 𝑀[𝑛 𝑡] =𝑀[𝑛 𝑡]∪𝑛 𝑠 ,Push𝑛 𝑡 to𝑊𝐿; 5 whileWLisnot∅do 6 Pop𝑛from𝑊𝐿; 7 foreach𝑜 in𝑀[𝑛] do 8 foreach𝑛 𝑠 in𝑠𝑡𝑜𝑟𝑒_𝑒𝑑𝑔𝑒𝑠_𝑠𝑜𝑢𝑟𝑐𝑒𝑠(𝑛)do 9 Add(𝑛 𝑠,𝑜,𝑐𝑜𝑝𝑦)toE,push𝑛 𝑠 to𝑊𝐿; 10 foreach𝑛 𝑡 in𝑙𝑜𝑎𝑑_𝑒𝑑𝑔𝑒𝑠_𝑡𝑎𝑟𝑔𝑒𝑡𝑠(𝑛)do 11 Add(𝑜,𝑛 𝑡,𝑐𝑜𝑝𝑦)toE,push𝑜 to𝑊𝐿; 12 foreach𝑛 𝑓 in𝑓𝑖𝑒𝑙𝑑_𝑒𝑑𝑔𝑒𝑠_𝑡𝑎𝑟𝑔𝑒𝑡𝑠(𝑛)do 13 Add𝑛 𝑓 = (𝑜.𝑓,𝑜.𝛾 𝑖𝑑)toE; 14 Add(𝑛 𝑓,𝑛 𝑡,𝑐𝑜𝑝𝑦)toE,push𝑛 𝑡 to𝑊𝐿; 15 foreach𝑛 𝑡 in𝑐𝑜𝑝𝑦_𝑒𝑑𝑔𝑒𝑠_𝑡𝑎𝑟𝑔𝑒𝑡𝑠(𝑛)do 16 𝑀[𝑛 𝑡] =𝑀[𝑛 𝑡]∪𝑀[𝑛]; 17 if𝑀[𝑛 𝑡] haschanged then 18 Push𝑛 𝑡 to𝑊𝐿; representingthedataitprotects.Accesstothisdataisexclusivelyfacilitatedthroughthelock()methods.By usinglock(),thecorrespondingMutexGuardisobtained.WhenMutexGuardisdropped(fallsoutofscope),the RustcompilerautomaticallyunlocksMutex.Therefore,wecanillustratethecurrentusagesituationoflocks byanalyzingthelifetimeofMutexGuard,andthesameinRwLock.Basedonthelifetimeinformationcontained inMIR,wecandirectlyobtainthestartandendpositionsoftheguardvariable’slifetime,thusinferringthe
dependencyrelationshipsbetweenlocks.Weusethelockgraphtorepresentthesedependenciesvisually.The representationoftherelevantdatastructuresisdescribedbelow: • 𝜆 = (𝜂 𝑠𝑤,𝜂 𝑗𝑛,𝛽).𝜆 describesathread.𝜂 𝑠𝑤 and𝜂 𝑗𝑛 arethelinenumbersofspawn()andjoin()inthe sourcecode.𝛽 = [𝜂 ,𝜂 ,...] representsthecallhierarchyatthetimeofthreadcreation.Ifthethreadis 1 2 createdwithinthemain()function,𝛽 isempty. • 𝐺 = (𝑛,𝜃,𝜂,𝛽,𝜆,Σ).𝐺 describesthelock’sguardstructure.𝑛representsthecorrespondingnodeof𝐶𝑜𝑛𝑠𝐺. 𝜃 ∈ {𝑀𝑋,𝑅,𝑊}representsthetypeofguardvariables,correspondingtoMutexGuard,RwLockReadGuard, andRwLock-WriteGuard.𝜂 representsthelocationwheretheguardvariableisintroduced,indicatedby thelinenumberinthesourcecode.𝛽 = [𝜂 ,𝜂 ,...] representsthecurrentcallhierarchy.𝜆isthecurrent 1 2 threadandΣisthesetofotherguardvariablesalivecurrent. • 𝐿𝐺 = (Ω,Π).𝐿𝐺 representsthelockgraphstructure,where Ω isthesetofalllockgraphnodes,and eachnodeisa𝐺.𝜋 = {(𝐺 ,𝐺 ,𝑘)} ∈ Πrepresentsanedgeinthelockgraph.𝑘 ∈ {𝐷,𝐴},𝐷 represents 1 2 adirectededgefrom𝐺 to𝐺 ,indicatingthedependencyrelationshipbetweenthem,i.e.,acquiring𝐺 1 2 2StaticDeadlockDetectionforRustPrograms • 9 Fig.6. Acodefragmentanditsinitialconstraintgraph. whileholding𝐺 .𝐴representsabidirectionaledgefrom𝐺 to𝐺 ,indicatingthattheyarealiases.Each 1 1 2 cycleinthelockgraphrepresentsaconflictlock. Wecollectallguardvariablesviafield-,context-andthread-sensitiveanalysis.Then,wecomparetheirlifetimes, threads,andtypes.Iftheyareinthesamethread,havethesametype,andtheirlifetimesoverlap,checkfor aliasingrelationshipsviaaliasanalysis[6].Ifaliasingrelationshipsarepresent,itisdetectedasadoublelock.For example,inFigure1,theguardvariablesg1andg2canbedescribedasfollows: 𝐺 𝑔1 =(𝑛 𝑔1,𝑀𝑋,4,[],𝜆 𝑚𝑎𝑖𝑛,∅) 𝐺 𝑔2 =(𝑛 𝑔2,𝑀𝑋,12,[5],𝜆 𝑚𝑎𝑖𝑛,{𝐺 𝑔1})10 • YuZhang,KaiwenZhang,andGuanjunLiu Algorithm2:Detectionfordoublelockandconflictlock input :Thesetofallguardvariables𝐺𝑉. output:Thesetofalldoublelocks𝐷𝐿andthesetofallconflictlocks𝐶𝐿. 1 𝐷𝐿 =∅,𝐶𝐿 =∅,𝐿𝐺 =∅; 2 foreach𝐺 in𝐺𝑉 do 3 if𝐺.Σisnot∅then 4 foreach𝐺 𝑖 inΣdo 5 𝜃 1=𝐺.𝜃,𝜃 2=𝐺 𝑖.𝜃 ; 6 if (𝜃 1,𝜃 2) ∈ {𝑀𝑀,𝑅𝑊,𝑊𝑊,𝑊𝑅}then 7 if alias(𝐺.𝑛,𝐺 𝑖.𝑛)then 8 Add(𝐺,𝐺 𝑖)to𝐷𝐿; 9 else 10 Add(𝐺,𝐺 𝑖,𝐷)to𝐿𝐺.Π; 11 if (𝜃 1,𝜃 2) ∈ {𝑀𝑅,𝑀𝑊,𝑅𝑀,𝑊𝑀}then 12 Add(𝐺,𝐺 𝑖,𝐷)to𝐿𝐺.Π; 13 foreach𝜋 1,𝜋 2in𝐿𝐺.Πdo 14 if𝜋 1.𝑘,𝜋 2.𝑘 is𝐷 then 15 𝐺 11=𝜋 1.𝐺 1,𝐺 12=𝜋 1.𝐺 2; 16 𝐺 21=𝜋 2.𝐺 1,𝐺 22=𝜋 2.𝐺 2; 17 if concurrency(𝐺 11.𝜆,𝐺 21.𝜆)then 18 if (𝐺 11.𝜃,𝐺 22.𝜃),(𝐺 12.𝜃,𝐺 21.𝜃) ∈ {𝑀𝑀,𝑅𝑊,𝑊𝑊,𝑊𝑅}then 19 if alias(𝐺 11.𝑛,𝐺 22.𝑛)&alias(𝐺 21.𝑛,𝐺 12.𝑛)then 20 Add(𝐺 11,𝐺 22,𝐴),(𝐺 21,𝐺 12,𝐴)to𝐿𝐺.Π; 21 if alias_common(𝐺 11.Σ,𝐺 21.Σ)is∅then 22 Add(𝐺 11,𝐺 12,𝐺 21,𝐺 22)to𝐶𝐿; Since𝐺 𝑔1 is alive when𝐺 𝑔2 is acquired, and they share the same type and thread, we compare the aliasing relationshipbetween𝑛 𝑔1 and𝑛 𝑔2.Accordingtothepointeranalysis,wecanconcludethatthereisanaliasing relationshipbetweenthem.Therefore,thisexampleisadoublelock. Iftheguardvariablesareinthesamethreadbuthavedifferenttypesortherearenoaliasingrelationships,a dependencyrelationshipisaddedbetweenthem.Fordifferentthreadswithoverlappinglifetimes,theiraliasing relationshipsarecomparedifthelockshavethesametype.IntheexampleillustratedinFigure2,theguard variablesatlines7,9,13,and15canberespectivelyrepresentedasfollows: 𝐺 𝑟𝑤1 =(𝑛 𝑟𝑤1,𝑊,7,[22],𝜆 𝑡ℎ1,∅) 𝐺 𝑟𝑒𝑡1 =(𝑛 𝑟𝑒𝑡1,𝑅,9,[22],𝜆 𝑡ℎ1,{𝐺 𝑟𝑤1}) 𝐺 𝑟𝑤2 =(𝑛 𝑟𝑤2,𝑊,13,[23],𝜆 𝑚𝑎𝑖𝑛,∅) 𝐺 𝑟𝑒𝑡2 =(𝑛 𝑟𝑒𝑡2,𝑅,15,[23],𝜆 𝑚𝑎𝑖𝑛,{𝐺 𝑟𝑤2}) Thecorrespondingthreadsarerepresentedas:𝜆 𝑡ℎ1 = (22,24,[]),𝜆 𝑚𝑎𝑖𝑛 = (19,25,[]).Asthereisnoaliasing relationshipbetween𝐺 𝑟𝑤1 and𝐺 𝑟𝑒𝑡1,wecanaddadependencyrelationshipbetweenthem.ThesameappliestoStaticDeadlockDetectionforRustPrograms • 11 Fig.7. LockGraphforTheExampleinFigure2. 𝐺 𝑟𝑤2and𝐺 𝑟𝑒𝑡2.Andthroughpointeranalysis,itcanbedeterminedthat𝐺 𝑟𝑤1isaliasingwith𝐺 𝑟𝑒𝑡2,and𝐺 𝑟𝑒𝑡1is aliasingwith𝐺 𝑟𝑤2.Therefore,theycauseaconflictlock.Thealiasinganddependencyrelationshipsbetween thesevariablescanbevisuallyrepresentedinthelockgraph,asshowninFigure7. DetectingconflictlockanddoublelockisdetailedinAlgorithm2.Whendeterminingthetypesoftwoguard variables,wedefineapairrelationshipbetween𝜃 consideringthecharacteristicsofRwLock.Forexample,𝑀𝑀 representstwoMutexGuardandsoon.Subsequentprocessingisnecessaryonlywhenthepairis𝑀𝑀,𝑅𝑊,𝑊𝑊,or 𝑊𝑅.𝑎𝑙𝑖𝑎𝑠()determineswhetherthereisanaliasingrelationshipbetweentwonodes,and𝑐𝑜𝑛𝑐𝑢𝑟𝑟𝑒𝑛𝑐𝑦()assesses whethertwothreadscanexecuteconcurrently.Additionally,weuse𝑎𝑙𝑖𝑎𝑠 𝑐𝑜𝑚𝑚𝑜𝑛()tocheckforthepresenceof thesamelockormutuallyaliasedlocks,therebyeliminatingfalsepositivescausedbygatelock[11]. Conditionvariablesaretypicallyassociatedwithabooleanpredicate(acondition)andamutex.Thepredicateis alwaysverifiedinsidethemutexbeforedeterminingthatathreadmustbeblocked.wait()atomicallyunlocksthe mutexspecifiedandblocksthecurrentthread.notify()wakesuptheblockedthreadonthesamecondvar.By analyzingthewait()andnotify()statements,wecanidentifythedependencyrelationshipbetweenconditional variablesandlocks.Weusetheextendedlockgraphtorepresentthesedependenciesvisually.Therepresentation
oftherelevantdatastructuresisdescribedbelow: • 𝑊𝑇/𝑁𝑇 = (𝑛 𝑐𝑣𝑎𝑟,𝑛 𝑙𝑜𝑐𝑘,𝜂,𝛽,𝜆,Σ).𝑊𝑇 and𝑁𝑇 describethewait()andnotify()statementsrespectively. 𝑛 𝑐𝑣𝑎𝑟 and𝑛 𝑙𝑜𝑐𝑘 representnodesof𝐶𝑜𝑛𝑠𝐺 associatedwiththeconditionvariableandlock,respectively. Themeaningof𝛽,𝜆,andΣissameasin𝐺. • 𝐸𝐿𝐺 = (Ω,Π).𝐸𝐿𝐺 representstheextendedlockgraph.Ωisthesetofallnodes,andeachnode𝜔 isa 𝐺 orthesignalofnotify𝑆 𝑛𝑡.𝜋 = {(𝜔 1,𝜔 2,𝑘)} ∈ Πrepresentsanedgeinthelockgraph.𝑘 ∈ {𝐷,𝐴}has thesamemeaningasin𝐿𝐺.weassume𝑊𝑇 applies𝑆 𝑛𝑡 and𝑁𝑇 holds𝑆 𝑛𝑡.Therefore,ifthereareguard variablesin𝑊𝑇.Σ(excludingnodesrelatedto𝑛 𝑙𝑜𝑐𝑘),edgesbeaddedfrom𝐺 𝑖 to𝑆 𝑛𝑡.Correspondingly,if thereareguardvariablesin𝑁𝑇.Σ(excludingnodesrelatedto𝑛 𝑙𝑜𝑐𝑘),edgesbeaddedfrom𝑆 𝑛𝑡 to𝐺 𝑗. Byperformingaliasanalysisonconditionvariables,wecompletethepairingofwait()andnotify().Then, we determine whether the current threads can execute concurrently. If not, the wait() leads to permanent blocking.Next,wecheckwhetherguardvariablesinΣarealiasesofeachother(excludingtheguardvariable associatedwiththe𝑛 𝑙𝑜𝑐𝑘).Ifso,adeadlockmayoccur.AsshowninFigure3,thewait()online12andthe notify()online20canberepresentedasfollows: 𝑊𝑇 =(𝑛 𝑐𝑣𝑎𝑟,𝑛 𝑙𝑜𝑐𝑘,12,[𝜂 𝑐],𝜆 𝑡ℎ1,{𝐺 𝑖1,𝐺 𝑠𝑡𝑎𝑟𝑡𝑒𝑑}) 𝑁𝑇 =(𝑛 𝑐𝑣𝑎𝑟,𝑛 𝑙𝑜𝑐𝑘,20,[𝜂 𝑐],𝜆 𝑡ℎ2,{𝐺 𝑖2,𝐺 𝑠𝑡𝑎𝑟𝑡𝑒𝑑})12 • YuZhang,KaiwenZhang,andGuanjunLiu Algorithm3:DetectionfordeadlocksrelatedtoCondvar input :Thesetofallguardvariables𝐺𝑉,Thesetofallwaitandnotifystatements𝑊𝑇𝑉,𝑁𝑇𝑉. output:Thesetofalldeadlocksrelatedtoconditionvariables𝐶𝑉𝐿. 1 𝐶𝑉𝐿 =∅,𝐸𝐿𝐺 =∅; 2 Thesetofmatchedwait-notifypairs:𝑃 =∅; 3 foreach𝑊𝑇 in𝑊𝑇𝑉 do 4 foreach𝑁𝑇 in𝑁𝑇𝑉 do 5 if alias(𝑊𝑇.𝑛 𝑐𝑣𝑎𝑟,𝑁𝑇.𝑛 𝑐𝑣𝑎𝑟)then 6 add(𝑊𝑇,𝑁𝑇)toP; 7 Add(𝑊𝑇,∅)to𝐶𝑉𝐿; 8 foreach(𝑊𝑇,𝑁𝑇)inP do 9 if concurrency(𝑊𝑇.𝜆,𝑁𝑇.𝜆)then 10 if 𝐺 𝑙𝑜𝑐𝑘 ∉𝑁𝑇.Σthen 11 Add(𝑊𝑇,𝑁𝑇)to𝐶𝑉𝐿; 12 foreach𝐺 𝑖 in𝑊𝑇.Σ−𝐺 𝑙𝑜𝑐𝑘 do 13 Add(𝐺 𝑖,𝑆 𝑛𝑡,𝐷)to𝐸𝐿𝐺.Π; 14 foreach𝐺 𝑗 in𝑁𝑇.Σ−𝐺 𝑙𝑜𝑐𝑘 do 15 Add(𝑆 𝑛𝑡,𝐺 𝑗,𝐷)to𝐸𝐿𝐺.Π; 16 if alias(𝐺 𝑖,𝐺 𝑗)then 17 Add(𝐺 𝑖,𝐺 𝑗,𝐴)to𝐸𝐿𝐺.Π; 18 Add(𝑊𝑇,𝑁𝑇)to𝐶𝑉𝐿; 19 else 20 Add(𝑊𝑇,𝑁𝑇)to𝐶𝑉𝐿; Fig.8. ExtendedLockGraphforTheExampleinFigure3. Andthecorrespondingthreadsare:𝜆 𝑡ℎ1 = (7,22,[𝜂 𝑐]),𝜆 𝑠𝑡𝑎𝑟𝑡𝑒𝑑 = (15,23,[𝜂 𝑐]).Inthreadth1,𝐺 𝑖1 isinitially locked,andthenwait()leadstoablockedstate,awaitingthenotifysignalfromtheth2.Inth2,𝐺 𝑖2 mustbe lockedbeforereleasingthenotifysignal.Since𝐺 𝑖1and𝐺 𝑖2arealiasesrepresentingthesamelock,thisresultsin mutualwaitingbetweenthem.TheextendedlockgraphinFigure8visuallyillustratesthisprocess.StaticDeadlockDetectionforRustPrograms • 13 Deadlockscausedbyimproperuseofconditionvariablesmainlyinvolvelosingnotifysignalsandconditions thatwillneverbesatisfied.Completingthepairingofwait()andnotify()andcheckingwhetherthethreads canexecuteconcurrentlyhelpdetectdeadlockscausedbymissingnotifysignalseffectively.Forthesecondtype, wehaveonlyconductedaroughanalysisandhavenotimplementedthepreciseanalysisofvariablevalues. Topreventspuriouswakeups,acommonlyusedpracticewhenusingwaitistoaddanassociatedboolean predicate.Inmostsituations,thisassociatedbooleanpredicateisoftenrelatedtothedataprotectedbythelock associatedwiththeconditionvariable,asillustratedinFigure4,whichchecksthevariablestarted.Weroughly checkwhetherthisvariableisusedinthenotifythread;ifitisnotused,weconsideritaconditionthatcannotbe satisfied.Forexample,thestatementsinline9andline17canberepresentedasfollows: 𝑊𝑇 =(𝑛 𝑐𝑣𝑎𝑟,𝑛 𝑙𝑜𝑐𝑘,9,[𝜂 𝑐],𝜆 𝑡ℎ1,{𝐺 𝑠𝑡𝑎𝑟𝑡𝑒𝑑}) 𝑁𝑇 =(𝑛 𝑐𝑣𝑎𝑟,𝑛 𝑙𝑜𝑐𝑘,17,[𝜂 𝑐],𝜆 𝑡ℎ2,{∅}) Since𝐺 𝑠𝑡𝑎𝑟𝑡𝑒𝑑 is not included in 𝑁𝑇.Σ, this is detected as a deadlock. However, using this variable does not guaranteethatthepredicateissatisfied.Itrequiresaspecificanalysisofthevaluesofrelevantvariables.We havenotimplementedityet,whichwillbecompletedinourfuturework.Thedetaileddescriptionfordetecting deadlocksrelatedtoconditionvariablescanbefoundinAlgorithm3. Theentiredeadlockdetectionprocessfirstrequirestraversingallfunctionstocollectinformationrelatedto locksandconditionvariables.Thisprocessisdependentonthenumberandscaleofcrates.Assumingthenumber ofcollectedlocksandconditionvariablesisdenotedas𝑍,thetimecomplexityofthesubsequentdetectionprocess is𝑂(𝑍3). 4 CONCLUSION WeproposeastaticdeadlockdetectionmethodforRustprogramstargetingtheprimarydeadlocktypesinRust. Then,wedevelopacorrespondingtoolandconductexperiments.ComparedtoexistingRustdeadlockdetection tools,ourresultsshowgreaterprecision,identifyingfalsepositivesandnegativesinothertools.Inthefuture,we intendtoimproveourmethodandtooltoachievegreaterprecisionandsupportmoredeadlocktypes. REFERENCES [1] RahulAgarwalandScottDStoller.2006.Run-timedetectionofpotentialdeadlocksforprogramswithlocks,semaphores,andcondition variables.InProceedingsofthe2006workshoponParallelanddistributedsystems:testinganddebugging.51–60. [2] LarsOleAndersen.1994.ProgramanalysisandspecializationfortheCprogramminglanguage.(1994). [3] YechanBae,YoungsukKim,AmmarAskar,JungwonLim,andTaesooKim.2021. Rudra:findingmemorysafetybugsinrustatthe ecosystemscale.InProceedingsoftheACMSIGOPS28thSymposiumonOperatingSystemsPrinciples.84–99. [4] MarekBaranowski,ShaoboHe,andZvonimirRakamarić.2018.VerifyingRustprogramswithSMACK.InAutomatedTechnologyfor VerificationandAnalysis:16thInternationalSymposium,ATVA2018,LosAngeles,CA,USA,October7-10,2018,Proceedings16.Springer, 528–535.
[5] JamesBrotherston,PaulBrunet,NikosGorogiannis,andMaxKanovich.2021.AcompositionaldeadlockdetectorforAndroidJava.In 202136thIEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering(ASE).IEEE,955–966. [6] MichaelBurke,PaulCarini,Jong-DeokChoi,andMichaelHind.1995.Flow-insensitiveinterproceduralaliasanalysisinthepresenceof pointers.InLanguagesandCompilersforParallelComputing:7thInternationalWorkshopIthaca,NY,USA,August8–10,1994Proceedings 7.Springer,234–250. [7] YuandaoCai,ChengfengYe,QingkaiShi,andCharlesZhang.2022. Peahen:Fastandprecisestaticdeadlockdetectionviacontext reduction.InProceedingsofthe30thACMJointEuropeanSoftwareEngineeringConferenceandSymposiumontheFoundationsofSoftware Engineering.784–796. [8] DawsonEnglerandKenAshcraft.2003.RacerX:Effective,staticdetectionofraceconditionsanddeadlocks.ACMSIGOPSoperating systemsreview37,5(2003),237–252. [9] JackJGarzella,MarekBaranowski,ShaoboHe,andZvonimirRakamarić.2020.Leveragingcompilerintermediaterepresentationfor multi-andcross-languageverification.InVerification,ModelChecking,andAbstractInterpretation:21stInternationalConference,VMCAI 2020,NewOrleans,LA,USA,January16–21,2020,Proceedings21.Springer,90–111.14 • YuZhang,KaiwenZhang,andGuanjunLiu [10] BenHardekopfandCalvinLin.2011.Flow-sensitivepointeranalysisformillionsoflinesofcode.InInternationalSymposiumonCode GenerationandOptimization(CGO2011).IEEE,289–298. [11] KlausHavelund.2000. UsingruntimeanalysistoguidemodelcheckingofJavaprograms.InSPINModelCheckingandSoftware Verification:7thInternationalSPINWorkshop,Stanford,CA,USA,August30-September1,2000.Proceedings7.Springer,245–264. [12] DavidHovemeyerandWilliamPugh.2004.Findingconcurrencybugsinjava.InProc.ofPODC,Vol.4. [13] ShuangHu,BaojianHua,andYangWang.2022.Comprehensiveness,AutomationandLifecycle:ANewPerspectiveforRustSecurity. In2022IEEE22ndInternationalConferenceonSoftwareQuality,ReliabilityandSecurity(QRS).IEEE,982–991. [14] PallaviJoshi,MayurNaik,KoushikSen,andDavidGay.2010.Aneffectivedynamicanalysisfordetectinggeneralizeddeadlocks.In ProceedingsoftheeighteenthACMSIGSOFTinternationalsymposiumonFoundationsofsoftwareengineering.327–336. [15] SteveKlabnikandCarolNichols.2023.TheRustProgrammingLanguage. https://doc.rust-lang.org/stable/book/ [16] DanielKroening,DanielPoetzl,PeterSchrammel,andBjörnWachter.2016.SoundstaticdeadlockanalysisforC/Pthreads.InProceedings ofthe31stIEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering.379–390. [17] ChrisLattnerandVikramAdve.2004.LLVM:Acompilationframeworkforlifelongprogramanalysis&transformation.InInternational symposiumoncodegenerationandoptimization,2004.CGO2004.IEEE,75–86. [18] OndrejLhotákandKwok-ChiangAndrewChung.2011. Points-toanalysiswithefficientstrongupdates.InProceedingsofthe38th annualACMSIGPLAN-SIGACTSymposiumonPrinciplesofProgrammingLanguages.3–16. [19] ZhuohuaLi,JinchengWang,MingshenSun,andJohnCSLui.2021.MirChecker:detectingbugsinRustprogramsviastaticanalysis.In Proceedingsofthe2021ACMSIGSACConferenceonComputerandCommunicationsSecurity.2183–2196. [20] ShanLu,SoyeonPark,EunsooSeo,andYuanyuanZhou.2008.Learningfrommistakes:acomprehensivestudyonrealworldconcurrency bugcharacteristics.InProceedingsofthe13thinternationalconferenceonArchitecturalsupportforprogramminglanguagesandoperating systems.329–339. [21] MayurNaik,Chang-SeoPark,KoushikSen,andDavidGay.2009.Effectivestaticdeadlockdetection.In2009IEEE31stInternational ConferenceonSoftwareEngineering.IEEE,386–396. [22] PengxiangNingandBoqinQin.2020.Stuck-me-not:AdeadlockdetectoronblockchainsoftwareinRust.ProcediaComputerScience 177(2020),599–604. [23] StackOverflow.2020. StackOverflowDeveloperSurvey. https://insights.stackoverflow.com/survey/2020#most-loved-dreaded-and- wanted [24] StackOverflow.2021. StackOverflowDeveloperSurvey. https://insights.stackoverflow.com/survey/2021#technology-most-loved- dreaded-and-wanted [25] StackOverflow.2022.StackOverflowDeveloperSurvey. https://survey.stackoverflow.co/2022#technology-most-loved-dreaded-and- wanted [26] BoqinQin.2020.lockbud. https://github.com/BurtonQin/lockbud [27] BoqinQin,YilunChen,ZemingYu,LinhaiSong,andYiyingZhang.2020.Understandingmemoryandthreadsafetypracticesandissues inreal-worldRustprograms.InProceedingsofthe41stACMSIGPLANConferenceonProgrammingLanguageDesignandImplementation. 763–779. [28] YuleiSuiandJinglingXue.2016. SVF:interproceduralstaticvalue-flowanalysisinLLVM.InProceedingsofthe25thinternational conferenceoncompilerconstruction.265–266. [29] TianTanandYueLi.2022. Tai-e:astaticanalysisframeworkforjavabyharnessingthebestdesignsofclassics. arXivpreprint arXiv:2208.00337(2022). [30] RajaVallée-Rai,PhongCo,EtienneGagnon,LaurieHendren,PatrickLam,andVijaySundaresan.2010.Soot:AJavabytecodeoptimization framework.InCASCONFirstDecadeHighImpactPapers.214–224. [31] AmyWilliams,WilliamThies,andMichaelDErnst.2005.StaticdeadlockdetectionforJavalibraries.InECOOP2005-Object-Oriented Programming:19thEuropeanConference,Glasgow,UK,July25-29,2005.Proceedings19.Springer,602–629.
[32] HongtaoYu,JinglingXue,WeiHuo,XiaobingFeng,andZhaoqingZhang.2010. Levelbylevel:makingflow-andcontext-sensitive pointeranalysisscalableformillionsoflinesofcode.InProceedingsofthe8thannualIEEE/ACMinternationalsymposiumonCode generationandoptimization.218–229. [33] ZemingYu,LinhaiSong,andYiyingZhang.2019.Fearlessconcurrency?understandingconcurrentprogrammingsafetyinreal-world rustsoftware.arXivpreprintarXiv:1902.01906(2019). [34] JinpengZhou,HanmeiYang,JohnLange,andTongpingLiu.2022.Deadlockpredictionviageneralizeddependency.InProceedingsof the31stACMSIGSOFTInternationalSymposiumonSoftwareTestingandAnalysis.455–466.
2401.01269 LLbezpeky: Leveraging Large Language Models for Vulnerability Detection NobleSajiMathews YelizavetaBrus YousraAafer UniversityofWaterloo,Canada UniversityofWaterloo,Canada UniversityofWaterloo,Canada noblesaji.mathews@uwaterloo.ca ybrus@uwaterloo.ca yousra.aafer@uwaterloo.ca MeiyappanNagappan ShaneMcIntosh UniversityofWaterloo,Canada UniversityofWaterloo,Canada mei.nagappan@uwaterloo.ca shane.mcintosh@uwaterloo.ca Abstract vulnerabilities[10],however,theapplicabilityofthesere- Despitethecontinuedresearchandprogressinbuildingse- mainslimitedinreal-worldsettingsduetothevastamount cure systems, Android applications continue to be ridden of training data required and an explicit focus on feature withvulnerabilities,necessitatingeffectivedetectionmeth- engineeringtoapproximatethecomplexityofthesystems ods.Currentstrategiesinvolvingstaticanddynamicanalysis beinganalyzed.WiththeadventofLLMs,hugebillionpa- toolscomewithlimitationslikeoverwhelmingnumberof rametermodelshavepushedtheboundariesofwhatwas false positives and limited scope of analysis which make thoughtachievablethroughanArtificiallyIntelligentsys- eitherdifficulttoadopt.Overthepastyears,machinelearn- tem. These are believed to acquire “embodied knowledge ing based approaches have been extensively explored for aboutsyntax,semantics,andontologyinherentinhuman vulnerability detection, but its real-world applicability is language”[8]andhavealsoshownsignificantpowerwhen constrainedbydatarequirementsandfeatureengineering dealingwithprogramminglanguagesduetotheirrelatively challenges.LargeLanguageModels(LLMs),withtheirvast simplerunderlyingGrammarandSemantics[6].Thisbrings parameters,haveshowntremendouspotentialinunderstand- aquestiontomind,HowgoodaretheseLanguageModels ingsemnaticsinhumanaswellasprogramminglanguages. atdetectingvulnerabilities?.Therehavebeenseveralrecent WediveintotheefficacyofLLMsfordetectingvulnerabili- explorations into the use of these large language models tiesinthecontextofAndroidsecurity.Wefocusonbuilding andimprovingtheirefficacyforvulnerabilitydetectionin anAI-drivenworkflowtoassistdevelopersinidentifying general,andthesehaveshownpromisingresults[9]. andrectifyingvulnerabilities.Ourexperimentsshowthat Currentworkintheliteraturehaslookedattheperfor- LLMsoutperformourexpectationsinfindingissueswithin mance of GPT-based models for the task of vulnerability applications correctly flagging insecure apps in 91.67% of detectionincode[4],Cheskovetal.reportittobenotvery casesintheGherabenchmark.Weuseinferencesfromour effectivebuttheyemployaverysimplisticapproach.Other experimentstowardsbuildingarobustandactionablevul- recentworkhasshownthatextendedpromptingandLLM- nerabilitydetectionsystemanddemonstrateitseffectiveness. driven methods complemented by other techniques have Ourexperimentsalsoshedlightonhowdifferentvarious yieldedmoreaccurateresultsthansimplepromptingforde- simpleconfigurationscanaffecttheTruePositive(TP)and tectingCWEspresentincode[2,11].Therehasalsobeen FalsePositive(FP)rates. a much more detailed exploration that looks into various aspectsofusingLLMsforsoftwaresecuritywithpromising results[14]. 1 INTRODUCTION We explore this area further in the context of Android Despiteadvancementsinbuildingsecuresystemsandexten- Security,attemptingtobuildanAI-enabledworkflowthat siveresearchinthearea,Androidapplicationsremainprone wouldenabledeveloperstodetectandaideinremediating toarangeofvulnerabilitiesandevenvulnerabilityreintro- vulnerabilitiesorevenaiddevelopersinwritingsecurecode ductionforfixedissues[1,5],creatingapressingdemand by acting as a pair programmer. Do note that fine-tuning foreffectivevulnerabilitydetectionmethodologies.Current models or training our own LLM is out of scope of this approaches to tackle this primarily revolve around static research,weprimarilyseektoexploreifandhowthelatent anddynamicanalysistools[10].However,theyhavetheir knowledgepresentintheseLLMscanbeusedforAndroid distinctlimitations,suchasvastfalsepositivesinthecase analysis. ofstaticanalysistools[3]andanoverwhelmingamountof Forthisexplorationintotheuseofnewandemergingtech- effortthatgoesintobuildingtheseframeworksandadapting nologiesitiscriticalwelayoutafewfundamentalquestions, themtonewervulnerabilitytypes. tobeginwith,anddirectourefforts.Weattempttoansweras In the past few years, there have also been numerous explorations into the use of machine learning to uncover 4202 beF 31 ]RC.sc[ 2v96210.1042:viXraCS858,ProjectProposal,LLbezpeky NobleSajiMathews,YelizavetaBrus,YousraAafer,MeiyappanNagappan,andShaneMcIntosh manyofthefollowingaspossiblebasedoninsightsgained case,thisknowledgebasewouldbespecifictoAndroidand fromthisexploration: couldincludeanyorallofthefollowing: • RQ1: Can LLMs detect Android vulnerabilities • Additionalcodethatneedstobefetchedfromalarge withbasicpromptingtechniques? codebase – Ifsohowgoodaretheyatthiscomparedtoexisting • Static/Codeanalysisresultsthatcouldproveuseful tools? tocommentaboutaspecificissue – WhatkindofvulnerabilitiesareLLMsgoodatun- • Documentationandadditionalinformationthatallows covering?Canthesesystemsdetectnewervulnera- theLLMtogarnerabetterunderstandingofthesystem bilitiesthatarelesswell-known? andtaskathand
– Dowerequirefine-tuningofeithertheModelorthe Weinitiallyfocusoureffortsonpromptengineeringto embeddingstoachievebetterresults? leveragetheLLM’sknowledgefortracingAndroidvulnera- • RQ2:WhatkindofInputwouldsuchasystem bilities.Weattempttocomparethedetectioncapabilityof needtobeabletounderstandanddiscoverissues theLLMwithotherstrategiesonthesamesetofapplications, inthecode? therebyprovidinginsightsonwhichapproachcanuncover – Howcouldwesupplythisadditionalcontext?What morevulnerabilitieswithfewerfalsepositives.Weusethese kindofKnowledgebaseswouldaidLLMsindiscov- insightstocontinuallyupdateandimprovetheinstructions eringcomplicatedbugs?(APIUsage,PermissionsIn- usedforpromptingoverthecourseoftheexperiments. volved,FrameworkEndpoints,Cross-languageand Inordertodothisweneedabenchmarkdatasetdesigned dynamiccomponents) totestAndroidSecurityAnalysistools.Forthisstudywetar- – Canexistingsolutions/statictoolsbeusedintan- getsmallerappsthatreplicateindividualvulnerabilitytypes. demwiththeseLLMs?orisitbettertoaddressonly However to understand our design objectives we need to some classes of vulnerabilities with each type of structureourpipelinesoitcanlogicallybeextendedtoreal approach? applications.Inthenextsectionwemoveontoacasestudy Tobuildoutsuchaworkflowthereare2keyelementswe attempting detection in an app that has multiple seeded need to address (We give a brief overview of these in the vulnerabilities. This involves integrating retrieval mecha- followingsections) nismsforobtainingadditionalcontextthatcansignificantly enhancethefeasibilityandperformanceofsuchsystems.Re- • Howdo wegetLLMs(particularly InstructTrained trievalmechanismarecriticalinreal-worldscenarioswhen Models)todowhatwewant?->PromptEngineering dealing with larger applications due to the limited token • Howdowesupplythecodeandadditionalcontextto windowofpresent-dayLLMs.Henceitisalsoimportantthat anLLM->RetrievalAugmentedGeneration wefocusonoptimisingthesizeoftheinputtothemodel whileensuringtheLLMhasenoughcontexttomakeasound 1.1 PROMPTENGINEERING decision. Prompt Engineering, a novel technique in artificial intel- ligence, is instrumental in enhancing the efficacy of lan- 2 METHODOLOGY guagemodelsforspecifictasks.Itinvolvesintricateprompt Inourstudy,experimentswereconductedwithGPT-4,using constructionthatoptimizesAIperformancebyelicitingim- theGherabenchmark1asthedataset.WeuseGPT4forour provedresponses[13].Onegroundbreakingstrategywithin experimentsasitisoneofthemostpowerfulavailableLLMs PromptEngineeringistheChain-of-ThoughtPromptingin- asoftoday.InourlimitedexperimentswithGPT3.5itstrug- troducedbyWeietal.(2022)[12].Thisapproachpushesthe gleswithfollowinginstructionsproperly.Furtherwealso boundaryofAI’sreasoningbyguidingthemodelthrougha setupourexperimentstoworkwithOpenLLMsbutasof sequenceofpromptsthatenrichandbuilduponeachother. writingthisreportopenmodelslikeLlama2performsignifi- ItallowsformoredepthinAIreasoning,particularlywhen cantlyworsecomparedtotheirpaidcounterparts.Hencewe pairedwithfew-shotprompting,provingusefulforcomplex stickwithoutdecisiontoemployGPT4despitethehigher tasksthatnecessitatemultiplestagesofreasoning. costsincurredforinferences.Throughouttheiterations,we 1.2 RETRIEVAL-AUGMENTEDGENERATION refinetheprompts,enhancingtheinformationprovidedto themodel,includingspecificdetailsaboutvulnerabilities.In RetrievalAugmentedGeneration(RAG)isanAIframework thefinalexperiment,only“AndroidManifest.xml”and“Main- designedtoenhancethequalityofresponsesgeneratedby Activity.java”filesiftheyexistintheanalyzedprojectwere largelanguagemodels(LLMs)[7].RAGallowsLLMstobuild presentedtothemodel.Wealsoprovidealistofadditional on a specialized body of knowledge to answer questions filespresentintheproject.Wealsoexperimentwithsum- more accurately. It’s like giving the model an open-book marizingthecontentoffilesandprovidingthatinformation exam, where it can browse through content in a book, as opposedtotryingtorememberfactsfrommemory.Inour 1GheraDatasetLLbezpeky:LeveragingLargeLanguageModelsforVulnerabilityDetection CS858,ProjectProposal,LLbezpeky Figure1.RoughArchitectureofExperiments tothemodelaswell.Wealsoimplementedfunctionalityto • Storage:Datastoragevulnerabilitiesinapps,includ- allow the model to request the content of specific files if ingexternal/internalstoragerisksandSQLinjection necessaryforfurthervulnerabilityidentification. threats. Gheraisabenchmarkrepositorythatpredominantlycat- • System:System-relatedvulnerabilitiesinapps,focus- alogsvulnerabilitiespreviouslyidentifiedinAndroidappli- ingonprivilegeescalationandinformationexposure. cations,asestablishedinexistingliterature.Thisrepository • Web:Webcomponentvulnerabilitiesinapps,suchas isdistinctivelyorganizedintobenchmarks,eachtargeting MitMattackrisksandcodeinjectioninWebViews. aspecificvulnerability.Thesebenchmarkscomprisethree types of applications: a benign application that possesses Duringtheexperimentationprocess,wefoundthatthe thevulnerability,amaliciousapplicationdesignedtoexploit Gherabenchmarkscontainedexplicitindicationsof"Benign" thisvulnerability,andasecureapplicationthatisimmune and"Secure"inboththefilepathsandthecontent.Forour
tosuchexploitation.Thebenchmarksarepractical,includ- experiments to be valid and to minimize data leakage to inginstructionsforbuildingandexecutingtheapplications, theLLMaboutthegroundtruth,wereplacedthesevalues therebyallowingfortheempiricalverificationofthevulner- with"llbezpekymyapp"and"llsezpekymyapp"respectively. abilitiesandtheircorrespondingexploits.Presently,Ghera’s However,weincludeourinsightsfromrunsinExperiments collectionexclusivelyconsistsof’lean’benchmarks,which 1and2thathadtheleakeddatatoseehowmuchitinfluences areminimalisticappsspecificallydesignedtoshowcasethe theresults.Interestinglyleakageofthewordsecureclearly vulnerabilitiesandtheirexploits,withoutincorporatingad- influencedtheoutcomesandhighlightedtheneedforclearly ditionalcomplexfunctionalities.Gheracontains69different sanitizingthedatafromsemanticnamesthatcanmislead issuesasofdatethatcanbecategorizedintothefollowing theLLM’sreasoning.Donotethatfoldernamesstillindicate types: thekindofvulnerabilitytosomeextentbutthisshouldn’t beacauseofconcerninanyofthesubsequentexperiments. Ouranalysisoftheseexperimentsandtheiroutcomeswill bedescribedinthefollowingsection. • Crypto:Vulnerabilitiesinappencryptionmethods, includingblockcipherissuesandexposedencryption 3 RESULTS keys. In this section, we discuss the various experiments con- • ICC:Risksinappcommunicationcomponents,such ducted,thethoughtprocessesbehindthem,andtheinsights asdynamicreceiversandintenthijacks. obtained. • Networking:Securityissuesinappnetworkcommu- nications,includingcertificatemishandlingandMitM attacksusceptibility. 3.1 Experiment1:BasicPromptingGPT4 • NonAPI:Vulnerabilitiesduetooutdatedlibrariesand For this experiment, we explore basic prompting without inheritedlibraryflawsinapps. providinganyinformationaboutthevulnerability.Wewish • Permission:Securityrisksfromunnecessaryorweak tofigureoutwhatkindofvulnerabilitiesifanyGPTcould apppermissionsleadingtopotentialunauthorizedac- detectwithoutanyexplanationabouttheissue.Resultsare cess. showninTable1.CS858,ProjectProposal,LLbezpeky NobleSajiMathews,YelizavetaBrus,YousraAafer,MeiyappanNagappan,andShaneMcIntosh LeakedData CleanedData 3.3 Experiment3:Requestingfilesasandwhen Insecure Secure Insecure Secure required Flaggedinsecure 54 21 58 56 Forpreviousexperimentsweweresendingalltheneeded Flaggedsecure 5 38 1 3 files,wecannotusesuchtechniquesforreal-worldapplica- Undecidable 1 0 1 0 tions.Hence,wemodifiedtheprompt,sothemodelasksto Overall 60 59 60 59 providemoreinformationifneeded.Resultsareshownin Table1.ResultsofExperiment1 Table3.WeinitiallyfocusontheAndroidManifest.xmland MainActivity.javafiles,recognizingthatwhilevulnerabilities oftenresidedeeperinthecode,thesefilescanprovidevital Itisinterestingtonotethatevenwithoutanydetailsabout startingpointsforanalysis.Fromhere,themodelcanrequest thevulnerabilityGPT4couldflagappsasinsecure.However, additionalfilesasneeded,therebyinitiatingtheRetrieval itseemsthatthemodeljusthasatendencytowardmark- AugmentedGenerationprocessinastructuredmanner. ingappsasinsecureascanbeseenwithsecureappsinthe Ourapproachincludesprovidingasummaryofallfiles cleaneddataset.Wenotethateventhough58outof60in- intheapplication,withtheexceptionoftheManifestand securearecorrectlyidentifiedwithrelevantsnippetsbeing theMainActivityfile.ThesummaryisgeneratedbytheLLM highlighted56ofthe59secureappsaremisclassified. itselfinapreprocessingstep.TheLLMisthenenabledtore- questthecontentofspecificfilesbasedonthesesummaries. 3.2 Experiment2:Providingasummaryofthe Thisselectiveprocessisparticularlyusefulinidentifyingvul- vulnerability nerabilitiesthatmightbeindicatedbyexportedcomponents Inthisexperiment,wecheckifthemodelcanverifythepres- orspecificimplementationsinthecode.Thismethodology enceofspecificvulnerabilitiesgivenaverybriefsummary. isaformofRetrievalAugmentedGenerationthoughata Wehypothesizethatspecifyinglimiteddetailsaboutissues verycoarsegranularity,aimingtoprobeitsimpactonthe wearelookingforwouldleadtocontextactivation2 and efficiencyandaccuracyofvulnerabilitydetection. enabletheLLMtouseitsexistingknowledgetowardsanaly- Theundecidablecaseinthisexperimentrequiresthebuild.gradle sis.Therefore,weextendedexperiment1byprovidingshort fileandthe"libs"folderandeventhoughthatiscorrectly informationaboutavulnerabilityandtheobtainedresults requestedwecurrentlyonlyincludecodewithin"app/src/- areshowninTable2.Thisprocessinvolvescreatingbrief main"andaddressthisinthefinalarchitecture.Wenoticed textualdescriptionsthatencapsulatehoweachvulnerability thatthemodeltendstoaskforallfileswhenimplementedin functionsorwhyanappissusceptibletoit.Thesesummaries asimplefashionsoweendedupcreatinganalternatechain arecrucialastheyofferaninitialunderstandingwithoutthe thatsummarizesallthefilesandincludesthissummarywith needfordetailed,app-specificdescriptions,whichmaynot thelistoffiles.Thisactuallyhadtheoppositeeffectwiththe bereadilyavailableinreal-worldscenarios.Suchsummaries model never requesting any file in most cases. We justify
mightbeakintoCommonWeaknessEnumeration(CWE) thelowerTPratesof60.5%duetohallucinationsmadeby descriptions,providingessentialinsightsataglance. themodelbasedonthesummaries.Anotherthingtonoteis thateventhoughtheimpactisnotsignificant,thegenerated LeakedData CleanedData reports lack clarity due to not having access to the exact Insecure Secure Insecure Secure implementationdetails.Howeverthereareclearlyefficiency Flaggedinsecure 53 6 55 34 gainstoanapproachlikethisthoughwhilesacrificingon Flaggedsecure 6 52 3 24 thequalityofthereportgenerated. Undecidable 1 1 2 1 Overall 60 59 60 59 Table2.ResultsofExperiment2 Weseethatwithjustashortsummaryofthevulnerability weareabletoimproveonthenumberofSecureappsflagged CleanedData asinsecurebyasignificantmargin.Anotherthingthatcan Insecure Secure benotedfromFigure2isthatExperiment2actuallyreduces Flaggedinsecure 57 43 thetimeconsumedbythemodeltoreturnaninferenceboth Flaggedsecure 2 15 onsecureandbenignapps.WenotesthanwehaveaTPrate Undecidable 1 1 of66.38%inthiscaseascomparedto51.26%intheprevious Overall 60 59 experiment(weconsiderundecidableasamisclassification). Table3.ResultsofExperiment3 2In-ContextLearningLLbezpeky:LeveragingLargeLanguageModelsforVulnerabilityDetection CS858,ProjectProposal,LLbezpeky Figure2.Timeconsumedforeachinference (cid:17) KeyTakeaways:Fromourexperimentswe seethatgivensufficientcontextGPT4can successfully identifyvulnerabilities. Sum- marizingclearlysavessignificantlyonthe costs, since the summaries can be used acrossscannersandisaone-timecost.At- temptsatreducingtheamountofinforma- tionstillneedworkandweneedacritique processtodealwiththemodelstendency tomarkapplicationsasinsecure. 4 LLBANALYZER Weusetheinsightsfromtheexperimentstoputtogether a python package called “LLB”, which can be invoked to Figure3.LLBPythonpackagerunningthroughCLI runthethepipelineonanytargetandroidapplication.The package is designed to facilitate the scanning of Android projectsforsecurityvulnerabilities.ItemploysaCommand Line Interface (CLI) as shown in Figure 3, leveraging the Typer framework to provide an intuitive user experience. Thispackageintegratesdistinctscanningmechanisms,of- feringflexibilityandcomprehensivenessinthevulnerability assessmentprocess. Thecorefunctionalityof"llb"isencapsulatedinthescan command. This command allows users to specify the tar- getAndroidapplicationdirectoryforanalysis.Inalignment withthepackage’sfocusonadaptability,itincorporatesmul- tiplescanneroptions,namely’GHERA’and’VULDROID’, alongwithan’all’optiontoexecuteallavailablescanners. Thesescannersaretailoredtoidentifydifferentcategories ofvulnerabilities,ensuringathoroughexaminationofthe targetapplication.Thescancommandalsosupportsanout- Figure4.ExamplefromcasestudyreportgeneratedbyLLB putdirectoryspecification,wheretheresultsofthescanare systematicallycompiledandstored.Thisfeatureiscritical formaintainingarecordofthevulnerabilitiesidentifiedand servesasareferenceforfurtheranalysisorremediationef- forts.AnexampleofapartofthereportgeneratedbyLLBis showninFigure4. post-scan analysis, allowing users to append expert com- Inadditiontoitsscanningcapabilities,"llb"includesthe mentsorinsightstothegeneratedreports.Thisfeatureun- expertcommand.Thiscommandisparticularlyusefulfor derscoresthepackage’sutilityincollaborativeenvironments, wheremultiplestakeholders,includingsecurityanalystsand developers,mightinteractwiththescanresults.CS858,ProjectProposal,LLbezpeky NobleSajiMathews,YelizavetaBrus,YousraAafer,MeiyappanNagappan,andShaneMcIntosh (cid:7) (cid:4) 5 Casestudy 1 String fileNm = "demo.txt"; 5.1 FlaggedVulnerability:Deepdive 2 // ... 3 Letuslookattheanalysisreportforcase“WebViewNoUser- 4 if (i != null && i.getStringExtra("fileName") != PermissionInformationExposure”inGhera.Inmobileapp null && !i.getStringExtra("fileName").equals("" ) security,it’scrucialtohandlesensitiveuserdatacarefully. 5 && i.getStringExtra("fileContent") != null && !i. Inthiscasewehaveasimplewebbrowserthatallowsweb getStringExtra("fileContent").equals("") 6 && i.getStringExtra("fileName").equals(fileNm)) { pagestoaccessthedevice’slocationviaaGPSTrackerAPI. 7 fileContent = i.getStringExtra("fileContent"); TheAPI’sgetLatitude()methodcanbetriggeredbyJavaScript 8 } else { 9 setResult(RESULT_CANCELED); onawebpagetofetchtheuser’slatitudewithoutaskingfor 10 return; theuser’sconsenteachtime.Thiscreatesavulnerability:a 11 } 12 maliciouswebpagecouldusethismethodtosecretlytracka 13 // ... user’slocation.Tomitigatethisrisk,appsmustnotonlyask 14 15 File file = new File(dir, fileNm); foruserpermissiontoaccesssensitivedatainitiallybutalso 16 try (FileWriter fileWriter = new FileWriter(file)) { maintainstrictcontroloveritsaccessduringuse,particularly 17 fileWriter.append(fileContent); 18 } catch (IOException e) { whendealingwithpotentiallyuntrustworthywebcontent. 19 Toast.makeText(getApplicationContext(), "IOError while writing", Toast.LENGTH_SHORT).show(); (cid:7) (cid:4) 20 setResult(RESULT_CANCELED); 1 @JavascriptInterface 21 e.printStackTrace();
2 public double getLatitude() { 22 } 3 if (location != null) { (cid:6)23 // ... (cid:5) 4 return location.getLatitude(); 5 } else { Listing2MisclassifiedexampleinGhera 6 // return dummy value 7 return 42.42; 8 } (cid:6)9 } (cid:5) commonpatternofvulnerabilitiesassociatedwithfilehan- Listing1InformationExposuresnippetflaggedbyLLBas dlingoperations,especiallywhentheyinvolveinputfrom indicatedintheGherabenchmark intentsorexternalsources.Whenitseescodethatinteracts withfilesystems,theremaybeanovercautiousapproachto flagpotentialsecurityrisks,suchaspathtraversal. InthiscaseLLBcorrectlyidentifiestheconcerningsnippet Theexpertfollow-upcorrectlyclarifiesthat,inthisspe- showninListing1.LLBreturnsthereasonasfollows:“The cificcase,thereisnodirectvulnerabilitypresentinthesnip- applicationisvulnerablebecauseitexposessensitiveinfor- petduetothefixedfilename.Usingtheexpertcommentwe mation(GPSlocation)totheJavaScriptcoderunninginthe areabletosettheanalyzerontherighttrackeveninother WebViewwithoutexplicitlyaskingtheuserforpermission... casesandgiveamorerelevantsuggestionifrequired. TheapplicationdoesrequesttheACCESS_FINE_LOCATION permission,butitdoesnotinformtheuserthattheirlocation 5.3 Vuldroid willbeaccessibletoanymaliciousJavaScriptcoderunningin Inordertoanalyzeafullapplicationwithmultipleknown theWebView.”andalsoprovidesasuggestedfixtoremediate vulnerabilitieswechosetoconductacasestudyonVuldroid. theissue. Vuldroid is a vulnerable Android application, which con- 5.2 Misclassification:Deepdive tainsonlysecurityissues.Theappconsistsofthefollowing vulnerabilities: Acommontrendwhichweobservedamongmisclassified sampleswasthattheyeitherwereflaggedforbadpatternsin • StealPasswordMagicLoginLinks(V1).Thisvulner- codewhichmightnotnecessarilybeconsideredvulnerable abilityallowsamaliciousapptointerceptpassword byanexpertinthecontextweareanalysing.Letuslookata resettokensormagicloginlinks.Thisispossiblebe- casewheretheLLMwasthrownoff.Theinitialclassification causetheappdoesn’tproperlyrestrictwhichactivities ofthecodeas"Vulnerable"duetolackofsanitizationchecks canhandledeeplinks,allowinganexternalapptocap- onthefilepathsseemstobebasedonamisunderstanding.In turethesesensitivetokens. theprovidedsnippet,thefilenamefileNmishard-codedto • WebviewXssviaExportedActivity(V2).Here,the "demo.txt",andthere’snoindicationthatitisinfluencedby vulnerability lies in an exported activity that loads externalinputsoruser-provideddata.Therefore,thespecific web content. Since the activity doesn’t validate the concernofpathtraversal,whereanattackercouldmanipu- URLsitloads,amaliciousappcanpassascript(like latefilepathstoaccessunauthorizeddirectories,doesnot aJavaScriptprompt)throughanintent,leadingtoa applyhere. cross-sitescripting(XSS)attack. It’slikelythattheLanguageModel(LLM)thatmadethe • WebviewXssviaDeepLink(V3).Similartothepre- initialclassificationmayhavebeen"thrownoff"duetothe viousone,thisexploitinvolvesXSSattacksbutthroughLLbezpeky:LeveragingLargeLanguageModelsforVulnerabilityDetection CS858,ProjectProposal,LLbezpeky deeplinks.TheappfailstovalidatedeeplinkURLs, optimized based on the specific functionality desired. We allowingtheinjectionofmaliciousscriptsviaquery exploreabasicpromptingstrategiesforLLBhoweveramore parametersintheseURLs. structuredpipelinewithmultipleagentscouldsignificantly • StealingFilesviaWebview(V4).Thisissuearises improvetheperformanceofLLBasananalyzer.Wealsowish because the app’s webview settings allow access to to highlight that each vulnerability we scan for is consid- localfileURLs(file:///).BycraftingaspecificURL,an eredasasinglescannerandthereisclearvaluetoexploring attackercanaccessandtransmitlocalfilestoaremote makingthisprocesslessresourceintensivebysharinginfor- server. mationbetweenscannersandchoosingwhichonestorun • StealingFilesviaFileprovider(V5).TheFileProvider basedonthetypeofcodebaseandartifactspresentwithinit. is misconfigured to expose all paths, and combined Wealsowishtocomparetheresultswiththoseobtained withanexportedactivity,itallowsotherappstoac- fromexistingapproachesinanempiricalstudy.Whileour cessandstealfiles. currentframeworkdoesnotintegratestaticanalysis,weac- • IntentSniffingBetweenTwoApplications(V6). knowledgeitspotentialvalueandareconsideringitsincor- This vulnerability occurs when two apps communi- porationinfutureiterations.Overarchingtheentiremethod- cateusingintentswithoutpropersecuritychecks.A ologyisaconstantfocusonimprovingsoftwarevulnerability maliciousappcanintercepttheseintentsandaccess identification,reducingfalsepositiverates,andstreamlining thetransmitteddata. theprocessofenhancingAndroidappsecurity.Webelieve • ReadingUserEmailviaBroadcasts(V7).Duetoan our study serves as a basis to attempts to merge state-of- exportedbroadcastreceiverintheapp,amaliciousapp the-artlanguagemodelswithstaticanalysis,potentiallyes- cantriggerthisreceiverandaccesstheuser’semail tablishing a more reliable, accurate, and efficient android information. vulnerabilitydetectionapproach.“Whatexistingtoolsand
• CommandExecutionviaMaliciousApp(V8).This codelevelanalysisresultscanbesuppliedtotheLLMtotake vulnerabilityallowsamaliciousapptoexecuteunau- amoreinformeddecision?”remainsanopenquestion. thorizedcommandsoroperationswithinthevulner- TheresultsoftheLLBcasestudyonvuldroidhighlights ableapp.Thedetailsofthisexploitweren’tfullyde- ashortcominginthecurrentimplementation.Thiscanbe scribedinyoursummary. easilyhandledbyindexingthecodeintoavectordatabase TheresultsofthecasestudyaredescribedinTable4.The andallowingvectorsearchandretrievaltoidentifyrelevant meaningofthesymbols: filesratherthanbuildingoutwardsfromasetoffiles.Further summarieswerenotincorporatedintheLLBpackagedue • C-vulnerabilitywasdetected totheirtendencytoinducehallucinationsinthereport.We • W-theprovidedinformationwasn’tenoughforthe plantoaddressthisbyincreasingourgranularitytoafile LLMtomakethedecision. levelandincorporatingcritiquemechanismslikehavebeen • X-vulnerabilitywasn’tdetected employedinrecentworksinotherdomainsthatattemptto leverageLLMs. V1 V2 V3 V4 V5 V6 V7 V8 W C C C W C C C Table4.Resultsofcasestudy 7 THREATSTOVALIDITY Promptengineering,whileapowerfultooltoguideLLMs, is also subject to limitations. The effectiveness of prompt WenotethatrunningLLBontheVuldroidsourcecode engineeringisheavilyreliantontheskillandexperienceof wecorrectlyidentify6ofthe8seededvulnerabilities.The2 theuser.Poorlydesignedpromptscanleadtosuboptimal whichcouldn’tbeclassifiedwerebecausetheanalyzercould results, as the model’s responses are only as good as the notfindtherelevantsnippetsforanalyzingbyrequesting questions posed. There’s also the risk of introducing bias files.Fortheremaining6casesthecorrectsnippetisiden- through prompts, which can skew the model’s focus and tifiedandavalidfixisalsosuggestedinmostcases.Thus potentiallyoverlookcertaintypesofvulnerabilities. theLLBreportdoesn’tjusttagvulnerableapplicationsbut A point which we highlighted earlier is about leaking actuallywalksyouthroughthereasoninginvolvedandhow semanticinformationabouttheclassoftheproblemdueto tofixtheflaggedissue. artifactsinthecode.Wereplacekeywordstocleanourdata buttherecouldbeimplicitdatathatleaksthisinformation 6 DICUSSIONANDFUTUREWORK totheLLMwhichwemightnothaveaccountedforinout ThefieldofleveragingLargeLanguageModels(LLMs)to analysis. Further capability of LLMs is very diverse with enhance Software Engineering tools and improve our un- someperformingdrasticallydifferentcomparedtoothers. derstandingoflargeprojectsisaveryactiveresearcharea. Whilewesetseedstoensurereplicabilityofourresultsthese Therearenumerousparametersandprocessesthatcanbe canvarydrasticallyovertime.CS858,ProjectProposal,LLbezpeky NobleSajiMathews,YelizavetaBrus,YousraAafer,MeiyappanNagappan,andShaneMcIntosh AnotherconcernisthedynamicnatureofbothAndroid References platformandcybersecuritythreats.AsAndroidcontinuously [1] SumayaAlmanee,ArdaÜnal,MathiasPayer,andJoshuaGarcia.2021. evolves,newtypesofvulnerabilitiesemerge,whichmaynot Tooquietinthelibrary:Anempiricalstudyofsecurityupdatesin beimmediatelyrecognizedbyanLLMtrainedonoutdated androidapps’nativecode.In2021IEEE/ACM43rdInternationalCon- ferenceonSoftwareEngineering(ICSE).IEEE,1347–1359. data.Similarly,cyberthreatsareconstantlyevolving,with [2] OwuraAsare.2023.SecurityEvaluationsofGitHub’sCopilot.Master’s attackersdevisingnewmethodstoexploitsystems.Thisre- thesis.UniversityofWaterloo. quirescontinuousupdatesandretrainingoftheLLM,which [3] WangChao,LiQun,WangXiaoHu,RenTianYu,DongJiaHan,Guo canberesource-intensive. GuangXin,andShiEnJie.2020.Anandroidapplicationvulnerability miningmethodbasedonstaticanddynamicanalysis.In2020IEEE 5thInformationTechnologyandMechatronicsEngineeringConference (ITOEC).IEEE,599–603. 8 CONCLUSION [4] AntonCheshkov,PavelZadorozhny,andRodionLevichev.2023.Eval- uationofChatGPTModelforVulnerabilityDetection.arXivpreprint Inourresearch,weexploretheutilizationofLargeLanguage arXiv:2304.07232(2023). Models (LLMs) for detecting Android vulnerabilities, We [5] JunGao,LiLi,PingfanKong,TegawendéFBissyandé,andJacques successfully demonstrate the power of LLMs for Android Klein.2019.Understandingtheevolutionofandroidappvulnerabilities. Vulnerabilitydetectionandremediation.Ourexperimentsus- IEEETransactionsonReliability70,1(2019),212–230. ingPromptEngineeringontheGheraVulnerabilityDataset [6] XinyiHou,YanjieZhao,YueLiu,ZhouYang,KailongWang,LiLi, XiapuLuo,DavidLo,JohnGrundy,andHaoyuWang.2023. Large showpromisingresultsandbringupnewandinteresting LanguageModelsforSoftwareEngineering:ASystematicLiterature directions which can be explored towards improving the Review.arXivpreprintarXiv:2308.10620(2023). efficacyofsuchsystems.Furtherweutilizetheresultsand [7] PatrickLewis,EthanPerez,AleksandraPiktus,FabioPetroni,Vladimir insightsfromourexperimentstocreateahighlyconfigurable Karpukhin,NamanGoyal,HeinrichKüttler,MikeLewis,Wen-tau
pythonpackagethatallowseasymodificationoftheLLMbe- Yih,TimRocktäschel,etal.2020. Retrieval-augmentedgeneration forknowledge-intensivenlptasks. AdvancesinNeuralInformation ingusedasthereasoningengineandalsosupportsextension ProcessingSystems33(2020),9459–9474. tomulti-agentarchitectures.Intermsofthequestionsweset [8] ChristopherDManning.2022. Humanlanguageunderstanding& outtoansweritisclearthatLLMsareincrediblypowerful reasoning.Daedalus151,2(2022),127–138. toolsthatcanrevolutionizeSoftwareEngineeringtoolsas [9] DavidNoever.2023.CanLargeLanguageModelsFindAndFixVul- weknowthem,butitalsoclearthattheydonotworkmagic nerableSoftware?arXivpreprintarXiv:2308.10345(2023). [10] JanakaSenanayake,HarshaKalutarage,MhdOmarAl-Kadri,Andrei outoftheboxandclearlyrequireworkintermsofdrafting Petrovski,andLucaPiras.2023. Androidsourcecodevulnerability andstructuringabetteranalysispipelinearchitectureand detection:asystematicliteraturereview.Comput.Surveys55,9(2023), optimisingthecontextavailabletotheLLM. 1–37. [11] Jin Wang, Zishan Huang, Hengli Liu, Nianyi Yang, and Yinhao Xiao.2023.DefectHunter:ANovelLLM-DrivenBoosted-Conformer- based Code Vulnerability Detection Mechanism. arXiv preprint 9 ACKNOWLEDGEMENTS arXiv:2309.15324(2023). ThisprojectreportisapartofthecourseCS858attheUni- [12] JasonWei,XuezhiWang,DaleSchuurmans,MaartenBosma,FeiXia, EdChi,QuocVLe,DennyZhou,etal.2022.Chain-of-thoughtprompt- versity of Waterloo. I express my sincere gratitude to my ingelicitsreasoninginlargelanguagemodels. AdvancesinNeural courseinstructor,YousraAafer,forherinvaluableguidance InformationProcessingSystems35(2022),24824–24837. andsupportthroughoutthisproject.Herexpertiseandin- [13] JulesWhite,QuchenFu,SamHays,MichaelSandborn,CarlosOlea, sightshavebeenfundamentalinshapingtheresearchand HenryGilbert,AshrafElnashar,JesseSpencer-Smith,andDouglasC itsoutcomes. Schmidt.2023.Apromptpatterncatalogtoenhancepromptengineer- ingwithchatgpt.arXivpreprintarXiv:2302.11382(2023). Iwouldalsoliketoextendmythankstomysupervisors, [14] ChenyuanZhang,HaoLiu,JiutianZeng,KejingYang,YuhongLi,and MeiyappanNagappanandShaneMcIntosh.Theirinputand HuiLi.2023. Prompt-EnhancedSoftwareVulnerabilityDetection feedback have been instrumental in refining the research UsingChatGPT.arXivpreprintarXiv:2308.12697(2023). methodologies and enhancing the overall quality of this work.Theirperspectivesandsuggestionshavegreatlycon- tributedtothedepthandrigoroftheresearch. Iamthankfulforthecollaborativeenvironmentprovided bytheUniversityofWaterloo,whichhasbeenconducive toacademicexplorationandinnovation.Theresourcesand supportofferedbytheuniversityhaveplayedacrucialrole inthesuccessfulcompletionofthisproject. Lastly,Iappreciatetheeffortsofallthosewhohavedi- rectlyorindirectlycontributedtothisresearch,including mypeersfortheirconstructivecriticismsandtheuniversity stafffortheiradministrativesupport.
2401.01571 CODEFUSE-QUERY: A DATA-CENTRIC STATIC CODE ANALYSIS SYSTEM FOR LARGE-SCALE ORGANIZATIONS APREPRINT XiaohengXie,GangFan*,XiaojunLin,AngZhou,ShijieLi,XunjinZheng,YinanLiang,YuZhang, NaYu,HaokunLi,XinyuChen,YingzhuangChen,YiZhen,DejunDong,XianjinFu, JinzhouSu,FuxiongPan,PengshuaiLuo,YouzhengFeng,RuoxiangHu,JingFan, JinguoZhou,XiaoXiao,PengDi AntGroup,China ABSTRACT Inthedomainoflarge-scalesoftwaredevelopment,thedemandsfordynamicandmultifacetedstatic codeanalysisexceedthecapabilitiesoftraditionaltools.Tobridgethisgap,wepresentCODEFUSE- QUERY,asystemthatredefinesstaticcodeanalysisthroughthefusionofDomainOptimizedSystem DesignandLogicOrientedComputationDesign. CODEFUSE-QUERY reimagines code analysis as a data computation task, support scanning over 10 billion lines of code daily and more than 300 different tasks. It optimizes resource utilization, prioritizesdatareusability,appliesincrementalcodeextraction,andintroducestaskstypesspecially for Code Change, underscoring its domain-optimized design. The system’s logic-oriented facet employs Datalog, utilizing a unique two-tiered schema, COREF, to convert source code into data facts.ThroughGO¨DEL,adistinctivelanguage,CODEFUSE-QUERYenablesformulationofcomplex tasksaslogicalexpressions,harnessingDatalog’sdeclarativeprowess. Thispaperprovidesempiricalevidenceof CODEFUSE-QUERY’stransformativeapproach,demon- stratingitsrobustness,scalability,andefficiency.Wealsohighlightitsreal-worldimpactanddiverse applications,emphasizingitspotentialtoreshapethelandscapeofstaticcodeanalysisinthecontext of large-scale software development.Furthermore, in the spirit of collaboration and advancing the field,ourprojectisopen-sourcedandtherepositoryisavailableforpublicaccess2. 1 Introduction Intherealmoflarge-scalesoftwaredevelopmentwithinlargeorganizations,,there’saburgeoningneedforadaptable andscalablestaticcodeanalysissystems[23]. Traditionalstaticanalysistools,suchasClangStaticAnalyzer(CSA) andPMD,haveservedwellincheckingprogrammingrulesandstyleissues[1,7]. Theirspecificscopeoftenlimits bothflexibilityandscalability,makingthemlessequippedtocatertothediverseandever-changingdemandsofmodern softwaredevelopmentinsuchorganizations. In large organizations, the requirements for static code analysis can greatly diversify. Beyond the traditional use of finding bugs, needs may extend to multi-language code metric analysis for R&D efficiency, compliance algorithm monitoring for legal adherence, and extracting code features for constructing attack denominators during network attackanddefenseexercises. Thesedistinctneeds,whencoupledwiththecomputationalresourceconstraintstypical inlargeorganizations,poseasignificantchallenge. Toaddressthis,wehavedesignedandbuilt CODEFUSE-QUERY withinanorganizationthathostsovertenthousand developers. CODEFUSE-QUERY pioneers a data-centric approach to traditional code analysis, transforming it into a data computation task. CODEFUSE-QUERY already supports over three hundred unique static analysis tasks and ∗Correspondingauthor:fangang@antgroup.com 2https://github.com/codefuse-ai/CodeFuse-Query 4202 naJ 3 ]ES.sc[ 1v17510.1042:viXraCODEFUSE-QUERY: ScalableStaticCodeAnalysis is used in more than thirty different scenarios. Moreover, it supports nine different programming and configuration languages. Impressively, itmanagesaworkloadofapproximately300,0003 tasksperdayandscansovertenbillion linesofcodedaily. The success of CODEFUSE-QUERY derives from two foundational design principles: Domain Optimized System Design and Logic Oriented Computation Design. Under the principle of Domain Optimized System Design, CODEFUSE-QUERY tailors a solution precisely attuned to the requirements of large-scale static code analysis. The systemintroducesdedicatedtasktypesspecificallydesignedfor”CodeChange”analysis,acknowledgingtheconstant, incrementalevolutionofcodebases. Alongside,itincorporatesaresource-awareschedulingapproach,efficientlyuti- lizing computational resources and prioritizing data reusability in response to the computationally intensive nature of static code analysis tasks. Furthermore, CODEFUSE-QUERY aligns with the incremental nature of software de- velopment by implementing an incremental code extraction strategy. This strategy adeptly manages the minute, yet constant changes that occur in large, evolving codebases, ensuring accurate, up-to-date analysis without redundant computational expenditure. These domain-specific design choices render CODEFUSE-QUERY a high-performance, easilyextendableplatformwithaminimallearningcurve. IntermsofLogicOrientedComputationDesign, CODEFUSE-QUERY introducesaninnovativemethodindatacom- putation, adopting Datalog as the principal computational model. Central to this approach is the implementation of a two-tiered schema, COREF, a two-tiered schema designed to transmute source code into data facts. Building on thisfoundation,wehavedevisedadistinctivelanguage, GO¨DEL,employsthedeclarativepowerintrinsictoDatalog, providing a user-oriented interface for formulating complex code analysis tasks as logical expressions. The practi- cal proficiency of CODEFUSE-QUERY is empirically confirmed through its successful application to nine different programmingandconfigurationlanguages. CODEFUSE-QUERY marks a paradigm shift in static analysis, meeting domain-specific requirements while accom-
modating large-scale software development dynamics. We argue that CODEFUSE-QUERY, with its fresh approach to static code analysis, paves a promising path for managing the escalating complexity and diversity of large-scale softwaredevelopment. Thepaper’sprimarycontributionsare: 1. InnovativeComputationApproachwithCODEFUSE-QUERY: ThepaperpresentsCODEFUSE-QUERY,asys- temthattransformscomputationapproachwithitsdomain-optimizedandlogic-orienteddesign. UsingDatalog, CODEFUSE-QUERY transforms source code into data facts through a two-tiered schema, COREF, and a user- friendlylanguage,GO¨DEL,whichsimplifiescomplextasks. 2. Empirical Evidence for CODEFUSE-QUERY’s Design: Our design of CODEFUSE-QUERY is supported by empiricalevidence. WepresenttestsandevaluationsthatprovideinsightsintoCODEFUSE-QUERY’srobustness, scalability,andefficiency,validatingitseffectivenessinlarge-scalestaticanalysis. 3. Real-worldImpactandApplicationsof CODEFUSE-QUERY: CODEFUSE-QUERY haspracticalapplications. Thepaperpresentsusecases,suchasgeneratingBusinessIntelligence(BI)fromcodedataandanalyzingtraining dataforlargelanguagemodels(LLMs). ItalsohighlightsCODEFUSE-QUERY’sintegrationacrossninedifferent programmingandconfigurationlanguages. Inthesubsequentsectionsofthispaper,weexploreCODEFUSE-QUERY’sdesignphilosophyandarchitectureindepth, discussing our technical decisions, highlighting its strengths, addressing its limitations, and presenting a rigorous empiricalperformanceassessment. 2 BackgroundandChallenge The practice of CODEFUSE-QUERY, our dedicated static analysis system, grapples with a myriad of challenges in real-worldscenariosandapplications. Asasignificantcontributorinthisfield,wetackleallissuesencompassedunderstaticanalysis. Thesetasksdemon- strate considerable diversity in their nature and requirements. For instance, tasks can range from ad-hoc requests foraBIreportsummarizingthecurrentstatusofallsoftwarerepositories,tostringentcodegatechecksforprogram rules and standards, to comprehensive security vulnerability assessments across a program and its dependencies, to fully automated, incremental code change impact analyses that necessitate absolute precision. This wide-ranging nature of tasks, each with its unique domain, performance requirement, and automation level, leads us to our first challenge—ProblemComplexityandDynamism(ComplexityChallenge). 3Allsystemmetricsarescaledbyarandomfactorrangingfrom0.1to10, thuspreservinggeneralitywithoutcompromising confidentiality. 2CODEFUSE-QUERY: ScalableStaticCodeAnalysis Oursecondchallenge,DiversityofAnalysisTargets(DiversityChallenge),arisesfromthebroadspectrumofprod- ucts in our organization, each encompassing unique programs such as backend and frontend components, mobile clients, and mini apps. This diversity also pertains to the multitude of programming languages and corresponding frameworks in use, each often augmented with specific libraries to enhance development and code maintainability. We encounter various frontend and backend frameworks, coupled with diverse middleware solutions for tasks like messaging, caching, or database interaction. The core challenge is the development of an analysis platform capa- ble of seamlessly handling this extensive heterogeneity, providing accurate insights irrespective of the language or frameworkutilized. The third challenge, Scalability and Speed (Efficiency Challenge), emerges from the tremendous volume of pre- existing code and the fast-paced generation of new code. For example, within our organization, we have gathered billionsoflinesofcode,withnewadditionsexceeding100klinesdaily.AsCODEFUSE-QUERYistheplatformtasked withanalyzingasignificantportionofthisvastcodebase,itisessentialthatoursystemandproceduresaredesigned forefficientscalability. Thisincludesthecapacitynotonlytomanagebillionsoflinesofcodebutalsotoprocessand incorporatenewcodeswiftly,thusensuringouranalysisstaysupdatedwiththelatestdevelopments. The fourth challenge, Resource Constraints and Variability (Resource Challenge), arises from the high compu- tational demands of static analysis due to path explosion. Deep analyses ideally require unlimited resources for accuracy, yetreal-worldconstraintsexist. Staticanalysisprojectsoftencompetewithotherhigh-valueprojects, em- phasizing return on investment (ROI). In large organizations like ours, resources are centrally managed and shared amongapplicationswithdiversepriorities, requiringastaticanalysisplatformthatperformsconsistentlydespitere- sourcefluctuations. Weoffervariouscomputationoptions,eachwithuniqueadvantagesandlimitations,complicating resourceselection. Thechallengeinvolvesoptimizingtheuseoftheseresourcesforthestaticanalysisplatformamidst resourceconstraintsandvariability. MaintainingastaticanalysisplatformlikeCODEFUSE-QUERYischallengingascodebasecomplexitygrows,empha- sizingtheneedforEvolutionaryMaintenance(MaintenanceChallenge). Theplatformmustbeeasilyupdatable, extendable, and debuggable, while accommodating changes in software paradigms, new languages, and evolving codingpractices. UpdatingCODEFUSE-QUERYfornewlanguagesyntax,expandingitsalgorithmsfornewprogram- mingconstructs,orrectifyingbugsareallpartofthechallenge. Limitedresourcesforinternalplatforms,prioritizing outward-facingproducts,compoundthischallenge,necessitatingan’easytomaintain’design. Withoutcarefulman- agement,technicaldebtcanaccumulate[38],hamperingplatformevolutionandmaintenance.TheChallengetherefore
spanstechnical,operational,andstrategicresourceallocationaspects,allcriticalformanagingalarge-scalestaticcode analysisplatformefficiently. 3 DomainOptimizedSystemDesign Theoverarchingdesigngoalof CODEFUSE-QUERY istoestablishalarge-scalecodeanalysisplatformthatishigh- performance,highlyreusable,easytoextend,andhasalowlearningcurve. Inthefollowingsections,wewilllayout ourdesignprinciplesinmoredetail,describethefeaturesofCODEFUSE-QUERY,anddiscussoursystemarchitecture. 3.1 DesignPrinciples PrincipleofDomain-IntegratedDesign(PICD):Thisprincipleemphasizesincorporatingdomain-specificfeatures intosystemdesign,especiallywhentacklingtheinherentComplexityandDiversityChallenge.Insteadofauniversal approach, PICD focuses on the unique characteristics and needs of code analysis tasks. Crucially, PICD recognizes the key role of Code Change in system analysis and partitions the code analysis process into two steps—Extraction andQuery,balancingdetailrichnessandstorageefficiency.ByfollowingthePICD,wedeviseasystemspecializedfor codeanalysistasks,enhancingefficiencyandeffectiveness. Thisprincipleensuresthesystemispreparedtoaddress codeanalysiscomplexitiesfromthedesignphase. Principle of Maximal Data Reusability (PMDR): Our system is meticulously engineered to optimize data reuse across the entire processing chain—from the initiation of user-created queries to the culmination of query results, encompassingallintermediateoutputs,directlyaddressingtheEfficiencyChallenge. TheProxylayerreusesresults through caching, the Data Sentinel employs data from the Facts DB to transform full extractions into incremental ones,andtheAnalysisNodeacceleratesrepeatedanalysesofthesamerepositorybyutilizingin-memorydata. Con- sequently,thisapproachsignificantlyspeedsuptheanalysisanddataextractionprocessesforcodechanges. PrincipleofComputationOptimization(PCO):Consideringthecomputationaldemandsoflarge-scalecodeanal- ysis and the performance sensitivity of various code analysis tasks, our system addresses both the Complexity and EfficiencyChallenges. Theimplementationsfeaturestrategiessuchasanextract-querydesignandtheuseoffixed- 3CODEFUSE-QUERY: ScalableStaticCodeAnalysis point computation to boost efficiency. Additionally, the framework is designed to reduce system overhead during queryexecution. Principle of Resilience Through Redundancy (PRTR): Our system acknowledges failure as inherent in complex systems,particularlythosedependentonmultiplecomponentsandservices,addressingtheMaintenanceChallenge. Asopposedtotreatingfailureasananomaly,weconsideritthenorm,buildingasystemthatanticipatesandhandles potential failures, ensuring resilience and uninterrupted operation. The PRTR directs the development of proactive systemfailurestrategies,suchasinternalretriesintheexecutor,reschedulingtaskstostrongerresources,anddeploying redundanciestomitigatesinglepointsoffailure. PrincipleofDynamicResourceAllocation(PDRA):Oursystemisarchitectedtoadeptlyadjusttochangingwork- loads,whichcouldcauseloadimbalancesacrosssystemcomponents,directlyaddressingtheResourceandEfficiency Challenges. PDRAemphasizesdynamicallocationofcomputationalresourcestohigh-loadtasks,requiringefficient component decoupling and utilization of complex resource distributions. This principle includes separating extrac- tionfromquerying,anddecouplingreadoperationsfromwriteones,ensuringoptimalelasticityandresourceusage, allowingthesystemtoadapttoworkloadvariationsandmaintainhighperformance. ByemployingthePrincipleof DynamicResourceAllocation, oursystemcanadjusttofluctuatingworkloadswhileensuringefficientresourceuse, maintainingsteadyperformance,andpreventingresourcewastage. 3.2 SystemInterface CODEFUSE-QUERY leverages the query language GO¨DEL (Definition 3.2), empowering developers to articulate in- tricate code analysis needs. The query language includes operators like pattern matching, code structure, and code similarity,enablingpreciseinformationretrievalcriteriaspecification. OursystemoffersoperationssegmentedintoExtraction,Analysis,andScanningfunctionalities. Theextract()opera- tionassemblesthecodedatamodel,withtheoutputknownasthefactsDB,formattedasCOREF(Definition3.1).The analysis()operationperformsadvancedcodedataanalysisbasedontheuser-inputquery(Section3.2.1),thespecified codefileorrepositoryURL,anditsversionidentifier. Fornewprojects,Analysisoperationsstartwithafullextrac- tion to construct the facts DB. The scan() operations are designed to detect and extract code features and structures matchingdefinedpatterns,applicabletosinglecodefilesorentirerepositories. WhilebuildingthefactsDB, CODEFUSE-QUERY checksexistingfactsDBsnapshotsforamatchingversion. Itin- crementallyconstructsmodelpartsbycomparingfiledifferencesandcodedependenciesagainstabaselinesnapshot. Eachdifferentversionextractioncreatesanewsnapshot. Differentcoderepositoryversionscanbeextractedconcur- rently. Withinthesamerepositoryforthesamedataversion,onlyoneextractiontaskwillexist,ensuredbydatabase row-levellocking. 3.2.1 Terminology We introduce a methodology that partitions static analysis into two separate processes: Extraction and Querying. The central concept of ”Extraction Result” is defined as the vital information extracted from the source code and subsequently transformed into a structured data model. To facilitate this, we have developed a new programming
language, GO¨DEL(Definition 3.2). This language, recognized for its simplicity and accessibility, allows developers, eventhoseunfamiliarwithstaticanalysis,toquicklygraspitsusage. ScriptswritteninGO¨DEL,knownas”Queries”, equipuserswithapowerfultoolforconductingcomprehensiveanalysisofthemodeleddata. Definition3.1(COREF)Acomprehensiverepresentationschemeforcodedata,employingatwo-tiereddatamodel- ingapproach.Thismethodologyaccuratelycapturesthecomplexstructureandsemanticsofcode,facilitatingeffective analysis(Section4.1). Definition 3.2 (GO¨DEL) A Domain-Specific Language (DSL) tailored for defining and executing code analysis. GO¨DEL also serves as a foundational computational engine. Built on the principles of Datalog, it adheres to the samecomputationalmodelasatypicalDatalogprogram(Section4.3). 3.2.2 AnalysisTaskStructure Oursystemintegratesvarioustasktypesforcodeanalysis,eachtailoredtospecificneedsandcontexts. TheFullRepositoryAnalysis(FRA)isthefirsttype,involvingathoroughexaminationoftheentirecoderepository asasingleunit. Whenbuildingthecodedatabase,weconsiderfileinterconnections. FRAformsthebasisforallother tasksandisinvaluableforlarge-scalerepositoryanalysistoextractmetricsorperformadhocscans. 4CODEFUSE-QUERY: ScalableStaticCodeAnalysis Codechangesareintegraltosoftwaredevelopment,impactingareaslikesecurity,riskmanagement,andproductivity. Assuch,oursystemaccommodatesthisaspectwithtwotasktypesdedicatedtocodechangelevelanalysis,enhancing systemefficiencyandmeetingcertaintimeconstraints. ThefirstisIncrementalFullRepositoryAnalysis(IFRA). We handle the incremental phase during the database creation, generating a corresponding database incrementally whenacodechangeoccurs. Thisapproachenablesfaster,moreefficientfulldatabaseanalysis. ThesecondisDelta CodeAnalysis(DCA),whichtargetsonlythealteredfilesinsteadofthewholerepository. Forexample,wheniden- tifyingfunctionsimpactedbyacodechange,DCAanalyzesallfunctionsinthemodifiedfiles,whileIFRAconsiders allfunctionsintherepository. Proxy Proxy Proxy Access Layer Cache Cache Cache Coordinator Analysis Cluster DataSentinel Layer Coordinator Controller Analysis Extractor Worker Node Node Layer CoQuery-Runtime CoQuery-Runtime Storage Layer Table RDBMS Object Storage Figure1: TheArchitectureofCODEFUSE-QUERY 3.3 SystemArchitecture CODEFUSE-QUERY utilizesaservice-orientedarchitecture, achievingcleandecouplingamongsystemcomponents. Figure1showsthatCODEFUSE-QUERYiscomposedoffourlayers: theaccesslayer,coordinatorlayer,workerlayer, andstoragelayer. The Access layer includes stateless proxies acting as user endpoints. These proxies operate concurrently to handle clientrequests, distributethemtotherightprocessingunits, andconsolidatepartialanalysisresultsbeforereturning themtoclients. Theseproxiesalsocachemetadataandanalysisresults. Themetadatavalidatestasklegitimacy,such asverifyingcodefileexistence. Cachingpartialanalysisresultspreventsredundantanalyses,particularlybeneficialin dailyCI/CDgatekeepingtasks. Thisapproachpresentsseveraladvantages. Firstly,itenablesearlyrejectionoffailed verificationrequests,reducingloadonothersystemcomponents. Secondly,itlessensoverheadfromrepeatedanalysis and code modeling. Thirdly, it cuts down the number of routing hops for requests, decreasing request processing latency. TheCoordinatorlayermanagessystemstatus,maintainsmetadata,andoverseestaskprocessing. Thislayerhouses threecomponents,eachwithspecificresponsibilities: 1. AnalysisCoordinator:ThiscomponentsupervisesAnalysisnodestatus,loadbalancing,tasksplittingandaggre- gation, andtaskexecutionstatus. Itoptimizestaskdistributionacrossnodesandmonitorsprogress. Beforetask assignment, the scheduler scrutinizes the query, traces its execution plan to include dependent data, and checks forunchangedfiles. Ifnounchangedfilesarepresent,DCA,IFRA,andFRAresultswillalign. Usingthisinfor- mation,theschedulerdecidesbasedonthequery’sunchangedfiledependencies. Fordependenciesonunchanged files,theschedulercantransformanFRAtaskintoanIFRAtask,usinganalyzeddataandpreventingredundant processing. Simultaneously,thesystemestimatescomputationalcostsbasedontheprogramminglanguage,code lines,andrepositorysize. Thisestimationoptimizeslarge-scaletaskresourceallocation,enhancingperformance. 2. DataSentinel: ThiscomponentmanagesallcodefactsDBmetadata,suchasversions,coderepositoryaddresses, andcommitIDs. Itschedulescodemodeling,codefeatureextraction,andmanagestaskstatus. Italsoensuresbal- 5CODEFUSE-QUERY: ScalableStaticCodeAnalysis anceddatadistributionacrossclusters,especiallyforhotdata,andsynchronizesExtractornodework. Oursystem efficientlyhandlescodechanges. ItperformsafullCOREFconstructionfornewrepositories,andincrementally updates the database for subsequent code modifications. This approach lightens extraction node loads, reduces extractiontime,andminimizesdiskI/O. 3. ClusterMonitor:Thiscomponentmonitorsclusterstatus,trackingmetricslikememoryandCPUusage.Itscales clusters dynamically during high workloads. Each component has multiple instances considered equal, and the Cluster Monitor consistently checks their status. Replicas take over failed components. These components are vitalfortaskmanagement,faulttolerance,loadbalancing,andscalability.
Worker layer is responsible for executing the actual computational tasks. The worker nodes are stateless, meaning they retrieve read-only copies of the data to perform tasks and do not require any dependencies. This approach offers several benefits, such as being the ability to elastically scale any high-load nodes, typically those handling computationallyintensivetasks. ItalsoenablesresourceisolationtomeetthevaryingQoSrequirementsofdifferent tasks. We have two types of worker nodes: extractor nodes and analysis nodes. The implementation of both types ofworkernodesisconsistent,astheypossessthecapabilitiesforbothmodelingandanalysis. Thisdesignallowsfor seamlesstransformationofextractornodesintoanalysisnodes. Storage layer in CODEFUSE-QUERY is responsible for persisting system status, metadata, and code facts DB. The systemutilizestheRDBMStostorethestatusandmetadataofvariouscomponents. Consideringthestorageformat forourcodefactsdb(SQLITE[26])andthelargevolumeofdatainvolved,weemployanobjectstorageservice. For efficientcodedataanalysisinCODEFUSE-QUERY,weplaceparticularemphasisonreal-timeanalysis. DataSentinel disperseshotdatatoworkernodes,reducingtheneedforfrequentreadsfromtheobjectstorageservice. Additionally, wedeployanalysisandcomputationtasksdirectlyonthenodesstoringthedata,employingaData-DrivenComputing approachasmuchaspossible. CodeFuse-Query Runtime Godel Task Filter Driver Executor Code Godel Scan Files Query Web Interface/CLI CPU0 CPU1 Sort Query analyzer CPU2 CPU3 Fact And Optimizer Extractor Language Facts Task Scheduler Configuration Facts Storage Service CodeFuse-Query Runtime Code Change Facts Cluster Figure2: CODEFUSE-QUERYworkerlayer,whichexecutesqueriesonadistributedclusterofVMs 3.4 TheCODEFUSE-QUERYRuntime The CODEFUSE-QUERY Runtime component, shown in Figure 2, manages query execution, code modeling, and featureextraction. ApplicationssenttotheRuntimearedenotedasjobs,eachsubdividedintostages. Astagesignifies ajobfragment,likeareadingstageforreadingfilesordataexchanges,endingindataexchangeorfinalresult. Stages in CODEFUSE-QUERY Runtimeareblock-oriented, withthenextstagestartingaftertheprecedingstageconcludes, allowingfaulttoleranceviastagereplaying. TheRuntimesupportsmultipleconcurrentjobs. The Runtime uses a Driver for scheduling, query optimization, and data alignment. A Driver controls multiple Ex- ecutors, each handling data scanning, manipulation, and result generation. Executors perform various operations such as GO¨DEL script computation, source code modeling, feature extraction, and User-Defined Functions (UDFs). Executors, being multi-threaded, incorporate task scheduling and thread pooling, facilitating parallel execution of independenttasks. Tasksthatneedexclusiveresourcesarequeued. ThestructuredapproachoftheCODEFUSE-QUERYRuntimeshapesthesystem’scomputationaldesignforcodeanal- ysis. Through its strategic stages and concurrent job handling, CODEFUSE-QUERY enables efficient, fault-tolerant 6CODEFUSE-QUERY: ScalableStaticCodeAnalysis processing. Thenextsectionwilldetailthesedesignelements, outliningthecomputationalprocessthatbolstersour large-scalecodeanalysissystem. 4 Logic-OrientedComputationDesign Analysis Program in Gödel Execution Plan Custom User Query Code Algorithm Interpret IDB Library Parse Compile Optimize Tier-2 Analysis Analysis Model Code Executable Execute Results COREF Tier-1 Java Data Model Source Code Facts Extract Store Tier-1 XML EDBTier-1 Model Facts EDBs Tier-1 Input Python Facts Computation Process Output Figure3: TheComputationDesign TheheartofCODEFUSE-QUERY’sruntimeengineisitslogic-orientedcomputationaldesign,whichiscrucialforef- ficientlyanalyzingvastvolumesofsourcecode. Thissectiondetailsthedesignelementsforlarge-scalecodeanalysis. Figure 3 provides a comprehensive overview of the computational process, which begins with the interpretation of userqueriesintoaGO¨DELprogramandtheextractionofsourcecodefactsintoadatabase. Theruntimeofoursystem thenexecutestheprogramtoproducetheanalysisresults. Thecomputationalprocesscomprisesthefollowingsteps: 1. Users write queries in GO¨DEL. These queries are interpreted by the system and turned into a comprehensive GO¨DEL program. Thisprogramincludestheanalysisalgorithmlibrary,userquery-derivedcustomcode,andthe Tier-2COREFmodel,alsoinGO¨DEL. 2. Aftertheprogramcodeisprepared,oursystemgeneratesanexecutionplanfromtheGO¨DELprogram. Thisplan encapsulates the computational relationships among facts, leading to the final facts. We then apply optimiza- tiontechniquestoenhancetheplan’sefficiency. Notallfactsrequirereasoning,offeringsignificantoptimization potential. Forinstance,wecanreduceaplanfrom2832computationstojust17. 3. After optimization, we compile the execution plan into an executable binary. By integrating the extracted facts fromthesource,weengageinalogicalreasoningprocesstoexecuteit,culminatingintheproductionofresults. Subsequentsubsectionsdelvedeeperintothedesignoftheunderlyingcomputationalmodel, datalog, thetwo-tiered datamodelingapproach,andtheDSL,GO¨DEL,usedtoframethecomputation. 4.1 UnderlyingComputationModel: Datalog GO¨DEL, a programming language for formulating the computation of CODEFUSE-QUERY, is fundamentally built uponDatalog[19], adeclarativelogiclanguage[25]thatabstractscomplexcomputations, permittinguserstospecify their requirements without fretting over execution minutiae. Datalog’s human-friendly syntax mirrors pseudo code, facilitating easy writing and maintenance. Moreover, its capabilities in handling complex queries, recursion, and logicalreasoningmakeitsuitableforstaticcodeanalysis.
ConsideranillustrativeDatalogprogramthatcomputesancestor-descendantrelationshipsofclasses,usingpredicates parentandancestorclass. Therulesaredefinedasfollows: 7CODEFUSE-QUERY: ScalableStaticCodeAnalysis parent(a, b) :- class(a), extends(a, b), class(b). ancestorclass(a, b) :- parent(a, b). ancestorclass(a, c) :- parent(a, b), ancestorclass(b, c). Datalog’s computation model is a specialized relational algebra variant, enabling logical computations among facts andsupportingrecursivecomputation[15],arequisiteformanystaticcodeanalysistasks[14]. Datalog’scomputationalprowess,harnessedby GO¨DEL,isrootedinseveralkeyattributes. Itleveragesoptimization algorithmstostreamlineexecution,ensuresprogramterminationtopreventinfiniteloops,operatesset-orientedcom- putations for efficiency, and handles complex queries and recursive computations proficiently. In practice, we use Souffle´[28]astheDatalogengineforGO¨DEL. OtheravailableenginesincludeµZ[27]andDDlog[30]. WhileDatalog serves as the computational core of GO¨DEL, our DSL extends it with higher-level features. Further details on the enhancementsprovidedbyGO¨DELwillbeexploredinSection4.3. 4.2 CodeModelingandExtraction Our system is underpinned by a data-centric approach, with the comprehensive schema, COREF, playing a critical roleinthemodelingofsourcecode. COREFencapsulatesboththesyntacticstructureandthesemanticinformation intrinsictothecode. COREF provides a suite of common code facts for analysis, including elements drawn from standard source code representationssuchasAbstractSyntaxTrees(AST),ControlFlowGraphs(CFG),AbstractSemanticGraphs(ASG), and Program Dependency Graphs (PDG). These elements deliver insights into syntax, control flow, semantics, and dependencieswithinthecode,therebyestablishingarobustfoundationofstandardcodefactsforuserstoanalyzeand query. Thisproactiveapproachtodataretentionallowsustoconfronttwomajorchallengesincodeanalysis:theComplexity Challenge, and the Diversity Challenge. By extracting the necessary data on-demand, COREF supports a broad spectrum of analyses.Despite the vast array of information in the source code, storing all data in a database is not practical. However, our ”Two-Tiered Modeling” technique circumvents this issue, successfully storing all relevant codeinformationatareasonablecost. 4.2.1 Two-tieredDataModelling Figure 3 depicts our data modeling process. The initial step is the extraction of source code facts, stored in a local database,representedbyourTier1modelextraction,comprisingroughlyahundredtablesperprogramminglanguage. AnexplicitE-RdiagramforJavaisavailableintheappendixD. The Tier 1 model is designed primarily to store facts in the most compact form, not for direct user querying. This focusonefficiencypreventsduplicateinformationstorageandenablesrecomputationofothernecessaryfacts. Thus, the database is designed for efficient persistent storage. For example, facts for analyzing a typical Java repository with about 1M lines of code can be stored in just around 720MB in the database. For comparison, precomputing andexpandingallthefactsforatypicalJavarepositorywouldtakearoundfourhoursand3.1GBofdiskspace. The Tier2modeliswhereuserinteractionmainlyoccurs,providingfactsreadyforquerying. Typicalfacts,likeaclass’s qualifiedname,arecalculatedbyanalyzingmultipletablesfromtheTier1facts. Thesynthesisofinformationoccurs dynamicallyatexecutiontime,withTier2factsaccessibleasifprecomputed. Essentially,Tier2factsarecomputed asneeded,providingon-demandaccesstocomplexdatarelationships. InDatalogterms,ourTier1modelissimilar tothe”ExtensionalDatabase”orEDB[35],containinggroundfactsavailablebeforecomputation. TheTier2schema, in GO¨DEL, is the ”Intensional Database” or IDB, consisting of derived facts, emerging from the reasoning process appliedtoEDBfacts. Inconclusion,ourtwo-tieredapproach,withuser-specificqueries,allowsustointerconnectalldataandencapsulate allstaticanalysistasksasDatalogcomputationtasks. Thisapproachprovidesanefficientmethodformanagingand analyzingsourcecodeinformation. RefertoAppendixHforanoverviewofourcurrentdatamodelingstatus. 4.2.2 Language-SpecificFactExtraction Forconstructlanguagefacts,ourprimarystrategyislanguage-specificfactextraction. Wecreateuniqueextractors andapplyadistinctCOREFschemaforeachlanguage. ThisapproachdeviatesfromUniversalAbstractSyntaxTrees 8CODEFUSE-QUERY: ScalableStaticCodeAnalysis (UASTs)andIntermediateRepresentations(IRs),whichaimforasingularrepresentationacrossalllanguages. How- ever,ourmethodretainsthecruciallanguagegrammardetails,whicharevitalformanyapplications. Constructinga parserinitsnativelanguageensuresoptimalcompatibilityandease. Thisstrategyfacilitatesascalable,standardized engineering process that can be applied to multiple languages. Each language necessitates a unique extractor, con- tributingtosignificantengineeringwork. AppendixHdetailsthenodecountfornineprogrammingorconfiguration languageswehavesupported,illustratingourefforts. Foreverylanguagewedealwith,weemployastrategythatdesignsourparserstooperateindependentlyofthebuild process. Ourextractorsareengineeredtofunctionindependentlyofanybuildprocesses, suchasMavenforJavaor Bazel for C++. This strategic choice, driven by the need to address the Maintenance Challenge, is based on the observationthatbuildprocessescanbeunreliableandbrittle, andmaintainingthemcanposesignificantchallenges,
especially in large organizations. By distancing ourselves from these processes, we enhance system maintainability andeasedebugging.ThisapproachcontrastswithtoolslikeCodeQL[13][2],whichdependonbuildsystemstocapture accuratesourcecodeandcompilationinformation. Tobetterillustrateourpoint,wedrawacomparisonwithCodeQL insection5.1,outliningthedifferencesinourstrategies. However,it’sworthnotingthatthismethodmightleadtothe lossofsomeinformation,especiallyforlanguagesintheCfamilythathaveadedicatedpreprocessingstage. Insuch scenarios,weconsidertheuseoffuzzyparsingtechniquestobridgetheinformationgap. It’simportanttohighlightthatwhileourmodelingandextractionprocessesarelanguage-specific,queriesarenot.This designallowsustoqueryandanalyzefactsacrossdifferentlanguageseffortlessly,addressingtheDiversityChallenge. 4.3 FormulatingtheComputationinGO¨DEL We have developed GO¨DEL, a Domain-Specific Language (DSL), specifically tailored for articulating code analysis computations. GO¨DEL’s primary design goals are twofold: 1) to provide a user-friendly interface enabling users to query and compute facts easily, addressing Complexity and Diversity Challenge) to implement an efficient and maintainable approach capable of handling the high volume and continue changing of tier-2 modeling. Ultimately, a GO¨DEL program will be compiled into a Datalog program, which is then transformed into an execution plan and executable. While this paper does not explore the comprehensive design and implementation details of GO¨DEL, it underscores severalkeydesignchoicesthatexemplifythevitalroleGO¨DELplaysinlarge-scalecodeanalysis. 4.3.1 ASQL-likeInterfaceCoupledwithRust-likeConstructs InGO¨DEL’sdesign,wemergetwodistinctivestrategies. Thefirstcaterstocommonusecasessuchasqueryingfacts withlightanalysisandmanipulation, forwhichweofferaSQL-likequeryinterfacetominimizethelearningcurve. WeprovideexamplesinAppendixF,forfurtherreference. However,SQLisknowntobechallengingtomaintainwhentheanalysismethodishighlycomplex(citationneeded). For instance, we have queries that span over 700 lines of script code. In such scenarios, we shift the language to a Rust-like code that includes high-level features such as Structs, Functions, and Types, which are leveraged to write intricatealgorithms. Intriguingly,in GO¨DEL’sDSLdesign,thesetwomethods,despitetheirdifferences,cancoexist within one script. This hybrid approach accommodates a broad spectrum of tasks, from lightweight operations like querying a class name to intricate algorithms such as customized dataflow analysis, effectively addressing both the ComplexityandDiversityChallengeaswellastheMaintenanceChallenge. 4.3.2 RichandHigh-levelProgramFeatures GO¨DEL provides a rich set of high-level features, enhancing the process of complex code analysis. Rather than just being a Datalog reiteration, it is a specialized language for code analysis and modeling, combining Datalog’s computationalpowerwithamoreexpressiveanduser-friendlyinterface. GO¨DEL excels in abstracting complex logic into understandable structures, simplifying the expression of intricate algorithmsandaddressingtheincreasingcomplexitychallengeoftenencounteredintraditionalDatalog. Unliketra- ditionalDatalog,whichofferslimiteddatatypes, GO¨DELhasarobusttypesystemthatallowsforcomplexdatatype definitionsandenforcesstricttypechecks, enhancingexpressivenessanddataintegrity. GO¨DEL’smodularityfacili- tatescodereuse,readability,andmaintenancebypartitioningprogramsintodistinctmodules. Thisstandsincontrast to the monolithic structure common in traditional Datalog programs. Additionally, GO¨DEL includes control struc- tures such as recursion, conditional statements, and looping constructs. These features, which can be transformed into corresponding Datalog semantics, expand GO¨DEL’s versatility while preserving Datalog’s computational effi- 9CODEFUSE-QUERY: ScalableStaticCodeAnalysis ciency. GO¨DEL alsoincorporatesUDFsandforeignfunctions,makingitaTuring-completelanguageandenhancing itsadaptabilityandflexibilityforspecificcomputationaltasks. In practical applications, using GO¨DEL can lead to a minimum of 50% reduction in source code lines compared to Souffle´,resultingincodethatisnotonlymoremaintainablebutalsoeasiertocomprehend. 4.3.3 UtilizingCommonAlgorithmsviaGO¨DELLibrary GO¨DEL integratesarobustCommonAlgorithmLibrary,housingvariouspredefinedanduser-definedmodules. This coderepositoryencouragesreusabilityandenhancescomputationalefficiency.Thelibrarycontainsfrequentlyutilized static analysis algorithms like control flow analysis, escape analysis, dataflow analyses, and live variable analysis. Userscanreadilyusethesepredefinedalgorithms,bypassingtheneedforreimplementation. Thelibraryalsosupports user-defined modules, facilitating customization per project needs. For instance, a user might create a custom taint analysisalgorithm, packageitasamodule, andreuseitinmultipleprojects. The GO¨DEL compilerisoptimizedfor thismodularity,effectivelyexecutingtheselibrariesandensuringefficienttranslationofhigh-levelGO¨DELcodeinto Datalogprograms. 4.4 OptimizationsandOpportunities Theresource-intensivenatureofstaticcodeanalysisnecessitatesstrategicoptimizationtoconserveCPUandmemory utilization. GO¨DEL,designedwithafocusonefficiency,introducesdual-leveloptimizationtechniques: oneintrinsic totheGO¨DELplatform,andtheothertargetingtheDatalogcomputationprocess. Boththesestrategiesjointlyaddress Efficiency Challenge, critical to large-scale code analysis. GO¨DEL programs are convertible into execution plans, whichdistillcomplexcomputationsintoastreamlinedprocess,providingaplatformforoptimization. Applicationof sophisticatedoptimizationalgorithms[14]candrasticallydecreasethecomplexityofstandardqueries. Asillustrated
in Figure 3, the implementation of these algorithms can reduce an analysis from 2832 computation nodes to a mere 17,withoutcompromisingtheresults. Beyond this program-level optimization, GO¨DEL’s architecture also enables system-level enhancements. The sys- tem can cache ”hot” facts—data points that are frequently computed and accessed—thereby curbing the redundant computationofrepetitivefacts. Moreover, GO¨DEL’sdesignallowsforproactivecomputation, wherethesystemcan anticipate and calculate certain facts before a query is initiated, based on usage pattern analysis. This preemptive approachbolstersthesystem’soverallefficiency, ensuringitcanadeptlyhandlelarge-scalecodeanalysistaskswith optimizedresourceutilization. 5 Evaluation In this section, we present a detailed evaluation of our system’s performance in executing code analysis tasks. We specificallymeasuretheimpactofcodevolumeoncomputingefficiencybyhandlingfileswithvaryingsizes,andwe assessqueryexecutionbyconsideringdatabasesizeandquerycomplexityasprincipalvariables. Thiscomprehensive evaluation is organized around three key aspects, each aimed at scrutinizing a critical component of system perfor- mance. TheseincludecomparativetestingwithCodeQL,theefficiencyofourtaskdesignandschedulingstrategies, andthedesignofoursystemforreusability. Thefindingsfromtheseinvestigationswillshedlightonoursystem’soperationalefficiency,scalability,andpotential bottlenecks,providingafoundationfortargetedenhancements. 5.1 ComparisonofCODEFUSE-QUERYandCodeQL Intool-level,CODEFUSE-QUERY’sapproachalignscloselywiththemethodologyemployedbyCodeQL[2],thestate- of-the-art. Inthisevaluation,ourfocusisonthistool-levelcomparisonratherthanasystem-wideanalysis. TheaimofthisexerciseistoevaluateandcomparetheefficiencyandprecisionofCODEFUSE-QUERYandCodeQL on metrics such as Success Rate, Data Transformation Time, Query Time, and Query Results. This evaluation also accentuatesCODEFUSE-QUERY’suniqueindependent-from-buildmethodology. Our evaluation used a diverse dataset of 50 open-source repositories (Appendix C) chosen randomly from GitHub, coveringJavaandPythonlanguageswithdistinctcodetransformationneeds. CodeQLrequiresJavapre-compilation but not Python. Tests were conducted on a MacBook Air Apple M1, 16GB memory, and an 8-core CPU to ensure fair comparison. The process involved measuring data extraction time for both CODEFUSE-QUERY and CodeQL, 10CODEFUSE-QUERY: ScalableStaticCodeAnalysis includingJava’scompilationtime.Thiswasfollowedbyrunningrepresentativequeriesonthedataandrecordingtheir executiontime. Systemresourceusage,suchasCPUandmemory,wasalsotrackedforfurtherefficiencyanalysis. 5.1.1 ResultAnalysisandConclusions Ananalysisof35open-sourceJavarepositoriesrevealedastarkdisparityinsuccessratesbetweenCODEFUSE-QUERY andCodeQL.Thenon-compilationextractionmethodologyemployedbyCODEFUSE-QUERYyieldeda100%success rate,anotablecontrasttothe28.5%achievedbyCodeQLinitsauto-compilemodenecessitatedbyitscompile-time nature(Table1). InthecontextofPython,wherebothtoolsemploynon-compilationextraction,paritywasobserved witha100%successrate. InsightfulrevelationsarisefromTable2. IntherealmofJavaextraction,CodeQL’sextractiontimeextendedto5.66 times that of CODEFUSE-QUERY due to the mandatory compilation step. Although the resulting database size for CODEFUSE-QUERYwas1.17timeslarger,itsmemoryfootprintwas4.65timesthatofCodeQL.InPythonextraction, CodeQL’stimeefficiencywassuperior,butitgeneratedadatabase2.62timeslargerandconsumed1.46timesmore memorythanCODEFUSE-QUERY. Acomparativeanalysisofqueryperformance(Table3,detailedinAppendixG)indicatedthat,forJava,theaverage querytimeforCODEFUSE-QUERYwas1.4timesthatofCodeQL,butCodeQLconsumed2.63timesmorememory. ForPython,CodeQL’saveragequerytimeandmemoryusagewere1.72and9.68timesthatof CODEFUSE-QUERY, respectively. Inconclusion,whileCODEFUSE-QUERY’sextractionandquerycapabilitiesaligncloselywiththoseofCodeQL(Ta- ble2,3), CODEFUSE-QUERY’sbuild-independentdesignoffersdistinctadvantages,particularlyintermsofsuccess rate. This is crucial considering our objective of analyzing a multitude of repositories and integrating with diverse systems. CODEFUSE-QUERY CodeQL Dataset Suc./Total Rate(%) Suc./Total Rate(%) Java 35/35 100 10/35 28.5 Python 15/15 100 15/15 100 Table1: ComparisonofRepositoryAnalysisSuccessRates CODEFUSE-QUERY CodeQL Java Python Java Python Time(s) 221.4 49.8 1252.9 30.5 DBSize(MB) 227.4 44.3 194.2 116.2 MaxMem(MB) 6625.3 819.8 1425.3 1197.9 Table2: CodeExtractionPerformanceComparison CODEFUSE-QUERY CodeQL Language Time(s) Mem(MB) Time(s) Mem(MB) Java 23.6 459.3 16.7 1207.8 Python 9.2 164.5 15.8 1592.8 Table3: ComparativeResultsofQueryingPerformance 5.2 EvaluatingtheEfficiencyDesigns Ourevaluationaimstoshowcasetheefficiencyandadaptabilityofoursysteminmanagingextensiveandvariedmodi- ficationsacrosslargecodebases,toassesstheperformanceenhancementsbroughtaboutbythreespecificmechanisms: DCATask,IFRATask,andDedicatedLong-runQueueing. FortheevaluationofIFRAandDCATaskmechanisms,wehavedesignedacontrolled,localexperiment,whichsimu- latestheenvironmentinwhichoursystemoperates,allowingustoisolatespecificvariablesandassesstheperformance
ofthesetwomechanismsinhandlingchangesinthecodebase. On the other hand, to evaluate the Dedicated Long-run Queueing mechanism, we employ a different approach. We recordtasksfromthelivesystemandreplaythemmultipletimesundervariousconditions. Thisapproachallowsusto 11CODEFUSE-QUERY: ScalableStaticCodeAnalysis observetheschedulingmechanism’seffectivenessinareal-worldsetting. Byreplayingthesametasksmultipletimes, wecanassesstheconsistencyofthesystem’sperformanceanditsabilitytooptimizeoverallend-to-endtime. 5.2.1 TheEfficacyoftheIFRA,FRAtaskdesign We conducted an experiment involving 10 large-scale applications. These applications spanned code sizes ranging from100,000to2,000,000linesofcode(LOC).Foreachapplication,weselectedasubsetof10commitstoevaluate theextractionperformanceofboththeFRAtaskandtheIFRAtask. Wethencomparedthemaximummemoryusage andtimeconsumptionforbothmethods. Theexperimentalsetupwasamachineequippedwith16GBofmemoryand a Mac M2 Pro CPU. To eliminate language-specific variations, our focus was exclusively on applications written in Java. PleaserefertoTable5foradetailedcomparisonofthemaximummemoryusageandtimeconsumptionforboththe FRAandtheIFRAforeachofthetenselectedapplications. OurresultsindicateatrendofincreasingextractiontimefortheIFRAextractionasthesizeofthecodebaseexpands, suggestingpotentialscalabilitychallenges. Despitethis,theIFRAachievesasignificantreductioninaverageextrac- tion time of all 10 apps from 233.28s to 41.58s, which - at average 82.2% reduction compared with the baseline, while App10 reaches 88.1%, and approximately 60% for applications with fewer than 20,000 LOC. These findings suggestthattheIFRAisbettersuitedtolargerrepositories,whileitsadvantagesmaynotbeaspronouncedinsmaller repositories. This isthe rationalebehind ourstrategy toselectively enabletheIFRA forcertain repositoriesand not universallyacrossall. Moreover,theIFRAtaskdemonstratesitsadvantagesinmemory-constrainedenvironments. Ourdatashowsanaver- age84.4%reductioninaveragememoryusageacrossallapplicationscomparedtoFRA’sextraction(baseline). This observation underscores the balance that the IFRA achieves between extraction time and memory efficiency, thus affirmingitspotentialasavaluablealternativetoFRAinscenarioswithlimitedsystemresources. 5.2.2 TheEfficacyoftheDCAtaskdesign To assess the efficiency of the DCA task methodology, we conducted a comparative analysis with the FRA task implementationacrossthesamesetof140tasksbyanalysingtheselecting22open-sourcerepositories(refertoTable inAppendixCintheDCAtasksection). AsdepictedinTable4,theresultswerenoteworthy: onaverage,aDCAtask necessitatedmerely3.67%oftheanalysistimecomparedtoaFRAtask,afigurethatunderscorestheefficiencyofthe DCAtaskapproachwhenprocessingcodemodifications. Moreover, the integral role of our scheduler in this process merits attention. Upon determining that a task can be downsizedtoaDCAtask,theschedulernotonlyconservessubstantialsystemresourcesbutalsosignificantlyenhances performance. Thisdecision-makingprowessoftheschedulerfurtheramplifiesthevalueandefficacyofoursystem. 5.2.3 TheEfficacyforhandlingHigh-DurationTasks Weconductedanexperimentanalyzinggatewayinterfacesinadatasetof4,000repositoriestoinvestigatetheeffect oftaskexecutiontimeontheoverallworkflowandtoexploreoptimizationstrategies. Thisexperimentusedrealtasks fromalivesystemtoensuretheresults’relevanceandapplicability. Inourworkflow,weseta3,600-secondlimitforeachtask’sexecutiontime. Tasksexceedingthislimitweretermed ’High-DurationTasks’(HDTs). Initially,tasksdispatchedtoCODEFUSE-QUERYwithoutspecificstrategiesresulted in a total execution time of 10,488 seconds for 4,000 tasks, including failed tasks and those that hit the time limit, primarilydueto11HDTswithintheset(seeTable6fordetails). Tooptimizethis,ourAnalysisCoordinatorusesastrategywhereHDTsareidentifiedanddirectedtoaseparatequeue processedbyhigher-capabilitymachines. Thisstrategicresourceallocationnotablyreducedthetotalexecutiontime to 4,006 seconds, an efficiency improvement of over 62%. Additionally, this strategy ensured a 100% success rate, demonstratingitseffectivenessinmanagingHDTs. This experiment underscores the value of strategic task scheduling in handling high computational requirements, providingabasisforfurtherresearchinthisfield. 5.3 EvaluatingReusabilityDesigns To evaluate our system’s re-usability, we observed our live system for a week as it performed various static code analysis tasks on cached facts DB. These tasks, ranging from security vulnerability to code smell detection, were 12CODEFUSE-QUERY: ScalableStaticCodeAnalysis TaskType Average. LOC Average. Time(s) DCA 1,431 12.09 FRA 269,169 321.35 Table4: ComparisonofDCAvs. FRATaskson140tasks App LinesofCode(LOC) ExecutionTime(s) Reduction MemoryUsed(MB) Reduction Total AvgChange Base Incr. (Incr.vsBase) Base Incr. (Incr.vsBase) App1 109,646 196 54.0 22.1 59.0% 9,985 903 90.9% App2 122,514 80 67.5 24.5 63.7% 9,989 965 90.3% App3 125,709 763 62.5 22.5 64.0% 10,120 1,056 89.5% App4 173,119 27 80.7 22.9 71.6% 10,390 1,453 86.0% App5 259,204 625 86.0 28.8 66.4% 10,564 1,692 83.9%
App6 264,963 89 127.3 29.1 77.1% 9,975 1,586 84.1% App7 428,473 75 202.3 35.1 82.6% 10,935 1,647 84.9% App8 671,469 320 181.5 39.8 78.1% 10,590 1,850 82.5% App9 944,614 298 300.6 52.0 82.7% 12,342 2,702 78.1% App10 1,862,273 2,238 1170.5 139.0 88.1% 14,296 3,202 77.6% Avg. 496,198 471 233.3 41.6 82.2% 10,919 1,706 84.4% Table5: Comparisonoftimeandmemoryusageforversioncodemodelingacross10applications. drivenbyscriptsfromthelivesystem,representingreal-worldusageandofferingvaluableinsightsintoourdatareuse mechanism. Thisreal-timemonitoring,asopposedtoasimulatedexperimentalsetup,providedapracticalperspective onthesystem’sversatilityandthedatareusemechanism’sapplicability. 5.3.1 AnalysisofResults Throughout a week of system operations, we collected task and query statistics which are detailed in Appendix E’s Table 7. The data revealed that the reuse factor of our cached COREF facts DB averaged around 13. This suggests thateachversionofthedatawasrepurposedapproximately13timesfordifferentstaticcodeanalysistasks. An interesting observation, however, was that the average reuse factor of query results was considerably lower, at around 1.4 (Table 8). This discrepancy implies that even though the facts DB itself is highly reusable, the demands for the results of specific queries are generally more diverse. However, there were instances where certain query resultsweresharedacrossmultipletasks,suggestingthatthereispotentialforincreasedresultsharing. Oneparticular patternwenotedwasthatgeneral,non-application-specificqueries,suchastheCyclomaticComplexitymetric,were morepronetosharing. Thisinsightindicatesthattheremightbevalueinbundlingthesecommonlyusedqueriesintoa ’commonsolution’package.Thisstrategycouldstreamlinethecodeanalysisprocessandfurtherenhancethesystem’s efficiency. The variety of code analysis tasks, demonstrated by data in Appendix E’s Table 7, highlights the versatility of our transformed,cachedfactsDB.Moreover,therecurrentusageofsimilarqueriesbydifferentusersindicatesapotential efficiency strategy: caching query results to avoid redundant computations. To further streamline the workflow, we mightpublishcriticalqueryresultsonadedicatedinterface,therebyminimizingtheneedforuserstoexecutecommon queries,enhancingproductivityandmakingresultsreadilyaccessible. 6 ExploringApplicationsandUseCaseswithinaLarge-ScaleOrganization Inthissection,weexplorethepracticalityofouradvanced,query-focusedcodeanalysissystem,particularlyforlarge corporationswithdiverse,complexuserrequirements. To illustrate the system’s versatility, we note its extensive operational context. Over 30 teams use this system for more than 110 daily and over 300 annual use cases, as shown partially in table 10 in the appendix. The system’s resilienceandflexibilityareevident,handlingover110,000,000tasksannually. Weelucidatethesystem’spracticality furtherthroughfourusernarrativesinthefollowingsections. Thesenarrativeswillprovideinsightsintothesystem’s real-worldapplications,itsbenefits,andpotentialfutureuses. 13CODEFUSE-QUERY: ScalableStaticCodeAnalysis Strategy Success Timeouts Exec. Time(s) Random 98.57% 9 10,488 Coordinator 100% 0 4,006 Table6: ComparisonofSchedulingStrategies Day No. of No. of Query/Extraction Queries Extractions Ratio Mon 119,510 7,672 15.6 Tue 126,231 8,524 14.8 Wed 132,537 9,164 14.5 Thu 133,344 9,674 13.8 Fri 110,990 11,211 9.9 Sat 17,196 1,632 10.5 Sun 9,991 768 13.0 Avg. 92,828 6,949 13.0 Table7: WeeklyStatisticsofCodeExtractionTasks 6.1 ChangeImpactAnalysis In the realm of online services risk management, the ’shift-left’ change impact analysis (CIA)[12, 29, 11, 16, 17] has gained importance. CIA scrutinizes code changes to detect potential impacts on services, guiding subsequent actions. The’shift-left’approachintegratesCIAintothedevelopmentcycle,facilitatingimmediateevaluationspost- codesubmission. Thisnecessitatesrapidanalysis,usuallywithintenminutes. Oursystemmeetsthisrequirementand integrateseffortlesslywithothersystems. Theterm”impact”inCIAiscontext-dependent. Forinstance,inasecurity context,animpactidentifiespotentialvulnerabilities; inselectivetestexecution,itinfluencesthetestsinitiated. Our systemcaterstothisdiversitywith GO¨DEL thatallowsuserstocustomizeimpactdefinitions. Asanexample,auser can define impacts as changes affecting specific database tables, enabling a tailored CIA experience. Incorporating CIA into the development process provides real-time insights for developers. This swift analysis supports informed decisionsaboutcodemodifications,securitypatches,andsystemstability,enhancingtheefficiencyandeffectiveness ofthedevelopmentprocess. 6.2 DataPreparationfortrainingLargeLanguageModels LargeLanguageModels(LLMs)aregainingpopularityinsoftwareengineering[39,40],withrolesincodegeneration and analysis[20]. The performance and security of these models significantly depend on the quality and diversity of their training data, often comprising billions of code lines. Handling such massive code data, especially with the explosion of coding languages and codebases, is challenging in LLM training. Our query-based system addresses this by efficiently processing and refining vast code data across multiple languages and frameworks. Our system’s robustarchitectureenablesrapidanalysisoflargecodevolumes,identifyingsyntaxerrorsandsecurityvulnerabilities,
therebyenhancingdataquality. Forexample,itcanswiftlyprocessamulti-terabytedatasetofdiverselanguages,filter out problematic code, and perform necessary transformations. Besides, our system maintains the model’s security integritybyeliminatingcommonvulnerabilities,likeSQLinjectionflawsinaPHPcodebase.Italsoensuresabalanced codedatadistributionacrossvariouslanguagesandframeworks,counterbalancinganyinitialbiasinthedataset. The scalability of our system makes it adaptable to increasing code data volumes, preparing it for the growing size and complexityofcodebases. Hence,oursystemisnotonlysuitedtocurrentLLMtrainingdemandsbutisalsoequipped forfuturedevelopmentsinthisfield. 6.3 Metrics-DrivenApproachtoEnhanceSoftwareEngineeringProductivity Weaimtoshapeaproductivity-centricculturewithinsoftwareengineering,focusingonimprovingR&Dproductivity by providing developers with actionable insights from their code. These insights include metrics on code quality, volume,style,anderrorrates,servingasindicatorsforcontinuousimprovement. Ourapproachoperatesattwolevels: seasonal and daily. Seasonally, we compile metrics for all developers, encouraging competition and setting perfor- mance benchmarks. Daily, we provide data to guide developers towards improved productivity and superior code. A daily report might include an assessment of grammatical changes in the code, offering a refined alternative to traditionallinesofcodemetrics. Thisreportalsoemphasizeserrorratesandprovidestargetedimprovementsugges- tions. Meanwhile, aseasonalreportcouldrankdevelopersbasedonthesemetrics, encouraginghealthycompetition 14CODEFUSE-QUERY: ScalableStaticCodeAnalysis RevisionID Mon Tue Wed Thu Fri Sat Sun C1 3,297 3,132 2,503 2,588 2,680 352 261 C2 194 408 868 869 437 187 196 C3 194 282 681 868 342 171 187 C4 188 279 661 867 252 153 187 C5 188 221 542 739 216 108 187 C6 187 195 266 252 190 108 95 C7 187 195 252 216 190 95 95 C8 179 194 252 198 190 73 57 C9 177 194 252 198 189 73 57 C10 171 194 201 198 187 68 57 (a)WeeklyDistributionofFrequentCommitsforWholeVersionTasks ScriptID Mon Tue Wed Thu Fri Sat Sun Q1 106 265 148 168 77 40 44 Q2 86 94 56 62 64 33 17 Q3 54 51 40 46 51 20 13 Q4 44 48 37 39 48 12 10 Q5 38 45 34 39 47 12 10 Q6 35 45 28 36 27 12 10 Q7 29 33 26 34 27 10 9 Q8 28 33 26 26 26 9 8 Q9 27 30 24 25 25 9 8 Q10 25 28 24 24 25 9 8 (b)DailyFrequencyofQueriesMappedtoMostFrequentCommits Table8: ComparisonofWeeklyCommitFrequenciesandDailyQueryMappingsforWholeVersionTasks andcontinuousself-improvement. Oursystem’sscalability,precision,andcapabilitytohandlevastvolumesofcode distinguishit. Itisdesignedtodeliverinsightsandfacilitateimprovements,irrespectiveofthecodebase’ssizeorcom- plexity. Integrating our system into their workflow allows organizations to foster continuous improvement, enhance developerproductivity,andimprovesoftwareproductquality. 6.4 Ad-hocAnalysisforLarge-ScaleCodebaseExamination Ourquery-basedcodeanalysissystemoffersad-hocanalysesforcomprehensiveexplorationandevaluationoflarge codebases. Thisiscrucialforgranular,one-timeexaminationsofallcoderepositories. AcaseinpointistheQuality AssuranceteammanagingAspect-OrientedProgramming(AOP)withintheorganization. Oursystem’sad-hocanaly- sisidentifiesallsetjoinpointvaluesandaffectedcodesegments,assistingincontrollingjoincutsandensuringAOP quality. Similarly,foraDataComplianceteamimplementingnewprivacyregulations,oursystemconductsaholistic scanofallcoderepositories,identifyingpotentialnon-complianceinstances.Forarchitectsandtechnicalleads,thead- hocanalysisaidsinarchitecturalexploration,identifyingareasforimprovement,examiningcodedependencies,and assessingarchitecturaldecisionimpacts. Theycandetectarchitecturaldriftandunderstanddesignmodificationimpli- cations. Inlargeorganizations, diverseteamsmayneedinsightsintocodingpractices. Forinstance, acybersecurity teammightscrutinizeoutdatedfunctionsuse,whileaDevOpsteammightassessspecificdeploymentmethodologies. Our system facilitates extensive ad-hoc analyses within hours, with an option to export results for further examina- tion. This empowers teams to make data-driven decisions, enhance architecture, and align with organizational best practices. 7 RelatedWork BigDataProcessingFrameworks: Bigdataprocessingframeworksarepivotalinanalyzinglarge-scalecodebases. MapReduce,aprogrammingparadigmdesignedforprocessinglarge-scaledatainadistributedenvironment[22],has influencednumeroussystems’design. Hadoop,anopen-sourceframework,facilitatesdistributedprocessingoflarge datasets across hardware clusters [36]. It offers a scalable and fault-tolerant infrastructure for data storage and pro- cessing. Spark,anotherdistributeddataprocessingframework,isknownforhigh-speeddataanalytics,employingan in-memory computing model for extensive data analysis [37]. Higher-level infrastructures, like Hive [34], leverage Hadoop and provide a high-level query language, HiveQL. Hive simplifies data analysis in Hadoop’s HDFS by en- 15CODEFUSE-QUERY: ScalableStaticCodeAnalysis ablingdeveloperstowritequeries,whichareconvertedintotasksinMapReduceorSparkforefficientevaluation. In ourwork,wetreatcodeasaspecificdataformandhavedevelopedaDSL,GO¨DEL,forqueryinglargecodebases. As abigdataprocessingframeworkforstaticcodeanalysis,ourapproachcouldgainfrombigdataprocessingadvance- ments. Future work could involve exploring efficiency enhancements by integrating big data processing algorithms intoourtechnique
StaticCodeAnalysisTools:Staticcodeanalysisisatechniquethatanalyzessourcecodeandpredictsprogrambehav- iorwithoutexecutingtheprogram. Tomeetthediverserequirementsofdevelopment,researchersandprofessionalsin bothacademiaandindustryhavedevelopedvarioustoolswithdistinctfeatures. Forexample,StaticApplicationSe- curityTesting(SAST)toolssuchasCoverity[6]andKlocwork[9]aredesignedtoidentifysecurityvulnerabilitiesin code,whicharecriticalformaintainingsoftwarereliabilityandsecurity.MostoftheSASTtoolsarelanguage-specific, likeClang[1],Infer[18],andPinpoint[33],whichserveasstaticanalyzersfortheCfamilyoflanguages. Inabroadercontext,toolslikeSonarQube[5]andPMD[7]offercomprehensiveanalysis,supportmultiplelanguages andprovideextensivechecks. Besides,therearetoolsthattargetspecificfeaturessuchasvisualizingcodedependen- cies(CodeScene[4]),enforcingcodingstandards(StyleCop[10]),ormanagingcomplexcodebases(CodeRush[3]and JArchitect[8]). Thesespecializedfeaturescatertonicherequirementsinsoftwaredevelopment,provinginvaluablein specificusecases. Ourworkalignswiththeemergingconceptofa”staticanalysisecosystem,”whichreferstotheintegrationofstatic analysis within the extensive machinery of large-scale software development. Major technology organizations like Google,Microsoft,Facebook,andAmazonhaveputthisconceptintopracticebydevelopingtheirownstaticanalysis tools, including Tricorder [32, 31], CloudBuild [24], and Cloud SAST [21]. These tools are designed to address the unique challenges presented by large-scale software development within their respective organizations. Insights derived from these systems have been instrumental in illuminating the challenges and opportunities associated with large-scale static analysis. Our research, like these pioneering works, contributes to this growing field of study by proposinganovelsolutiontoenhancethestaticanalysisecosystem. 8 Conclusion CODEFUSE-QUERYrevolutionizeslarge-scalestaticcodeanalysisbyleveragingadatacomputationapproach. Draw- ingfromDomainOptimizedSystemDesignandLogicOrientedComputationDesignprinciples,itemploysresource optimization,uniquetasks,andGO¨DELforrobust,scalable,andefficientanalysis. CODEFUSE-QUERY’sprovensuc- cessinhandlingovertenbillionlinesofcodedailyunderscoresitstransformativepotential. Wealsoopen-sourceour computationimplementation,fosteringfurtherresearchandinnovationinthisfield. References [1] Clangstaticanalyzer. https://clang-analyzer.llvm.org/. [2] Codeql. https://codeql.github.com/. [3] Coderush:Visualstudioproductivitytool. https://www.devexpress.com/products/coderush/. [4] Codescenecodeanalysistool. https://codescene.com/. [5] Continuouscodequality. https://www.sonarqube.org/. [6] Coveritystaticanalysis. https://www.synopsys.com/software-integrity/static-analysis-tools-sast.html. [7] Anextensiblecross-languagestaticcodeanalyzer. https://pmd.github.io/. [8] Jarchitect:Manageyourtechnicaldebt. http://www.jarchitect.com/. [9] Klocworkstaticcodeanalysis. https://www.perforce.com/products/klocwork. [10] Stylecop:C#codingstyleenforcement. https://github.com/StyleCop/StyleCop. [11] ACHARYA,M.,ANDROBINSON,B. Practicalchangeimpactanalysisbasedonstaticprogramslicingforindustrialsoftware systems. In Proceedings - International Conference on Software Engineering (New York, NY, USA, may 2011), ACM, pp.746–755. [12] ARNOLD,R.S. SoftwareChangeImpactAnalysis. IEEEComputerSocietyPress,Washington,DC,USA,1996. [13] AVGUSTINOV,P.,DEMOOR,O.,JONES,M.P.,ANDSCHA¨FER,M.QL:Object-orientedQueriesonRelationalData.In30th EuropeanConferenceonObject-OrientedProgramming(ECOOP2016)(Dagstuhl,Germany,2016),S.Krishnamurthiand B.S.Lerner,Eds.,vol.56ofLeibnizInternationalProceedingsinInformatics(LIPIcs),SchlossDagstuhl–Leibniz-Zentrum fu¨rInformatik,pp.2:1–2:25. 16CODEFUSE-QUERY: ScalableStaticCodeAnalysis [14] BANCILHON, F., MAIER, D., SAGIV, Y., AND ULLMAN, J. D. Magic sets and other strange ways to implement logic programs. ProceedingsofthefifthACMSIGACT-SIGMODsymposiumonPrinciplesofdatabasesystems(1986). [15] BANCILHON, F., ANDRAMAKRISHNAN, R. Anamateur’sintroductiontorecursivequeryprocessingstrategies. SIGMOD Rec.15,2(jun1986),16–52. [16] CAI,H.,ANDSANTELICES,R. Diver:Precisedynamicimpactanalysisusingdependence-basedtracepruning.InASE2014 -Proceedingsofthe29thACM/IEEEInternationalConferenceonAutomatedSoftwareEngineering(NewYork,NY,USA, sep2014),vol.33,ACM,pp.343–348. [17] CAI, H., AND THAIN, D. DistIA: a cost-effective dynamic impact analysis for distributed programs. In Proceedings of the31stIEEE/ACMInternationalConferenceonAutomatedSoftwareEngineering(NewYork,NY,USA,aug2016),ACM, pp.344–355. [18] CALCAGNO,C.,DISTEFANO,D.,DUBREIL,J.,GABI,D.,HOOIMEIJER,P.,LUCA,M.,O’HEARN,P.,PAPAKONSTANTI- NOU, I., PURBRICK, J., AND RODRIGUEZ, D. Movingfastwithsoftwareverification. InNASAFormalMethods(Cham, 2015),K.Havelund,G.Holzmann,andR.Joshi,Eds.,SpringerInternationalPublishing,pp.3–11.
[19] CERI,S.,GOTTLOB,G.,ANDTANCA,L. WhatyoualwayswantedtoknowaboutDatalog(andneverdaredtoask). IEEE, 1989. [20] CHEN, B., ZAN, D., ZHANG, F., LU, D., WU, B., GUAN, B., WANG, Y., ANDLOU, J.-G. Largelanguagemodelsmeet nl2code:Asurvey. InACL2023(June2023). [21] CHRISTAKIS, M., COTTENIER, T., FILIERI, A., LUO, L., MANSUR, M. N., PIKE, L., ROSNER, N., SCHA¨F, M., SEN- GUPTA,A.,ANDVISSER,W.Inputsplittingforcloud-basedstaticapplicationsecuritytestingplatforms.InESEC/FSE2022 (2022). [22] DEAN, J., AND GHEMAWAT, S. Mapreduce: Simplifieddataprocessingonlargeclusters. In6thSymposiumonOperating SystemDesignandImplementation(OSDI2004),SanFrancisco,California,USA,December6-8,2004(2004),E.A.Brewer andP.Chen,Eds.,USENIXAssociation,pp.137–150. [23] DISTEFANO, D., FA¨HNDRICH, M., LOGOZZO, F., AND O’HEARN, P. W. Scalingstaticanalysesatfacebook. Commun. ACM62,8(2019),62–70. [24] ESFAHANI, H., FIETZ, J., KE, Q., KOLOMIETS, A., LAN, E., MAVRINAC, E., SCHULTE, W., SANCHES, N., AND KANDULA,S. Cloudbuild:Microsoft’sdistributedandcachingbuildservice. InProceedingsofthe38thInternationalCon- ferenceonSoftwareEngineeringCompanion(NewYork,NY,USA,2016),ICSE’16,AssociationforComputingMachinery, p.11–20. [25] GENESERETH,M.R.,ANDGINSBERG,M.L. Logicprogramming. Commun.ACM28,9(sep1985),933–941. [26] HIPP,R.D. SQLite,2020. [27] HODER, K., HODER, K., BJØRNER, N., AND DE MOURA, L. µz- an efficient engine for fixed points with constraints. In Lecture Notes in Computer Science (including subseries Lecture Notes in Artificial Intelligence and Lecture Notes in Bioinformatics)—Lect. Notes Comput. Sci. (2011), vol. 6806, pp. 457–462. 23rd International Conference on Computer AidedVerification,CAV2011;Conferencedate:01-07-2011. [28] JORDAN,H.,SCHOLZ,B.,ANDSUBOTIC´,P. Souffle´: Onsynthesisofprogramanalyzers. InComputerAidedVerification (Cham,2016),S.ChaudhuriandA.Farzan,Eds.,SpringerInternationalPublishing,pp.422–430. [29] LEHNERT, S. A taxonomy for software change impact analysis. In Proceedings of the 12th International Workshop on PrinciplesofSoftwareEvolutionandthe7thAnnualERCIMWorkshoponSoftwareEvolution(NewYork,NY,USA,2011), IWPSE-EVOL’11,AssociationforComputingMachinery,p.41–50. [30] RYZHYK,L.,ANDBUDIU,M.Differentialdatalog.In3rdInternationalWorkshopontheResurgenceofDataloginAcademia andIndustry(2019). [31] SADOWSKI, C., AFTANDILIAN, E., EAGLE, A., MILLER-CUSHON, L., AND JASPAN, C. Lessons from building static analysistoolsatgoogle. CommunicationsoftheACM(CACM)61Issue4(2018),58–66. [32] SADOWSKI,C.,VANGOGH,J.,JASPAN,C.,SODERBERG,E.,ANDWINTER,C. Tricorder: BuildingaProgramAnalysis Ecosystem. 2015IEEE/ACM37thIEEEInternationalConferenceonSoftwareEngineering(2015),598–608. [33] SHI, Q., XIAO, X., WU, R., ZHOU, J., FAN, G., AND ZHANG, C. Pinpoint: fastandprecisesparsevalueflowanalysis for millionlines ofcode. In Proceedings ofthe 39thACM SIGPLANConference on ProgrammingLanguage Design and Implementation, PLDI2018, Philadelphia, PA,USA,June18-22, 2018(2018), J.S.FosterandD.Grossman, Eds., ACM, pp.693–706. [34] THUSOO, A., SARMA, J. S., JAIN, N., SHAO, Z., CHAKKA, P., ZHANG, N., ANTONY, S., LIU, H., AND MURTHY, R. Hive - a petabyte scale data warehouse using hadoop. In 2010 IEEE 26th International Conference on Data Engineering (ICDE2010)(2010),pp.996–1005. [35] ULLMAN,J.D. PrinciplesofDatabaseandKnowledge-BaseSystems,Vol.1. ComputerSciencePress,Inc.,1989. [36] WHITE,T. Hadoop-TheDefinitiveGuide:MapReducefortheCloud. O’Reilly,2009. 17CODEFUSE-QUERY: ScalableStaticCodeAnalysis [37] ZAHARIA, M., CHOWDHURY, M., DAS, T., DAVE, A., MA, J., MCCAULY, M., FRANKLIN, M. J., SHENKER, S., AND STOICA, I. Resilientdistributeddatasets: Afault-tolerantabstractionforin-memoryclustercomputing. InProceedingsof the9thUSENIXSymposiumonNetworkedSystemsDesignandImplementation,NSDI2012,SanJose,CA,USA,April25-27, 2012(2012),S.D.GribbleandD.Katabi,Eds.,USENIXAssociation,pp.15–28. [38] ZAZWORKA,N.,SHAW,M.A.,SHULL,F.,ANDSEAMAN,C. Investigatingtheimpactofdesigndebtonsoftwarequality. InProceedingsofthe2ndWorkshoponManagingTechnicalDebt(NewYork,NY,USA,2011),MTD’11,Associationfor ComputingMachinery,p.17–23. [39] ZHANG, Z., CHEN, C., LIU, B., LIAO, C., GONG, Z., YU, H., LI, J., ANDWANG, R. Asurveyonlanguagemodelsfor code,2023. [40] ZHENG,Z.,NING,K.,WANG,Y.,ZHANG,J.,ZHENG,D.,YE,M.,ANDCHEN,J. Asurveyoflargelanguagemodelsfor code:Evolution,benchmarking,andfuturetrends,2023. 18CODEFUSE-QUERY: ScalableStaticCodeAnalysis A RepresentativeUseCases
Team/PlatformFocus SpecificResponsibilities CodeAnalysisCapabilityandSystem Integration R&DEfficiency CodeMetricsAnalysis Supportsmulti-languagecodemetricanalysis. R&DEfficiency Application Architecture Gover- Providesarchitecturalmetricanalysisresults. nance LegalCompliance ComplianceAlgorithmMonitoring Analyzes code to detect if the algorithm sup- portspersonalizedswitches. CodeChangeQA Intelligent Change Analysis and Analyzes changed code for interface coverage ReleaseRiskAssessment andimpactanalysis. Information Flow Analy- Intelligent Analysis of Single Sys- Maps all parameter relationships, up to up- sis temInformationFlow stream and downstream interfaces, which can beusedasabaseforrulecomparison. Gray-ScaleReleasing Automatic Generation of Gray Analyzesserviceinterfaceparameterconsump- RulesforBusinessSystems tionandtraceabilityrelationships,aidinginthe improvement of gray change lines and overall coverage. AppSizeReduction Reducing the Size of iOS and An- AnalyzesiOSandAndroidcodetoidentifyun- droidApps usedcoderesources. MutationTesting Mutant Parameter Analysis and Analyzes code to supplement test cases and StaticCodeAnalysis. checktestcasecoverage. ApplicationSecurity Online Application Risk Preven- Analyzescodetodetectdangerousfunctionsin tion thelink. Change Risk Assessment TechnicalRiskAnalysis Providesmetadatainformationforfilesinclud- Platform ingjava,xml,properties,etc. QA Data Center for Gathering QA-related Data for Extracts data models from source code and Cloud CloudPlatform configurationfiles. IntelligentChangeAnaly- IntelligentHosting Evaluates the complexity of change code to sis judgeifthechangecanbehosted. IntelligentTesting CodeRiskIdentification Provides thesource codeof thecorresponding interfaceorimplementationclassfunction. Information Security DataSecurityCodeInterfaceScan Triggersafull-sitecodeinterfacescan,collect- Analysis ingandsummarizingallinterfaces(http,tr)and correspondinginterfaceparametersinthecode repository. Mini-program Privacy Privacy Risk Detection for Mini Analyzes code to detect incidents that violate Compliance Programs privacyrules. Architecture Assets and Architecture Assets Management Identifies the middleware framework informa- Governance andGovernance tionusedinapplicationsinbatch. ChangeImpactAnalysis CodeChangeImpactAnalysis Analyzes changed code to perform code change content analysis and change impact analysis. Network Attack and De- RiskPointInjectionAttack Extracts code features such as classes, meth- fenseExercise ods,variables,etc.,toaidintheconstructionof theattackdenominator. Manual Test Case Rec- Intelligent Recommendation of Analyzes changed code to perform code ommendation TestCasesforManualTesting change link analysis and service interface in- formationquery. Internal Coding Stan- Internal guidelines established to Analyzes code by implementing the coding dards ensureconsistency,readability,and standardcheckers. maintainabilityofcode. Table9: RepresentativeUseCases 19CODEFUSE-QUERY: ScalableStaticCodeAnalysis B QueryScriptList Category ScriptName Programming Languages Q1CodeCommentRatioQuery Java,Python,Js/Ts,Go Category1: CodeMeasure Q2CodeCyclomaticComplexityQuery Java,Python,Js/Ts,Go Q3CodeASTQuery Java,Python,Js/Ts,Go Q4CodeReusabilitywithJarQuery Java Q5CodeReusabilitywithHttpApi Java Q6CodeReusabilitywithRpcApiQuery Java,Xml Q7CodeCallGraphQuery Java Q8Auto-generatedCodeQuery Java,Python,Js/Ts,Go Q9HalsteadVocabularyQuery Java Category2: ArchitectureSmell Q10Fan-In/Fan-OutQuery Java Q11MutualRecursiveCallQuery Java Q12DepthofInheritanceTreeQuery Java Q13NumberofCyclicHierarchiesQuery Java Q14FindDuplicateImportJarQuery Java Q15LackofCohesionofMethodsQuery Java Q16UnusedImportQuery Java Q17OverlappingInterfacesQuery Java Q18OverridingMethodsQuery Java Q19CallChainbyGivenMethod Java Q20CallGraphwithRootQuery Java Category 3: Risk Analysis Meta Q21ClassHierarchyTreeQuery Java InfoModel Q22XmlDalSettingQuery Java,Xml Q23XmlPomDependencyQuery Xml Q24XmlSofaReferenceQuery Xml Q25XmlSofaConsumerQuery Xml Q26XmlCommonDrmConfigQuery Xml Q27XmlBeanQuery Xml Q28XmlLogSettingQuery Xml Q29PropertiesSettingQuery Properties Q30RpcMustHaveTimeoutQuery Java,Xml Category4: ChangeRiskAnalysis Q31FindSetBeforeUpdateQuery Java Rule Q32FindLocalThreadPoolQuery Java Q33FindInheritedClasswiththeSameName Java Query Q34FindReferenceAssignmentQuery Java,Xml Q35FindAuthenticateUserInfoQuery Java Q36FindCacheExpirationTimeQuery Java Q37FindInterfaceFieldAssignedQuery Java,Xml Q38FindJarMethodUsageQuery Java Q39FindPrivacyFieldInInterfaceQuery Java Category 5: Privacy Governance Q40 Find Exported Privacy Message Info Java andLegalCompliance Query Q41FindDependedPrivacyInterfaceQuery Java Q42FindRecommendationAlgorithmSetting Java,Xml Query Q43FindExportedPrivacyDBInfoQuery Java,Xml Q44FindPrivacyDBFieldsLineageQuery SQL Q45 Find Privacy Data Lineage from Code to Java,Xml,SQL DBFieldQuery Q46FindAdapterSettingQuery Java,Xml Category 6: Insurance Quality Q47FindInsuranceCVModelMappingQuery Java,Xml,Python Testing Q48FindConfigureKeyValueQuery Java Q49FindAllPointCutValuesQuery Java Category 6: Security and AOP Governance 20CODEFUSE-QUERY: ScalableStaticCodeAnalysis Category ScriptName Programming Languages Q50FindAllPointCutValueInfluencesQuery Java Q51FindReleasedArtifactModuleQuery Java,Xml Q52FindChairFrameworkApiQuery Js/Ts Category7:MiniProgramSecurity Q53FindTradeBffRpcFieldTracingQuery Js/Ts,Xml,Java andRiskGovernance Q54FindLoopPopUpConfrimQuery Js/Ts Q55FindLoopPopUpOnloadQuery Js/Ts Q56FindLoopPopUpRedirectQuery Js/Ts Q57FindOverCollectionUserInfoQuery Js/Ts Q58FindUnusedInterfaceQuery Objective-C
Category 8: Android/IOS Package Q59FindClassDependencyQuery Objective-C SizeGovernance Q60FindResourceSettinginXml Java,Xml Q61FindFunction/ClassDeclaration Swift Q62FindAllstatementsandAncestorQuery Objective-C Q63FindAllDeclarationandAncestorQuery Objective-C,Swift Q64CheckValueTypeWriteQuery Go Category 9: Middleware Gover- Q65CheckHttpBodyCloseQuery Go nance Q66CheckUnusedFunctionQuery Go Q67CheckErrorSettingQuery Go Q68CheckSetUserAgentDefinitionQuery Go Q69CheckSetK8sUserStructsQuery Go Q70FindControl/WebhookWatchesQuery Go Q71ValidFunctionCommentPairQuery Go Category 10: Data Preprocessing Q72ValidFunctionCommentPairQuery Python forLLMTraning Q73 Valid Callable/Class Documentation Pair Java Query Q74ValidCodeDocumentationPairQuery Js/Ts Q75FilterOversizedCodeBlockQuery Js/Ts,Java,Python,Go Q76 Filter Over Complicated Code Block Js/Ts,Java,Python,Go Query Q77FilterAuto-generatedFilesQuery Js/Ts,Java,Python,Go Table10: Listofqueryscriptscurrentlyinuse. 21CODEFUSE-QUERY: ScalableStaticCodeAnalysis C RepositoriesURLsinEvaluation No. Category RepositoryName RepositoryURL 1 Python Poetry https://github.com/python-poetry/poetry.git 2 Python Pytest https://github.com/pytest-dev/pytest.git 3 Python Faust https://github.com/robinhood/faust.git 4 Python Cirq https://github.com/quantumlib/Cirq.git 5 Python Request-HTML https://github.com/psf/requests-html.git 6 Python Bokeh https://github.com/bokeh/bokeh.git 7 Python Molten https://github.com/Bogdanp/molten.git 8 Python TermGraph https://github.com/mkaz/termgraph.git 9 Python Black https://github.com/psf/black.git 10 Python Bowler https://github.com/facebookincubator/Bowler. git 11 Python Transcrypt https://github.com/TranscryptOrg/Transcrypt. git 12 Python Langchain https://github.com/langchain-ai/langchain.git 13 Python AutoGPT https://github.com/Significant-Gravitas/ AutoGPT.git 14 Python Flask https://github.com/pallets/flask.git 15 Python Chartify https://github.com/spotify/chartify.git 16 Java(FRA) Zipkin https://github.com/openzipkin/zipkin 17 Java(FRA) IoTDB https://github.com/apache/iotdb 18 Java(FRA) Dubbo https://github.com/apache/dubbo 19 Java(FRA) Kafka https://github.com/apache/kafka.git 20 Java(FRA) Camel https://github.com/apache/camel.git 21 Java(FRA) SkyWalking https://github.com/apache/skywalking.git 22 Java(FRA) RocketMQ https://github.com/apache/rocketmq.git 23 Java(FRA) Pulsar https://github.com/apache/pulsar.git 24 Java(FRA) HBase https://github.com/apache/hbase.git 25 Java(FRA) Hive https://github.com/apache/hive.git 26 Java(FRA) Storm https://github.com/apache/storm.git 27 Java(FRA) Iceberg https://github.com/apache/iceberg.git 28 Java(FRA) Logging-log4j2 https://github.com/apache/logging-log4j2 29 Java(DCA) Hadoop https://github.com/apache/hadoop 30 Java(DCA) Druid https://github.com/apache/druid 31 Java(DCA) CAT https://github.com/dianping/cat 32 Java(DCA) Deeplearning4j https://github.com/deeplearning4j/ deeplearning4j 33 Java(DCA) Realm-Java https://github.com/realm/realm-java 34 Java(DCA) MaterialComponentsAndroid https://github.com/material-components/ material-components-android 35 Java(DCA) DoKit https://github.com/didi/DoKit 36 Java(DCA) Jedis https://github.com/redis/jedis 37 Java(DCA) Flink https://github.com/apache/flink 38 Java(DCA) Hystrix https://github.com/Netflix/Hystrix 39 Java(DCA) Apollo https://github.com/apolloconfig/apollo 40 Java(DCA) Tinker https://github.com/Tencent/tinker 41 Java(DCA) PhotoView https://github.com/Baseflow/PhotoView 42 Java(DCA) Fastjson https://github.com/alibaba/fastjson 43 Java(DCA) Servo https://github.com/Netflix/servo 44 Java(DCA) Eureka https://github.com/Netflix/eureka 45 Java(DCA) RxJava https://github.com/ReactiveX/RxJava 46 Java(DCA) Copybara https://github.com/google/copybara 47 Java(DCA) Guice https://github.com/google/guice 48 Java(DCA) Gson https://github.com/google/gson 49 Java(DCA) Guava https://github.com/google/guava 50 Java(DCA) Redisson https://github.com/redisson/redisson 22CODEFUSE-QUERY: ScalableStaticCodeAnalysis D RepresentativeER/Classdiagram Figure4: COREFforJavaERDiagram 23CODEFUSE-QUERY: ScalableStaticCodeAnalysis Figure5: COREFforJavaClassDiagram 24CODEFUSE-QUERY: ScalableStaticCodeAnalysis Figure6: COREFforPythonClassDiagram 25CODEFUSE-QUERY: ScalableStaticCodeAnalysis E StatisticsofDistinctQueriesforWholeVersionTasksOverOneWeek. CodeVersion Day1 Day2 Day3 Day4 Day5 TotalQueryTasks 119510 126231 132537 133344 110990 DistinctQueries 1751 2630 2641 2694 2558 DistinctQueries(Normalized) 111 98 101 105 100 Table11: StatisticsofDistinctQueriesforWholeVersionTasksOverOneWeek. ScriptID Frequency ScriptID Frequency ScriptID Frequency ScriptID Frequency Q1 46 Q1 54 Q1 24293 Q1 5393 Q2 45 Q2 38 Q2 22694 Q2 5390 Q3 45 Q3 35 Q3 22631 Q3 5389 Q4 31 Q4 35 Q4 1813 Q4 5388 Q5 31 Q5 35 Q5 1802 Q5 5387 Q6 31 Q6 34 Q6 343 Q6 5387 Q7 19 Q7 33 Q7 38 Q7 5387 Q8 19 Q8 33 Q8 35 Q8 5385 Q9 19 Q9 33 Q9 35 Q9 5381 Q10 18 Q10 33 Q10 22 Q10 5381 (c)Mostfrequentqueriesfor (d)Mostfrequentqueriesfor (a)Mostfrequentqueriesfor (b)Mostfrequentqueriesfor slice tasks with the same wholeversiontaskswiththe slicetasks wholeversiontasks code samecode
Table12: Top10mostfrequentqueriesperdayforfourscenarios. 26CODEFUSE-QUERY: ScalableStaticCodeAnalysis F ExampleQueryScripts Listing1: QueryExample1 // script 1 use coref::java::* 2 3 fn default_java_db() -> JavaDB { 4 return JavaDB::load("coref_java_src.db") 5 } 6 7 // find unused methods 8 fn unused_method(unused: string) -> bool { 9 for(c in Callable(default_java_db()), method in Callable( 10 default_java_db()), caller in method.getCaller()) { if (c != caller && unused = method.getSignature()) { 11 return true 12 } 13 } 14 } 15 16 fn main() { 17 output(unused_method()) 18 } 19 Listing2: QueryExample2 // script 1 use coref::javascript::* 2 3 fn default_db() -> JavascriptDB { 4 return JavascriptDB::load("coref_javascript_src.db") 5 } 6 7 fn getACallerFunction(function: FunctionLikeDeclaration, callerFunction: 8 FunctionLikeDeclaration) -> bool { for (mayInvokeExpression in MayInvokeExpression(default_db())) { 9 if (mayInvokeExpression in function.getACallSite() && 10 callerFunction = mayInvokeExpression.getEnclosingFunction()) { 11 return true 12 } 13 } 14 } 15 16 fn getAnEffectedFunction(function: FunctionLikeDeclaration, 17 effectedFunction: FunctionLikeDeclaration) -> bool { if (getACallerFunction(function, effectedFunction)) { 18 return true 19 } 20 for (callerFunction in FunctionLikeDeclaration(default_db())) { 21 if (getACallerFunction(function, callerFunction) && 22 getAnEffectedFunction(callerFunction, effectedFunction)) { 23 return true 24 } 25 } 26 } 27 28 /** 29 * Query the effected functions according to the changed lines. 30 27CODEFUSE-QUERY: ScalableStaticCodeAnalysis * 31 * @param function the changed function id 32 * @param signature the changed function signature 33 * @param functionPath the changed function file path 34 * @param startLine the changed function start line 35 * @param endLine the changed function end line 36 * @param effectedFunction the effected function id 37 * @param effectedSignature the effected function signature 38 * @param effectedFunctionPath the effected function file path 39 * @param effectedStartLine the effected function start line 40 * @param effectedEndLine the effected function end line 41 */ 42 fn out( 43 function: FunctionLikeDeclaration, 44 signature: string, 45 functionPath: string, 46 startLine: int, 47 endLine: int, 48 effectedFunction: FunctionLikeDeclaration, 49 effectedSignature: string, 50 effectedFunctionPath: string, 51 effectedStartLine: int, 52 effectedEndLine: int 53 ) -> bool { 54 if (getAnEffectedFunction(function, effectedFunction)) { 55 let (symbol = function.getSymbol(), 56 effectedSymbol = effectedFunction.getSymbol(), 57 location = function.getLocation(), 58 effectedLocation = effectedFunction.getLocation()) { 59 if (signature = symbol.getDescription() && 60 effectedSignature = effectedSymbol.getDescription() && 61 functionPath = location.getRelativePath() && 62 startLine = location.getStartLineNumber() && 63 endLine = location.getEndLineNumber() && 64 effectedFunctionPath = effectedLocation.getRelativePath() 65 && effectedStartLine = effectedLocation.getStartLineNumber() 66 && effectedEndLine = effectedLocation.getEndLineNumber()) { 67 return true 68 } 69 } 70 } 71 } 72 73 fn main() { 74 output(out()) 75 } 76 28CODEFUSE-QUERY: ScalableStaticCodeAnalysis Listing3: QueryExample3 // script 1 use coref::xml::* 2 3 schema DependencyElement extends XmlElement {} 4 5 impl DependencyElement { 6 @data_constraint 7 pub fn __all__(db: XmlDB) -> *DependencyElement { 8 for(e in XmlElement(db)) { 9 if (e.getElementName() = "dependency") { 10 yield DependencyElement { 11 id: e.id, 12 location_id: e.location_id, 13 parent_id: e.parent_id, 14 index_order: e.index_order 15 } 16 } 17 } 18 } 19 } 20 21 schema GroupElement extends XmlElement {} 22 23 impl GroupElement { 24 @data_constraint 25 pub fn __all__(db: XmlDB) -> *GroupElement { 26 for(e in XmlElement(db)) { 27 if (e.getElementName() = "groupId") { 28 yield GroupElement { 29 id: e.id, 30 location_id: e.location_id, 31 parent_id: e.parent_id, 32 index_order: e.index_order 33 } 34 } 35 } 36 } 37 } 38 39 schema VersionElement extends XmlElement {} 40 41 impl VersionElement { 42 @data_constraint 43 pub fn __all__(db: XmlDB) -> *VersionElement { 44 for(e in XmlElement(db)) { 45 if (e.getElementName() = "version") { 46 yield VersionElement { 47 id: e.id, 48 location_id: e.location_id, 49 parent_id: e.parent_id, 50 index_order: e.index_order 51 } 52 } 53 } 54 } 55 } 56 57 schema ArtifactElement extends XmlElement {} 58 29CODEFUSE-QUERY: ScalableStaticCodeAnalysis 59 impl ArtifactElement { 60 @data_constraint 61 pub fn __all__(db: XmlDB) -> *ArtifactElement { 62 for(e in XmlElement(db)) { 63 if (e.getElementName() = "artifactId") { 64 yield ArtifactElement { 65 id: e.id, 66 location_id: e.location_id, 67 parent_id: e.parent_id, 68 index_order: e.index_order 69 } 70 } 71 } 72 } 73 } 74 75 schema PomFile extends XmlFile {} 76 77 impl PomFile { 78 @data_constraint 79 pub fn __all__(db: XmlDB) -> *PomFile { 80 for(f in XmlFile(db)) { 81 if (f.getFileName() = "pom.xml") { 82 yield PomFile { 83 id: f.id, 84 file_name: f.file_name, 85 relative_path: f.relative_path 86 } 87 } 88 } 89 } 90 } 91 92 // output relative path of the file, referenced jar name and version 93
fn out(fileName: string, m1: string, m2: string, m3: string) -> bool { 94 let (db = XmlDB::load("coref_xml_src.db")) { 95 for (f in PomFile(db), 96 e1 in GroupElement(db), 97 e2 in VersionElement(db), 98 e3 in ArtifactElement(db), 99 c1 in XmlCharacter(db), 100 c2 in XmlCharacter(db), 101 c3 in XmlCharacter(db), 102 p in DependencyElement(db)) { 103 if (f.key_eq(p.getLocation().getFile()) && 104 fileName = f.getRelativePath() && 105 p.key_eq(e1.getParent()) && 106 e1.key_eq(c1.getBelongedElement()) && 107 m1 = c1.getText() && 108 p.key_eq(e2.getParent()) && 109 e2.key_eq(c2.getBelongedElement()) && 110 m2 = c2.getText() && 111 p.key_eq(e3.getParent()) && 112 e3.key_eq(c3.getBelongedElement()) && 113 m3 = c3.getText()) { 114 return true 115 } 116 } 117 30CODEFUSE-QUERY: ScalableStaticCodeAnalysis } 118 } 119 120 fn main() { 121 output(out()) 122 } 123 31CODEFUSE-QUERY: ScalableStaticCodeAnalysis G ComparativeResultsofQueryingPerformance CODEFUSE-QUERY CodeQL Language QueryName Time(s) Mem(MB) Time(s) Mem(MB) Java Q1. AfferentCoupling 18.5 294.7 7.2 1018.1 Java Q2. EfferentCoupling 19.7 292.3 71.5 3045.9 Java Q3. CyclomaticComplexity 64.4 1391.6 6.5 1003.8 Java Q4. CallGraph 19.8 297.3 5.8 785.9 Java Q5. ClassHierarchy 7.0 151.1 4.9 674.2 Java Q6. FindAllClass 12.2 328.7 4.5 718.8 Avg. 23.6 459.3 16.7 1207.8 Python Q1. CyclomaticComplexity 11.9 169.5 27.6 2431.3 Python Q2. ClassHierarchy 9.6 178.7 17.1 1964.3 Python Q3. FindRedundantIfStatement 6.1 145.4 2.7 382.9 Avg. 9.2 164.5 15.8 1592.8 Table13: ComparativeResultsofQueryingPerformance H CodeModelStatistics Language Status Nodes(T1) Nodes(T2) Java Mature 157 482 XML Mature 12 27 Js/Ts Mature 392 574 Objective-C Beta 53 109 Go Beta 38 263 Python Beta 55 120 Swift Beta 248 679 SQL Beta 750 2552 Properties Beta 9 11 Table14: CodeModelStatistics 32
2401.02737 1 The Vulnerability Is in the Details: Locating Fine-grained Information of Vulnerable Code Identified by Graph-based Detectors Baijun Cheng, Kailong Wang, Cuiyun Gao, Xiapu Luo, Li Li, Yao Guo, Xiangqun Chen, Haoyu Wang Abstract—Vulnerabilitydetectionisacrucialcomponentinthe function or a code snippet could contain over a dozen of software development lifecycle. Existing vulnerability detectors, code lines, which remains challenging for the developers to especially those based on deep learning (DL) models, have understandtherootcauseofthevulnerabilitiesandfurthertake achieved high effectiveness. Despite their capability of detecting action to fix them. vulnerablecodesnippetsfromgivencodefragments,thedetectors aretypicallyunabletofurtherlocatethefine-grainedinformation One promising way to tackle this problem is leveraging pertaining to the vulnerability, such as the precise vulnerability explanation approaches to select important features for the triggering locations.In this paper, we propose VULEXPLAINER, DL-based detectors, and then mapping them to the corre- a tool for automatically locating vulnerability-critical code lines sponding code lines. Recent rapid advances in the graph- fromcoarse-levelvulnerablecodesnippetsreportedbyDL-based based explainability technology shows great potential towards detectors.Our approach takes advantage of the code structure andthesemanticsofthevulnerabilities.Specifically,weleverage this solution.In particular, the existing explanation methods programslicingtogetasetofcriticalprogrampathscontaining commonly facilitate model interpretability from three angles: vulnerability-triggering and vulnerability-dependent statements assigningnumericvaluestographedges[10],[11],computing and rank them to pinpoint the most important one (i.e., sub- importance scores for nodes [12], and calculating scores for graph) as the data flow associated with the vulnerability. We graph walks while traversing through GNNs [13]. Despite demonstrate that VULEXPLAINER performs consistently well on four state-of-the-art graph-representation(GP)-based vulner- their success in tasks such as molecular graph classifications, ability detectors, i.e., it can flag the vulnerability-triggering the existing GNN-based explanation techniques still contain code statements with an accuracy of around 90% against eight intrinsic insufficiencies that hinder the direct application to common C/C++ vulnerabilities, outperforming five widely used derive fine-grained information regarding the vulnerability, GNN-based explanation approaches. The experimental results such as the triggering code lines. demonstratetheeffectivenessofVULEXPLAINER,whichprovides insights into a promising research line: integrating program The first insufficiency lies in the limited capability for slicing and deep learning for the interpretation of vulnerable capturingthesubtlebutrichsemanticsencompassedinbenign code fragments. and vulnerable code bases. Similar to the fact that chemical molecule function is defined by its chemical groups (i.e., the important structures including nodes and edges), the function I. INTRODUCTION of a program is defined by statements (i.e., nodes) and their The proliferation of modern software programs developed information flows (i.e., edges) in the extracted code graph as for diverse purposes and usage scenarios is inevitably and well. Therefore, program-specific semantics is crucial for ex- persistentlycoupledwithintensifiedsecuritythreatsfromvul- plainingapproaches.Nonetheless,existingexplainingmethods nerabilities, evidenced by the substantial surge in the volume areunabletolocatesuchfine-grainedinformationastheygen- of reported vulnerabilities via the Common Vulnerabilities erallyneglecttherichsemanticinformationinprogramgraphs. and Exposures (CVE) [1]. To counteract the potential ex- This is plausibly attributed to the complexity of program ploitation, both academia and industrial communities have vulnerabilitydetectionincomparisontotheexistingtasks(i.e., proposed numerous techniques for identifying and locating simpler topological structure). For example, the control-flow those vulnerabilities. or program-dependence relationship between two statements Traditional approaches, such as the rule-based analysis represented by an edge is hardly reflected. In addition, the techniques (e.g., SVF [2], CHECKMARX [3], INFER [4], and semantic information contained in a node is difficult to be CLANG STATIC ANALYZER [5]), leverage predefined signa- encoded into the latent space. turesorrulestoidentifyvulnerabilities.Unfortunately,similar The second insufficiency arises from inadequate considera- to other static analysis techniques, they typically suffer from tion of statements that are critical for vulnerability detection. high false positive and negative rates. More recently, DL- Mostvulnerableprogramsandtheirpatchedversionstypically based detection techniques [6], [7], [8], [9], which generally have similar topological structures, as they all contain the operate on extracted code feature representations, have shown statementswhichtriggervulnerabilities,asshowninFigure1. great effectiveness in flagging vulnerability-containing code The only difference could reside in a few statements where fragments (i.e., functions or slices). However, the coarse the vulnerabilities are patched, entailing control-flow and granularity and the black-box nature of the analysis renders program-dependent information related to the vulnerability
poor interpretability in the detection results. For example, a triggers. Unfortunately, none of the existing methods target 4202 peS 7 ]ES.sc[ 3v73720.1042:viXra2 PLAINER can better locate vulnerability-triggering code lines on slice-level detector DEEPWUKONG than the other three Source code Graph function-leveldetectors.Intheseconddimension,wecompare 0 void badSink(int data) { 0 VULEXPLAINER with other GNN explainers, including PG- 1 int i; EXPLAINER, GNNEXPLAINER, GRAD, DEEPLIFT [15] and 2 int buffer [ 10 ] = { 0 } ; 1 GNN-LRP.VULEXPLAINERachievesanaverageLC of90% -3 if (data >= 0) { which is significantly higher than that of other explanation +3 if (data >= 0 && data < 10) { 2 approaches. More specifically, the explanation results given 4 buffer[data] = 1; by the existing approaches are not strongly related to the 5 for(i = 0; i < 10; i++) { 3 dependencepathsofvulnerablestatements,whichcouldbethe 6 printIntLine(buffer[i]); causeoftheirlowereffectiveness.Inaddition,weshowthatthe 7 } 4 10 performance of VULEXPLAINER is independent of the front- 8 } end detectors, which further confirms that VULEXPLAINER is 9 else { a general-purpose approach. 5 10 printLine("ERROR: negative index."); In summary, we make the following main contributions: 11 } • A novel vulnerability fine-grained information locat- 12 } 6 ing technique for GNN-based vulnerability detectors. vulnerability trigger points GiventheinadequateexplainabilityoftheexistingGNN- normal statements Control flow edge based vulnerability detectors, we propose the framework vulnerability fix points Control Dependence edge Data Dependence edge VULEXPLAINER as a solution. It can identify impor- tant flow paths in a program that contain vulnerability- Fig. 1: A vulnerable code from SARD where in its fixed triggering statements, providing finer-grained semantics version Line 3 has been modified. contexts for the identified vulnerabilities. We release our source code and dataset used in this work on our anonymous repository [16]. or capture such relationships between vulnerability-triggering • Approach effectiveness. Through the multi-dimensional evaluation of the comprehensive benchmark dataset, we and vulnerability-fixing statements. show that VULEXPLAINER outperforms the existing ex- Our solution.Inthiswork,wepropose VULEXPLAINER,a planationmethodsintermsofLC,whichisthekeyfactor novel approach to identify fine-grained information from vul- that impacts the localization and fix of a vulnerability. nerable code reported by GNN-based vulnerability detectors. On average, VULEXPLAINER achieves LC higher than Given a detected vulnerable code fragment, VULEXPLAINER 85% for all vulnerability detectors used in this study, first extracts program slices from it and then constructs the showing good generalization for different GNN-based control- and data-dependence information. Compared with vulnerability detectors. prior works (e.g., DEEPWUKONG [6]), VULEXPLAINER only preserves vulnerability-triggering and vulnerability-dependent program path-level information, rather than that of the full II. BACKGROUND program.Thissignificantlyimprovestheanalysisefficiencyas A. GNN-based Vulnerability Detectors program paths contain a smaller number of code lines. Lever- aging the program slicing method, VULEXPLAINER captures Recently, GNNs have been utilized by security analysts more semantic information encompassed in code lines. As a and researchers in vulnerability detection tasks [9], [7], [8], result, it can provide more accurate explanation results than [6], [17], [18]. They presume the graph representation of the approaches only focusing on topological features. codes could better preserve critical semantic information The goal of VULEXPLAINER is to identify the root cause of vulnerability-related programs, compared with traditional ofthevulnerabilities.Arecentwork[14]suggeststhatthebug sequence-based representation. Typically, the most frequently trigger path is the key to locating and fixing a vulnerability. used graph representation is code property graph (CPG), Thus,toevaluatetheeffectivenessofourapproach,wepropose which is combined with abstract syntax tree (AST), control a new evaluation metric, vulnerability-triggering code line flow graph (CFG), control dependence graph (CDG), and coverage (or referred to as LC hereafter, to be detailed in data dependence graph (DDG). In addition, another graph Section V-B). We conduct multi-dimensional evaluations on representationprogramdependencegraph(PDG)iscomposed the effectiveness of VULEXPLAINER. In the first comparison ofCDGandDDG,whichcouldbedeemedasasubstructureof dimension, we apply VULEXPLAINER to interpret the outputs CPGandiswidelyusedinprogramslicing[19].Inthisstudy, offourstate-of-the-artgraphcoderepresentation-basedvulner- we mainly utilize PDG for slicing. Generally, the detection ability detectors, including DEEPWUKONG [6], REVEAL [7], phaseofaGNN-baseddetectorusuallyconsistsofthreesteps, IVDETECT [8], and DEVIGN [9]. All of these four detectors as shown in Figure 2: use program dependence graphs (PDGs, DEVIGN uses only (a) Parsing source code into a graph representation. A data dependence graph, not control dependence graph) as target source code fragment is typically a function or a slice. the code graph representation. We observe that VULEX- Here we utilize Joern [20] to dump the graph representations3 source code code graph vectorized graph Parsing tools 1 Embedding utils vec1 Well-trained GNN model 10 2 3 vec2 vec3 Prediction
4 vec4 5 6 vec5 vec6 Fig. 2: General detection phase of deep-learning-based vulnerability detectors with graph representations of the code fragment to support those GNN-based detec- etc. Among them, “2 – 6 – 7 – 11” is deemed the most tors (DEEPWUKONG [6], REVEAL [7], IVDETECT). critical one as both lines 2 (critical variable assignment) and (b) Embedding code graph into vectorized representation. line 11 (vulnerability trigger) are included. Inacodegraph,anodeusuallystandsforaprogramstatement TechnicalChallenges.Accordingtothisvulnerabilitylocating while an edge denotes a relationship (execution order or sample, the technical challenges for a general and automatic def-use) between two statements. Here, each node could be location of the detected vulnerability code are at least two- vectorized by DOC2VEC [21] or WORD2VEC [22]. Then the fold: vectorized graph data is generated by sequentially vectorizing • Challenge#1 Given a correctly detected vulnerable code all the contained nodes. by a GNN-based detector, there is a lack of an efficient (c) Using a well-trained GNN model to classify vectorized vulnerability locating approach that generates flow paths code graph. With vectorized graphs of code fragments and covering both vulnerability triggers and related critical their labels, a GNN model, such as Graph Convolutional variable assignments. Networks(GCN)andGatedGraphNeuralNetworks(GGNN), • Challenge#2 Given the generated flow paths, there is could be trained to detect vectorized graph data from target a lack of an efficient path selection mechanism that programs. identifies the most suitable path as the most reasonable final data flow for a detected vulnerability. B. Control and Data dependence relation To address the two challenges, we propose VULEXPLAINER In a PDG, a control-dependence edge S → S denotes thatautomaticallygeneratesfeasibleflowpathsfromthePDG i j whetherstatementS willbeexecuteddependingonconstraint derived from a code fragment, and rank them to select the j conditions in S . A data-dependence edge S′ → S′ means most reasonable path. The technical details of this framework i i j that a value defined at S′ is used in S′. And there are no are to be presented in Section IV. i j other statements redefining corresponding value among the path from S′ to S′. i j Source code Graph The control-dependence graph of a program can be deter- 0 char* data; 0 2 6 7 11 minedthroughthealgorithmpresentedbyCytronRetal[23]. 1 data = NULL; 1 8 11 While data dependence relations can be calculated through 2 data = (char*)malloc(50 * sizeof(char)); 2 3 if(data == NULL) { 3 8 10 reaching definition analysis. 4 exit(-1);} 5 data[0] = \0 ; 4 5 2 6 7 13 6 char* dataCopy=data; 6 8 9 III. ANEXAMPLEOFLOCATINGVULNERABILITY 87 c ch ha ar r* s od ua rt ca e= [d 1a 0t 0a ]C ;opy; 7 2 5 8 To illustrate the essential idea of our methodology, we use 9 memset(source, C , 100 - 1); ... 10 source[0] = \0 ; 9 a code fragment from SARD [24] as a toy example, as shown 11 strncpy(data, source, 100); 10 in Figure 3. It contains a buffer overflow vulnerability that 12 printLine(data); 13 free(data); 11 is triggered by copying more data (i.e., 100 bytes defined by Potential sink point 12 line 11 of the code fragment) than the maximum capacity No dependence- related Program dependence-related 13 2 6 7 11 of an array (i.e., 50 bytes defined by line 2). A GNN-based vulnerability detector only outputs the detection results as 1, indicating the code fragment is vulnerable (or 0 vice versa). Fig. 3: A example extracted from SARD. The target of the vulnerability locating task is to construct a control-anddata-dependencepath,orflowpathhereafter,that contains the vulnerability triggering code line and the critical IV. LOCATINGVULNERABILITYSTATEMENTSUSING assignment of vulnerability-related variables. To this end, we GNN-BASEDDETECTORS first convert the source code into a graph representation by By manually investigating the vulnerable and non- mapping the statements into nodes and then constructing the vulnerable code fragment samples in the existing public flow paths according to the dependence information among datasets respectively, we can always find code fragment thenodes. Fromthepaths,we selectonesthat satisfyourvul- pairs (i.e., one labeled as vulnerable and the other non- nerability locating target. Specifically, in our example shown vulnerable)thatarehighlysimilarexceptforthevulnerability- in Figure 3, there are multiple flow paths extracted from the triggeringandthevulnerability-fixingcodelines.Theyarecru- original code fragment, such as “8 – 11”, “2 – 6 – 7 – 13”, cial features utilized by the current GNN-based vulnerability4 Algorithm1Details.Inline2,thepathsetS forthecurrent GENERATE GRAPH (a).GENERATE PATHS (b).SELECT PATH programisinitialized asanemptyset.In line 3,thealgorithm source code code graph flow paths extractsPSPswiththegivencodegraph(SectionIV-B1).Then the algorithm generates flow paths for each PSP with the vectorizing identify PSP following steps. In line 5, we initialize the current traversed vectorized paths pathpwiththecorrespondingPSP.Theninline6,thecurrent 4 parsing vec1 vec1 PSP’s flow-path set is initialized as an empty set. In line 7, tool backward flowpathsaregeneratedwithaDFSalgorithm(tobeexplained slicing vec2 vec3 next). In line 8, we include all flow paths of the current PSP code graph vec4 vec4 flow paths to the path set S. 1 score
2 3 1 1 function The function DFS describes the process of the backward traversing algorithm when generating flow paths. In lines 14- 4 2 3 score1 score2 argmax 16, if the length of the current flow path p reaches the upper 5 6 4 4 limit,thenpwillbeappendedtothepathsetSandthefunction 1 2 4 will return. In lines 18-19, the algorithm extracts nodes on Fig. 4: Overview of VULEXPLAINER. which the last node n of p is dependent. In lines 20-22, if p cannot continue to extend, then p will be appended to S. Otherwise,inlines24-27,werepeatthisDFSprocessforeach detectors. Based on the insights drawn from the control- and node that n is dependent on. data-dependence between those vulnerability-triggering and vulnerability-fixing code lines, we propose VULEXPLAINER Algorithm 1 Slice Generation Algorithm. to facilitate the vulnerability code line locating of the GNN- Input: code graph G,max length of path k based detection results. Output: path set S 1: function GENERATESLICE(G,k) A. VULEXPLAINER Overview 2: S ← ∅ As shown in Figure 4, the overall framework of VULEX- 3: sink nodes ← ExtractSinkNodes(G) PLAINER consists of two modules: flow path generation from 4: for sink node ∈ sink nodes do the original code graph and critical path selection. 5: p← {sink node} Flow Path Generation. Given a vulnerable code fragment 6: S′ ←∅ represented as a graph with its control- and data-dependence 7: DFS(p, G, 1, k, S′) computed (in Figure 4(a)), VULEXPLAINER first identifies 8: Append all slice in S′ to S statements (i.e., nodes) in the program that might trigger the 9: end for vulnerability, denoted as potential sink points (PSPs). Next, 10: return S VULEXPLAINER iteratively traverses backward from a PSP 11: end function along a flow path in the program graph, until the source of 12: thePSP(e.g.,noderepresentingcriticalvariableassignment)is 13: function DFS(p,G,l,k,S) reached.Similarly,VULEXPLAINERgeneratesallthequalified 14: if l=k then flow paths from the graph, each ending with a PSP. 15: Append p to S FlowPathSelection.VULEXPLAINERfirstvectorizeseach 16: return flow path and computes an importance score correlated to 17: end if the vulnerability probability (in Figure 4(b)). Next, VULEX- 18: n← last node in p PLAINER selects the flow path with the highest importance 19: prec nodes ← ExtractPrecNodes(n, G) score as the vulnerability data flow. Note that we do not 20: if prec nodes is ∅ then directly train a classifier for the path selection as each path 21: Append p to S is regarded as a data flow rather than a code fragment. 22: return 23: end if 24: for prec node ∈ prec nodes do B. Flow Path Generation 25: Append prec node to p To generate flow paths from the original code graph (i.e., 26: DFS(p, G, 1 + 1, k, S) PDG), we utilize program slicing based on DLVD methods, 27: pop the last node in p which have been widely adopted by previous works such as 28: end for DEEPWUKONG, REVEAL, IVDETECT, DEVIGN. The slicing 29: end function principle is based on both control and data dependence of the PDG. More specifically, the detailed flow path generation 1) Potential Sink Points (PSPs): PSPs are statements that approach is described by the “GENERATESLICE” function arecriticallyrelatedtovulnerabilities.InAlgorithm1,theyare in Algorithm 1. It takes a code graph G and a path length extracted by the function “ExtractSinkNode” (line 3) which limitk(i.e.,toeffectivelyremovelengthypathsforsubsequent considers the following four types of PSPs in our program searching) as input. We detail the algorithm as follows. slicing.WeadoptthesamedefinitionproposedbyLietal[25].5 • Library/APIFunctionCall(FC).ThiskindofPSPcovers relationfornode“n”isrelatedtothevulnerability,asasource almostallvulnerabilitytypesexceptforintegeroverflow. code statement might contain multiple expressions among Different types of vulnerabilities are triggered by various which only one could trigger the vulnerability. Therefore, types of API calls. For example, OS command injection we only focus on the control and data dependence involving is usually triggered by APIs such as system and execl, key variables related to each PSP when extracting depen- while buffer overflow is normally triggered by data copy dent nodes. For illustration in Figure 5, our tool identified functions like memcpy. arithmeticoperation“CHAR ARRAY SIZE-1”whichmight • Array Usage (AU). This kind of PSP usually appears in triggerintegerunderflowinstatementS3.AlthoughS3isdata- memory errors. In this study, AU only covers the buffer dependent with S1 via the variable “connectSocket”, they do overflow vulnerability. For example, “data[i] = 1;” might not appear in arithmetic operations. We thus do not consider cause a buffer overflow. Note that we do not consider thedata-dependenceedge“S1- S3”whenperformingslicing. trivial cases such as array accesses with constant indexes For other nodes, we consider all dependent statements of the in this work. current node. • Pointer Usage (PU). Similar to AU, PU usually appears inmemoryerrors.Thisstudyonlycoversbufferoverflow C. Flow Path Selection vulnerability. • Arithmetic Expression (AE). This type of PSP is usually Among the flow paths, we aim to select one that can best an arithmetic expression like “a + 1” or “a++”. AE is locate the vulnerability-triggering statements based on the usually related to integer overflow and division-by-zero prediction results. The key intuition is that if a path contains vulnerabilities. Here we mainly focus on the former. boththePSP anditssourcenode,thepath shouldbeselected.
Note that we do not consider trivial cases such as self- For example, the path “2 – 6 – 7 – 11” in the example in incrementandself-decrementoperationswithconditional SectionIII.Ifthereismorethanonequalifiedpath,wefurther checks in this work. rankthembasedonthepathimportance(tobedetailedbelow) and select the one with the highest importance score. More formally, given a code graph G, we extract flow S1:connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); S2: char inputBuffer[CHAR_ARRAY_SIZE]; paths from it and vectorize each flow path. The process of connectSocket inputBuffer vectorizing one flow path is the same as that of detectors vectorizing the corresponding code graph. Then we compute S3: recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); the importance score for each flow path by treating each Fig. 5: An example of ignored data-dependence edges. vectorized flow path as a subgraph of the original code graph and feeding it into the well-trained GNN-based vulnerability detector. This process could be formally described as: p =Φ(vec(g)) (1) Backward:11 g 0 CPG 1 2 where g is a flow path extracted from G, Φ is one of the GNN-based vulnerability detectors. 2 Potential sink points: 6 Finally, we compute the importance score IS for each statement 11 g 3 (strncpy) path, measuring their contribution to the detector predicting 7 8 4 5 the corresponding code fragment. 6 11 IS =1−(Φ(vec(G))−p ) (2) g g 7 Suppose there are n flow paths after slicing G and denoted 8 Paths:11 as {g ,...,g ,...g }. The vulnerability data flow g is denoted 1 i n ∗ 9 {8} as: {7, 6, 2} 10 g∗ =argmaxIS (3) gi 11 12 Control flow edge flow paths V. EXPERIMENTALSETTINGS {8, 11} 13 Program dependence edge We evaluate the effectiveness of VULEXPLAINER for lo- {2, 6, 7, 11} cating vulnerability statements from the prediction results Fig. 6: An example to demonstrate how slicing works by of DEEPWUKONG, REVEAL, IVDETECT, and DEVIGN. The evaluation is conducted for detecting 8 of the top 30 vulnera- revisiting the code in Figure 3. bilities on CWE, comparing with five state-of-the-art explain- 2) Dependent Statements: The function “ExtractPrecN- ers for GNN. To this end, we outline the dataset used in this odes” (line 19) in Algorithm 1 establishes the dependence studyandtheprocessinvolvedinlabelingthem(SectionV-A). relation for the node “n” (i.e., identify nodes that the node Next, we provide a detailed exposition of the experimental “n” is dependent on). We find that not every dependence setup (Section V-B).6 TABLE I: Distribution of labeled samples from SARD. stringprep (char *in, size_t maxlen, Stringprep_profile_flags flags, VulnerabilityCategory codegraph #vulnerablesamples #safesamples #total const Stringprep_profile * profile) CWE20 XFG 58,350 174,250 232,600 { CPG 25,829 54,842 80,671 int rc; XFG 8,771 11,500 20,271 char *utf8 = NULL; CWE22 CPG 4,063 3,809 7,872 uint32_t *ucs4 = NULL; XFG 4,643 8,385 13,028 size_t ucs4len, maxucs4len, adducs4len = 50; CWE78 CPG 4,250 8,156 12,406 XFG 34,901 80,155 115,056 do CWE119 { CPG 21,662 40,466 62,128 uint32_t *newp; CWE125 XFG 6,147 12,469 18,616 CPG 4,315 7,907 12,222 free (ucs4); XFG 4,173 10,168 14,341 ucs4 = stringprep_utf8_to_ucs4 (in, -1, &ucs4len); CWE190 CPG 3,948 11,347 15,295 if (ucs4 == NULL) XFG 11,296 37,417 48,713 return STRINGPREP_ICONV_ERROR; CWE400 CPG 2,199 10,831 13,030 maxucs4len = ucs4len + adducs4len; XFG 23,493 49,718 73,211 newp = realloc (ucs4, maxucs4len * sizeof (uint32_t)); CWE787 if (!newp) CPG 15,977 27,378 43,355 return STRINGPREP_MALLOC_ERROR; XFG 151,774 384,062 535,836 TOTAL CPG 82,243 164,736 246,979 ucs4 = newp; rc = stringprep_4i (ucs4, &ucs4len, maxucs4len, flags, profile); adducs4len += 50; 2) Benchmark Dataset Processing.: The data collected } ... fromSARDisprocessedinthefollowingsteps.First,weparse Fig. 7: An example function where lines marked green are the functions of SARD programs into CPGs for REVEAL and added to fix the vulnerability. IVDETECT. We directly utilize the slice level XFGs (a sub- graph of the PDG) generated by DEEPWUKONG as they are availableontheirrepository[6].Thenwelabelanddeduplicate thoseCPGsand XFGsfollowingpreviousworks[8],[6].Any A. Dataset CPG or XFG containing one or more vulnerable statements will be labeled vulnerable and vice versa. Apart from that, 1) Target Vulnerabilities.: The dataset used here must sup- welabelthekeystatementsinthevulnerablesamplesasnode portfine-graineddetection,whichrequiresexplicitinformation indexes. on vulnerable code lines. Many flaw lines in real-world 3) Benchmark Dataset Distribution.: After the processing datasets like DEVIGN [9], REVEAL, Fan [26] are labeled stage, we collect 82,243 vulnerable CPGs and 164,736 non- with code change information extracted from committed ver- vulnerable CPGs from the SARD dataset, as listed in Table I. sion patches. As shown in Figure 7, a sample code with Wedownloadedthe XFGsdatasetsfrom DEEPWUKONG at1. vulnerability ID CVE-2015-2029 includes the vulnerability- After relabeling, we assemble 151,774 vulnerable XFGs and
fixing code lines that are marked as green. However, such a 384,062 non-vulnerable XFGs in total. labeling method only enables the detection of vulnerability- fixing lines, while leaving the vulnerability-triggering lines undetected.InthesameexampleinFigure7,thestatementsin B. Experimental Setup the tainted flow are marked as pink, which does not cover the 1) Experimental Configuration: The experiments are per- vulnerability-triggering code lines. In addition, a vulnerability formed on a machine with 2 NVIDIA GeForce GTX TitanX fixedatfunctionf mightbetriggeredatfunctionf .Insuch GPUs and Intel Xeon E5-2603 CPU operating at 1.70GHz. A B cases, f A would be labeled as vulnerable while f B as non- Weimplementthegraphneuralnetworksbasedon PYTORCH vulnerable.Evenworse,RolandCroftetal[27]havereportthe GEOMETRIC [29]. existenceofapproximately20-71%falsepositivevulnerability Initially, we conduct individual detection tasks for each samples in the real-world dataset. From the above, accurately vulnerability type, whereby we train a model for each of flagging vulnerable code lines in real-world datasets can be the eight vulnerability categories. For dataset splitting, we challenging. randomly choose 80% of the programs for training, 10% Since noised datasets could affect the performance of for validating, and the remaining 10% for detecting. For deep learning models [28], we assemble our dataset from modelimplementationwefollowDEEPWUKONG[30],IVDE- SARD [24], a synthetic vulnerability database. In the SARD TECT [31], DEVIGN [32] and REVEAL [33]. We utilize the dataset, each program (i.e., test case) could be related to one same hyper-parameters as detailed in the works. Note that or more CWE IDs, as a program could contain different types DEEPWUKONG utilizes three different types of GNN models ofvulnerability.Moreimportantly,thevulnerability-triggering including GCN, GAT, and k-GNNs. Considering their similar statements of each vulnerable program have been properly effectiveness,wefocusonthewidelyusedGCNforsimplicity marked. Our objective is to examine eight out of the 30 in this work. The neural networks are trained in batches, and most hazardous software flaws in C/C++ for the year 2021, we set the batch size to 64. In the training stage, ADAM [34] specifically focusing on CWE20, CWE22, CWE78, CWE119, is used for training and the learning rate is set to 0.001. All CWE125, CWE190, CWE400, and CWE787. We employ 1https://bupteducn-my.sharepoint.com/:u:/g/personal/jackiecheng bupt the same web crawler as DEEPWUKONG [6] to collect all edu cn/EalnVAYC8zZDgwhPmGJ034cBYNZ8zB7-mNSNm-a7oYXkcw?e= available programs. eRUc507 TABLE II: Detection performance of four detectors. TABLE III: Overall performance of VULEXPLAINER over Detector DeepWuKong IVDetect Reveal Devign eight types of vulnerability. Mean F1 0.95 0.97 0.95 0.93 CWE-ID 20 22 78 119 125 190 400 787 Mean ACC 0.97 0.98 0.97 0.95 Mean LC 0.84 0.92 0.98 0.87 0.97 0.90 0.89 0.88 involved neural networks are randomly initialized by Torch TABLE IV: Performance of VulExplainer on four detectors. initialization. method LC(k=3) LC(k=5) LC(k=7) For detection result explanation tasks, we follow DIG [35] DeepWuKong 0.93 0.94 0.94 to implement 5 state-of-art explaining methods: PGEX- PLAINER, GNNEXPLAINER, GRAD, DEEPLIFT, and GNN- Reveal 0.86 0.88 0.89 LRP. IVDetect 0.92 0.91 0.91 2) Evaluation Metrics: We first assess the effectiveness of Devign 0.87 0.90 0.90 four vulnerability detection tools with six commonly utilized metrics,includingaccuracy(ACC),falsepositiverate(FPR), false negative rate (FNR), recall rate (R), Precision (P), (i.e.,programstatements)ineachflowpathinourexperiments. F1 Score (F1). The simplified results are summarized in The parameter sparsity is calculated by 1− n where m and Table II, and the fully-detailed results are available in our m narethetotalnumbersofnodesinagraphandapathrespec- repository [16]. tively.Intuitively,sparsitycontrolshowevenlydistributedare To assess the efficacy of explanation methods as well as thenodeswithinthegraph.Morenodesconcentratedinfewer VULEXPLAINER, we propose metric Line Coverage, or LC. paths (i.e., relatively longer paths) results in lower sparsity. Note the evaluation metric only applies to the true positive The parameter k specifies the maximum number of nodes in samples which are both labeled and detected as vulnerable. a path, as mentioned in Algorithm 1. Taking both parameters LC isdefinedasfollows:givenaflowpathgofcodefragment C containing n vulnerable code lines, then LC = n where intoconsideration,themaxnumberofnodesMaxN inaflow m path is given by min(k,(1−sparsity)∗m). m(m≥n) represents the total number of code lines that are labeled as vulnerable in the dataset. LC is 1 if g contains From our manual analysis, we observe that the value of all vulnerable statements labeled in the dataset, LC is 0 if g sparsity has limited practical influence on the actual path length.Therefore,weadoptthefixedvalueof0.5forsimplic- contains no vulnerable statements labeled. ityinourlarge-scaleexperiment.Meanwhile,wealsoobserve Notethatwehaveconsideredusingfidelity[36]tomeasure that most vulnerable paths contain less than 7 nodes, we thus
theperformanceofexplainersandVULEXPLAINER.However, evaluate the explanation performance against k = 3,5,7 for there is a lack of a generalized and standard method for simplicity. calculating fidelity, causing huge discrepancies among the derived result derived from different methods. This renders it The overall explanation performance of VULEXPLAINER unreliable to utilize fidelity as one of the evaluation metrics. for each vulnerability type at k = 5 is averaged over four In addition, our goal is to locate and interpret the causes for vulnerability detectors, as listed in Table III. The overall thedetectedvulnerabilities,whichdoesnotnecessarilyrequire explanationperformanceofVULEXPLAINERforeachdetector constructing a subgraph that maximally retains the properties is average over the eight types of vulnerabilities, as listed in from the original graph. Table IV. In general, VULEXPLAINER attains encouraging outcomes. On average, the LC is above 90% for DEEP- VI. VULEXPLAINEREVALUATION WUKONG and IVDETECT, above 85% for REVEAL and DEVIGN. Our evaluation aims to answer the following two research 1) RQ1.1: Detection Results across Vulnerabilities: As questions: shown in Table III, VULEXPLAINER demonstrates varying RQ1 Can VULEXPLAINER accurately localize performance when locating different types of vulnerabilities. vulnerability-triggering code lines? In particular, It achieves the highest LC score (98%) for CWE-78 vulnera- we would like to further individually investigate bility, and relatively lower LC scores for CWE-20 (84%) and RQ1.1: can VULEXPLAINER perform consistently CWE-119(87%).Tobetterunderstandthereasonsbehindsuch across various types of vulnerabilities? RQ1.2: can variations, we conduct a manual review of several exceptional VULEXPLAINER perform consistently on different cases and identified the following three possible causes. graph-based vulnerability detectors? In other words, is • First,theselectedPSPsmightbeincomplete.Vulnerabil- the performance of VULEXPLAINER impacted by the ities could be triggered by various types of statements. choice of detectors? Certain vulnerabilities, such as CWE-78, can only be RQ2 Can VULEXPLAINER outperform existing explaining triggered by APIs related to system commands, making methods for GNN-based vulnerability detection? the vulnerability pattern comparatively straightforward. However, other kinds of vulnerabilities (e.g., buffer over- A. RQ1: The performance of VULEXPLAINER flows) may be triggered by a variety of statements, Overall Results. For the computation efficiency, we set two including memory-related APIs, array operations, and parameters, sparsity and k, to control the number of nodes pointer operations. This results in more PSPs in the code8 graph, and subsequently more interference during path fore although DEEPWUKONG might not surpass IVDETECT, generation and selection, which poses a challenge to VULEXPLAINER can still achieve better results on DEEP- our method. Additionally, our target PSP patterns might WUKONG. notbecomplete,potentiallyexcludingsomevulnerability types during the explanation. ANSWER: The performance of VULEXPLAINER is not • We leverage program slicing to generate flow paths strongly tied to the performance of the detector, as with the aim of preserving the vulnerability semantics. it achieves promising results across all four detectors. During this process, we filter out some control- & data- VULEXPLAINER performs better on DEEPWUKONG dependencerelationswithoutvariablesthatarepotentially than other detectors, as it can perform detection on relevant to vulnerabilities. Nonetheless, analyzing a large a more fine-grained level. number of paths using our approach could become chal- lenging, considering the exponentially expanding possi- B. RQ2: VULEXPLAINER VS. Existing Deep-learning-based bilities to be explored and parsed. Approaches • The deep learning-based detectors are not as reliable as To answer RQ2, we compare VULEXPLAINER with five we expect. In some cases, the output score from the representative node-based and edge-based explaining meth- detectorissignificantlylowerthanexpected,evenwhena ods, including GNNEXPLAINER [10], PGEXPLAINER [11], pathisstronglyrelatedtovulnerability.Suchunreliability GRAD [12], GNN-LRP and DEEPLIFT [15]. Here we de- could consequently impact the measured effectiveness note them as GE, PE, GR, GL, and DL respectively, and of VULEXPLAINER. This also indicates that traditional VULEXPLAINER as VE. We further summarize the technical evaluationmetricsmaynotfullycapturetheeffectiveness details for each method in our repository [16] for a complete of these detectors. reference. Nevertheless, VULEXPLAINER still exhibits high explana- 1) Results: As shown in Figure 8, when evaluated against tioneffectiveness acrossall typesofvulnerabilities coveredin the eight types of vulnerabilities using the evaluation metrics our evaluation. LC, VE surpasses all five explanation approaches in compar- ison. ANSWER: VULEXPLAINER demonstrates excellent Since the same trend in explainers’ performance can be performanceinautomaticallydeterminingcrucialstate- observedwhenthevalueofkisvaried,wepresentandanalyze ments in a code graph when a vulnerability is detected, the final results using k = 7 due to page constraints. Taking demonstrated by its ability to effectively explain the the CWE-20 as an example, when locating vulnerable lines predictions of detectors across eight different types based on the predictions of DEEPWUKONG, VE is roughly
of vulnerabilities. A few exceptional cases could be 30% higher than GL in terms of LC. As for CWE-125, when introduced by the selection of PSPs. locating vulnerable lines for REVEAL, GR only obtains 51% LC, while our approach achieves 96%. For IVDETECT, DL 2) RQ1.2: Comparison of Explaining Results on Different obtains only 4% LC while VE achieves 97%. Compared with Detectors.: The average detection performance of four de- GE, when locating vulnerable lines for DEVIGN on CWE- tectors over eight types of vulnerabilities is summarized in 787, VE achieves 91% LC, nearly 33% higher than that of Table II. GE. A similar pattern is observed for PE, with only 33% LC AccordingtothemetricsF1andACC,thedetectionperfor- achieved. mance is ranked as follows: IVDETECT > DEEPWUKONG = 2) Analysis: The experimental results suggest that solely REVEAL>DEVIGN.Incomparison,theaveragevulnerability relyingonnodeembeddingsandtopologicalstructuresofcode locating performance of VULEXPLAINER on the detection graphsisinsufficienttolocatetherootcauseofthevulnerable results of the four detectors is summarized in Table IV. In code fragment. terms of the evaluation metric LC, the explanation perfor- We conduct a case study on the example we use in Sec- mance ranking of VULEXPLAINER on the four detectors is tion III, and the result is shown in Figure 9. We can observe DEEPWUKONG > IVDETECT > DEVIGN > REVEAL. that PE, GR, and GL do not succeed in identifying the state- Comparingtheresults,wefindthattheperformanceofvul- ment that triggers the vulnerability. And GE, DL are unable nerabilitydetectorsandthatoftheexplainersarenotnecessar- tocapturetheconnectionsbetweenthevulnerability-triggering ily aligned. For example, DEEPWUKONG performs relatively statement and other vulnerability-relevant statements, despite better for explanation than detection, as the adopted slice- recognizing that statement “11” is vulnerability-relevant. VE level detection technique fits better with VULEXPLAINER. In determineswhetheracodefragmentisvulnerablebyselecting particular, an XFG (slice) used in DEEPWUKONG comprises a flow path including both potential vulnerability-triggering multiple statements related to a specific point of interest in statements and those passing along tainted data to them. the program, which is more fine-grained than approaches ANSWER: VULEXPLAINER surpasses other explana- operating at the function level. Additionally, the XFG uti- tion methods as it examines the semantic information lized in DEEPWUKONG typically incorporates interprocedu- of statements and the relationships among them in a ral information. Thus, accurately retain code characteristics, program-dependent context. including control and data flows, exclusively for code state- mentsthatarepertinenttotheidentifiedvulnerabilities.There-9 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 GE 0.21 0.34 0.41 0.39 0.49 0.57 0.36 0.45 0.52 0.24 0.41 0.47 0.24 0.41 0.48 0.34 0.44 0.47 0.25 0.4 0.48 0.23 0.38 0.45 PE 0.21 0.3 0.35 0.05 0.1 0.11 0.26 0.4 0.49 0.29 0.43 0.48 0.63 0.73 0.78 0.09 0.27 0.3 0.05 0.19 0.22 0.14 0.24 0.28 DL 0.2 0.31 0.37 0.33 0.6 0.7 0.05 0.14 0.26 0.14 0.29 0.35 0.07 0.17 0.25 0.38 0.59 0.63 0.46 0.6 0.67 0.12 0.27 0.34 GR 0.54 0.68 0.76 0.34 0.44 0.5 0.16 0.29 0.32 0.77 0.86 0.92 0.71 0.78 0.81 0.43 0.58 0.63 0.45 0.68 0.85 0.72 0.85 0.89 GL 0.41 0.57 0.6 0.67 0.68 0.86 0.32 0.42 0.54 0.43 0.63 0.69 0.24 0.53 0.62 0.11 0.2 0.22 0.46 0.67 0.76 0.47 0.67 0.76 VE 0.88 0.9 0.91 0.99 0.95 0.97 0.97 0.98 0.98 0.87 0.9 0.9 0.98 0.98 0.98 0.97 0.98 0.98 0.88 0.95 0.95 0.87 0.85 0.85 (a.1) CWE20 (a.2) CWE22 (a.3) CWE78 (a.4) CWE119 (a.5) CWE125 (a.6) CWE190 (a.7) CWE400 (a.8) CWE787 (a) Experimental results for DeepWuKong k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 GE 0.28 0.43 0.47 0.28 0.33 0.38 0.2 0.26 0.29 0.35 0.53 0.57 0.31 0.5 0.61 0.51 0.59 0.6 0.32 0.46 0.51 0.33 0.52 0.58 PE 0.52 0.67 0.72 0.26 0.27 0.27 0.08 0.1 0.12 0.34 0.47 0.53 0.49 0.68 0.74 0.71 0.77 0.79 0.36 0.44 0.51 0.37 0.47 0.51 DL 0.39 0.5 0.56 0.17 0.23 0.29 0.52 0.67 0.72 0.46 0.73 0.77 0.27 0.34 0.38 0.52 0.58 0.58 0.34 0.47 0.55 0.34 0.51 0.54 GR 0.45 0.58 0.61 0.33 0.33 0.34 0.67 0.73 0.76 0.65 0.78 0.81 0.36 0.48 0.51 0.7 0.79 0.81 0.41 0.62 0.65 0.49 0.65 0.7
GL 0.33 0.45 0.51 0.33 0.38 0.44 0.44 0.52 0.55 0.37 0.51 0.56 0.33 0.43 0.52 0.33 0.44 0.45 0.31 0.41 0.47 0.29 0.47 0.49 VE 0.78 0.8 0.81 0.95 0.91 0.91 0.98 0.99 0.99 0.81 0.86 0.86 0.94 0.95 0.96 0.82 0.86 0.86 0.76 0.82 0.83 0.84 0.86 0.86 (b.1) CWE20 (b.2) CWE22 (b.3) CWE78 (b.4) CWE119 (b.5) CWE125 (b.6) CWE190 (b.7) CWE400 (b.8) CWE787 (b) Experimental results for Reveal k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 GE 0.32 0.47 0.54 0.37 0.44 0.48 0.17 0.22 0.24 0.39 0.59 0.64 0.41 0.66 0.74 0.47 0.58 0.61 0.36 0.52 0.6 0.44 0.65 0.7 PE 0.28 0.42 0.48 0.2 0.21 0.23 0.48 0.51 0.52 0.31 0.5 0.55 0.29 0.52 0.63 0.35 0.48 0.49 0.63 0.73 0.79 0.47 0.66 0.69 DL 0.19 0.26 0.3 0.33 0.62 0.63 0.14 0.28 0.53 0.04 0.08 0.09 0.02 0.04 0.04 0.09 0.19 0.21 0.1 0.26 0.34 0.03 0.05 0.06 GR 0.47 0.64 0.71 0.54 0.76 0.79 0.23 0.29 0.31 0.35 0.6 0.68 0.29 0.53 0.74 0.64 0.77 0.78 0.78 0.86 0.9 0.42 0.71 0.77 GL 0.28 0.5 0.57 0.37 0.45 0.49 0.05 0.11 0.11 0.13 0.32 0.4 0.06 0.15 0.22 0.13 0.22 0.25 0.21 0.36 0.48 0.21 0.44 0.49 VE 0.84 0.84 0.84 0.87 0.86 0.86 0.98 0.98 0.99 0.88 0.88 0.89 0.97 0.97 0.97 0.92 0.91 0.91 0.92 0.92 0.92 0.88 0.89 0.89 (c.1) CWE20 (c.2) CWE22 (c.3) CWE78 (c.4) CWE119 (c.5) CWE125 (c.6) CWE190 (c.7) CWE400 (c.8) CWE787 (c) Experimental results for IVDetect k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 k = 3 k = 5 k = 7 GE 0.29 0.42 0.48 0.33 0.41 0.55 0.29 0.35 0.4 0.33 0.49 0.54 0.33 0.51 0.62 0.45 0.57 0.59 0.33 0.54 0.58 0.38 0.54 0.58 PE 0.53 0.67 0.71 0.2 0.21 0.23 0.28 0.5 0.6 0.48 0.67 0.7 0.1 0.36 0.51 0.64 0.81 0.82 0.04 0.15 0.17 0.21 0.29 0.33 DL 0.21 0.28 0.33 0.32 0.44 0.48 0.12 0.14 0.14 0.27 0.43 0.49 0.07 0.14 0.3 0.47 0.61 0.62 0.28 0.34 0.48 0.15 0.21 0.24 GR 0.55 0.69 0.76 0.18 0.21 0.22 0.1 0.11 0.11 0.67 0.81 0.86 0.39 0.64 0.73 0.73 0.84 0.84 0.65 0.67 0.71 0.65 0.81 0.85 GL 0.39 0.49 0.54 0.36 0.42 0.51 0.05 0.06 0.06 0.36 0.55 0.6 0.35 0.57 0.64 0.55 0.67 0.69 0.37 0.53 0.6 0.39 0.57 0.61 VE 0.8 0.81 0.81 0.96 0.97 0.97 0.95 0.96 0.95 0.86 0.87 0.87 0.87 0.96 0.97 0.83 0.86 0.86 0.84 0.87 0.86 0.88 0.9 0.91 (d.1) CWE20 (d.2) CWE22 (d.3) CWE78 (d.4) CWE119 (d.5) CWE125 (d.6) CWE190 (d.7) CWE400 (d.8) CWE787 (d) Experimental results for Devign 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 Fig. 8: Detailed experimental results on four detectors. Second, our framework performs program slicing using key Source code Graph Explaining results library API calls, array or pointer operations, and operator 0 char* data; 0 VE 2 6 7 11 statementsasPSPs.AsmentionedinSectionVI-A1,implying 1 data = NULL; 1 2 data = (char*)malloc(50 * sizeof(char)); 2 that certain corner cases might be neglected. In addition, 3 if(data == NULL) { 3 PE 3 5 6 7 13 it could also introduce irrelevant statements as sink points. 4 exit(-1);} 4 5 One way to enhance our methodology is to detect additional 5 data[0] = \0 ; 6 GE 0 1 10 11 12 supplementarytypesofPSPpatterns,andsubsequentlyscreen 6 char* dataCopy=data; 7 out extraneous sink points to diminish potential inaccuracies. 7 char* data=dataCopy; 8 8 char source[100]; GR 3 5 6 7 9 Thisrequiresextrainsightsintohowreal-worldvulnerabilities 9 9 memset(source, C , 100 - 1); are triggered and how they are fixed. We only consider ana- 10 10 source[0] = \0 ; DL 2 7 8 11 13 lyzingPSPshere,althoughitisapromisingdiagonalresearch 11 strncpy(data, source, 100); 11 direction to further analyze potential source points where the 12 printLine(data); 12 13 free(data); 13 GL 1 2 5 6 7 data related to vulnerabilities are input to the programs. Third,ourexperimentsarelimitedtoeightvulnerabilitytypes in C/C++ programs. Nonetheless, our methodology can be effortlessly expanded to encompass additional source-sink Fig. 9: Vulnerability locating results by different explainers vulnerabilities and other programming languages.
for the prediction of REVEAL in the motivating example. Fourth,ourapproachonlyconsiderslocatingvulnerablestate- VII. THREATSTOVALIDITY mentsbasedonfourgraph-basedvulnerabilitydetectors.How- ever, our approach is easily applicable to other detectors, and First, we only conduct experiments on the SARD dataset, potentially to other program analysis tasks. which contains synthetic and academic programs, but it may not be representative of real-world software products. We have discussed the problems in existing real-world datasets in VIII. RELATEDWORK section V-A. It remains an open problem to generate reliable Conventional static analysis tools. Several conventional datasets on a fine-grained granularity. static program analysis frameworks(e.g. CLANG STATIC AN-10 ALYZER [5], INFER [4], SVF [2], MALWUKONG [37]) have a customized neural network to predict relevance to vul- been designed to detect vulnerabilities or identify malicious nerabilities. LineVul [49] analyses each function with fine- behaviorsinsoftwaresystems.CLANGSTATICANALYZER[5] tuned CodeBert and ranks each statement based on attention isaconstraint-basedstaticanalysistoolthatperformssymbolic scores, a higher attention score implies stronger relation with executiontoexplorepathsintheprogram’scontrol-flowgraph vulnerability. While IVDETECT [8] attain this goal by first anddetectpotentialbugs.While INFER [4]isastaticprogram identifyingvulnerabilitiesatthesourcecodelevelandutilizing analysis tool for detecting security issues such as null-pointer existingexplanationapproach GNNEXPLAINER togeneratea dereferenceandmemoryleaksbasedonabstractinterpretation. subgraph of the PDG to locate vulnerabilities in the function SVF [2] first parses a program into a sparse value-flow subsequently. However, serveral recent studies [50], [51], graph(SVFG)thenconductpath-sensitivesource-sinkanalysis [52] have substantiated the inefficiency of current explanation by traversing SVFG. The effect of conventional approaches approaches in vulnerability detection.proved the inefficiency depends on two factors: static analysis theories and security of current explanation approaches in vulnerability detection. rules. static analysis theories include but are not limited to, Machine-learning for software engineering. In addition to parsing code into abstract structures (such as SVFG), where vulnerability detection, deep learning has made significant a better abstract structure facilitates the development of more progress in recent years in software engineering tasks such as sophisticated rules for detecting vulnerabilities. The effective- codeclonedetectionandcodeunderstanding,Themaindiffer- ness of detection rules depends on the expertise of the person ence between these methods lies in the different vectorization who writes the rules. The quantity of rules is restricted, and processes proposed for their specific tasks. The vectorizing it is impossible to encompass all of the vulnerability patterns, pipelinescanbecategorizedintotokens-based[53],[54],[55], which frequently results in high rates of false positives and [56],ASTs-based[57],[58],[59],[60]andgraphs-based[61], false negatives when analyzing intricate programs. [62], [63], [64], [65], [66]. Complex vectorizing pipelines Deep learning based vulnerability detection. Compared to often yield better results on specific tasks, but also rely on conventional static analysis, another field is machine/deep- more precise program analysis theories. learning-based analysis [38], [39], [40]. DeepBugs [41] rep- resents code via text vector for detecting name-based bugs. IX. CONCLUSION VGDETECTOR [42] uses control flow graph and graph con- volutional network to detect control-flow-related vulnerabili- In this paper, we present VULEXPLAINER, a new method ties. In this field, Devign [9] and REVEAL [7] utilize graph to locate vulnerable statements based on the predictions of representations to represent source code to detect vulnera- GP-based vulnerability detectors by analyzing semantic in- bilities. They aim to pinpoint bugs at the function level. formation in statements of input programs and the program- VULDEEPECKER [43] applies code embedding using data- dependence relationship between those statements. VULEX- flow information of a program for detecting resource man- PLAINER first performs program slicing to extract the flow agement errors and buffer overflows. SYSEVR [25] and pathsofacodefragment.Eachflowpathendswithapotential muVULDEEPECKER [44] extend VULDEEPECKER by com- sink point (PSP) in the code. After program slicing, VULEX- bining both control and data flow and different Recurrent PLAINER utilizes a score function to compute an importance neural networks(RNN) to detect various types of vulnera- score for each path and select the path with the highest score bility. DEEPWUKONG [6] utilizes program slicing methods as the explanation of the vulnerability data flow. We have to generate code fragments that are vectorized to apply the applied VULEXPLAINER for 8 of the 30 most dangerous GNN model for classification. Hao et al. [45] extend CFG C/C++ vulnerabilities, and demonstrate that VULEXPLAINER in the domain of exception handling, subsequently leveraging outperforms several state-of-the-art explainers for GNN in the this extension to enhance the detection capability of existing vulnerability detection task. DL-based detectors for exception-handling bugs. W Zheng et al. [17] combine DDG, CDG, and function call dependency graph (FCDG) into slice property graph (SPG), which is
materialized into the implementation of the detection tool vulspg.BinYuanetal.[46]constructabehaviorgraphforeach function and implement VulBG to enhance the performance of DL-based detectors by behavior graphs. All these solutions can only detect vulnerabilities on coarse granularity, and they could only tell whether a given code fragment is vulnerable. Fine-grained vulnerability detection. On the basis of deep learning vulnerability detection, fine-grained vulnerability de- tection has received increasing attention in recent years. More recently, Zou et al. [47] proposes an explanation framework to select key tokens in code gadgets generated by VULDEEP- ECKER and SeVCs generated by SYSEVR to locate the vulnerable lines. VULDEELOCATOR [48] compiles source codes into LLVM IRs, performs program slicing, and uses11 REFERENCES [24] Software Assurance Reference Dataset, 2017. https://samate.nist.gov/ SARD/index.php. [1] AmericanInformationTechnologyLaboratory. NATIONALVULNER- [25] ZhenLi,DeqingZou,ShouhuaiXu,HaiJin,YaweiZhu,andZhaoxuan ABILITYDATABASE,2020. https://nvd.nist.gov/. Chen. Sysevr:Aframeworkforusingdeeplearningtodetectsoftware [2] Yulei Sui and Jingling Xue. SVF: Interprocedural static value-flow vulnerabilities. IEEETransactionsonDependableandSecureComput- analysisinLLVM. InCC’16,pages265–266,2016. ing,pages1–1,2021. [3] Checkmarx,2020. https://www.checkmarx.com/. [26] JiahaoFan,YiLi,ShaohuaWang,andTienNNguyen. Ac/c++code [4] Infer,2020. https://fbinfer.com/. vulnerabilitydatasetwithcodechangesandcvesummaries.InMSR’20: [5] Clang static analyzer, 2020. https://clang-analyzer.llvm.org/scan-build. 17thInternationalConferenceonMiningSoftwareRepositories,2020. html. [27] Roland Croft, M. Ali Babar, and Mehdi Kholoosi. Data quality for [6] Xiao Cheng, Haoyu Wang, Jiayi Hua, Guoai Xu, and Yulei Sui. softwarevulnerabilitydatasets,2023. Deepwukong: Statically detecting software vulnerabilities using deep [28] XuNie,NingkeLi,KailongWang,ShangguangWang,XiapuLuo,and graphneuralnetwork. ACMTrans.Softw.Eng.Methodol.,30(3),2021. HaoyuWang. Understandingandtacklinglabelerrorsindeeplearning- [7] SaikatChakraborty,RahulKrishna,YangruiboDing,andBaishakhiRay. basedvulnerabilitydetection(experiencepaper). InProceedingsofthe Deep learning based vulnerability detection: Are we there yet? arXiv 32ndACMSIGSOFTInternationalSymposiumonSoftwareTestingand preprintarXiv:2009.07235,2020. Analysis,pages52–63,2023. [8] Y. Li, S. Wang, and T. N. Nguyen. Vulnerability detection with fine- [29] MatthiasFeyandJanE.Lenssen.Fastgraphrepresentationlearningwith grainedinterpretations. 2021. PyTorchGeometric. InICLRWorkshoponRepresentationLearningon [9] YaqinZhou,ShangqingLiu,JingKaiSiow,XiaoningDu,andYangLiu. GraphsandManifolds,2019. Devign:Effectivevulnerabilityidentificationbylearningcomprehensive [30] Cheng,XiaoandWang,HaoyuandHua,JiayiandXu,GuoaiandSui, program semantics via graph neural networks. In Hanna M. Wallach, Yulei. https://github.com/jumormt/DeepWukong,2021. Hugo Larochelle, Alina Beygelzimer, Florence d’Alche´-Buc, Emily B. [31] Yi Li, Shaohua Wang, Tien N. Nguyen. https://github.com/ Fox, and Roman Garnett, editors, Advances in Neural Information vulnerabilitydetection/VulnerabilityDetectionResearch,2021. ProcessingSystems32:AnnualConferenceonNeuralInformationPro- [32] Yaqin Zhou and Shangqing Liu and Jing Kai Siow and Xiaon- cessingSystems2019,NeurIPS2019,December8-14,2019,Vancouver, ing Du and Yang Liu. https://github.com/vulnerabilitydetection/ BC,Canada,pages10197–10207,2019. VulnerabilityDetectionResearch,2019. [10] R.Ying,D.Bourgeois,J.You,M.Zitnik,andJ.Leskovec.Gnnexplainer: [33] Chakraborty,SaikatandKrishna,RahulandDing,YangruiboandRay, Generatingexplanationsforgraphneuralnetworks. Advancesinneural Baishakhi. https://github.com/VulDetProject/ReVeal,2020. informationprocessingsystems,32:9240–9251,2019. [34] Diederik P. Kingma and Jimmy Ba. Adam: A method for stochastic [11] D. Luo, W. Cheng, D. Xu, W. Yu, and .X. Zhang. Parameterized optimization. InYoshuaBengioandYannLeCun,editors,3rdInterna- explainerforgraphneuralnetwork. 2020. tionalConferenceonLearningRepresentations,ICLR2015,SanDiego, [12] P. E. Pope, S. Kolouri, M. Rostami, C. E. Martin, and H. Hoffmann. CA,USA,May7-9,2015,ConferenceTrackProceedings,2015. Explainabilitymethodsforgraphconvolutionalneuralnetworks.In2019 [35] Meng Liu, Youzhi Luo, Limei Wang, Yaochen Xie, Hao Yuan, Shurui IEEE/CVF Conference on Computer Vision and Pattern Recognition Gui,HaiyangYu,ZhaoXu,JingtunZhang,YiLiu,KeqiangYan,Haoran (CVPR),2020. Liu, Cong Fu, Bora M Oztekin, Xuan Zhang, and Shuiwang Ji. DIG: [13] T.Schnake,O.Eberle,J.Lederer,S.Nakajima,KTSchu¨tt,KRMu¨ller, Aturnkeylibraryfordivingintographdeeplearningresearch. Journal andG.Montavon. Higher-orderexplanationsofgraphneuralnetworks ofMachineLearningResearch,22(240):1–9,2021.
viarelevantwalks. 2020. [36] H. Yuan, H. Yu, S. Gui, and S. Ji. Explainability in graph neural [14] Xiao Cheng, Xu Nie, Ningke Li, Haoyu Wang, Zheng Zheng, and networks:Ataxonomicsurvey. 2020. Yulei Sui. How about bug-triggering paths? - understanding and [37] NingkeLi,ShenaoWang,MingxiFeng,KailongWang,MeizhenWang, characterizinglearning-basedvulnerabilitydetectors.IEEETransactions andHaoyuWang. Malwukong:Towardsfast,accurate,andmultilingual onDependableandSecureComputing,pages1–18,2022. detection of malicious code poisoning in oss supply chains. In 2023 [15] Avanti Shrikumar, Peyton Greenside, and Anshul Kundaje. Learning 38th IEEE/ACM International Conference on Automated Software En- importantfeaturesthroughpropagatingactivationdifferences. InDoina gineering(ASE),pages1993–2005.IEEE,2023. PrecupandYeeWhyeTeh,editors,Proceedingsofthe34thInternational [38] StephanNeuhausandThomasZimmermann. Thebeautyandthebeast: ConferenceonMachineLearning,volume70ofProceedingsofMachine Vulnerabilities in red hat’s packages. In In Proceedings of the 2009 LearningResearch,pages3145–3153.PMLR,06–11Aug2017. USENIXAnnualTechnicalConference(USENIXATC,2009. [16] Dataset Repository. https://anonymous.4open.science/r/ [39] Gustavo Grieco, Guillermo Luis Grinblat, Lucas Uzal, Sanjay Rawat, VulExplainerExp-84ED,2023. Josselin Feist, and Laurent Mounier. Toward large-scale vulnerability [17] Weining Zheng, Yuan Jiang, and Xiaohong Su. Vu1spg: Vulnerability discovery using machine learning. In Proceedings of the Sixth ACM detectionbasedonslicepropertygraphrepresentationlearning.In2021 ConferenceonDataandApplicationSecurityandPrivacy,CODASPY IEEE32ndInternationalSymposiumonSoftwareReliabilityEngineer- ’16,pages85–96,NewYork,NY,USA,2016.ACM. ing(ISSRE),pages457–467.IEEE,2021. [40] Hua Yan, Yulei Sui, Shiping Chen, and Jingling Xue. Machine- [18] X. Cheng, H. Wang, J. Hua, M. Zhang, and Y. Sui. Static detection learning-guided typestate analysis for static use-after-free detection. ofcontrol-flow-relatedvulnerabilitiesusinggraphembedding. In2019 In Proceedings of the 33rd Annual Computer Security Applications 24th International Conference on Engineering of Complex Computer Conference, ACSAC 2017, page 42–54, New York, NY, USA, 2017. Systems(ICECCS),2019. AssociationforComputingMachinery. [19] MarkWeiser. Programslicing. InProceedingsofthe5thInternational [41] Michael Pradel and Koushik Sen. Deepbugs: A learning ap- Conference on Software Engineering, ICSE ’81, page 439–449. IEEE proach to name-based bug detection. Proc. ACM Program. Lang., Press,1981. 2(OOPSLA):147:1–147:25,October2018. [20] F. Yamaguchi, N. Golde, D. Arp, and K. Rieck. Modeling and [42] X.Cheng,H.Wang,J.Hua,M.Zhang,G.Xu,L.Yi,andY.Sui. Static discovering vulnerabilities with code property graphs. In 2014 IEEE detectionofcontrol-flow-relatedvulnerabilitiesusinggraphembedding. SymposiumonSecurityandPrivacy(SP),pages590–604,LosAlamitos, In 2019 24th International Conference on Engineering of Complex CA,USA,may2014.IEEEComputerSociety. ComputerSystems(ICECCS),pages41–50,Nov2019. [21] QuocV.LeandTomasMikolov.Distributedrepresentationsofsentences [43] ZhenLi,DeqingZou,ShouhuaiXu,XinyuOu,HaiJin,SujuanWang, anddocuments.InICML,volume32ofJMLRWorkshopandConference Zhijun Deng, and Yuyi Zhong. Vuldeepecker: A deep learning-based Proceedings,pages1188–1196.JMLR.org,2014. systemforvulnerabilitydetection. TheNetworkandDistributedSystem [22] Tomas Mikolov, Ilya Sutskever, Kai Chen, Greg Corrado, and Jeffrey SecuritySymposium(NDSS),2018. Dean. Distributed representations of words and phrases and their [44] DeqingZou,SujuanWang,ShouhuaiXu,ZhenLi,andHaiJin. compositionality. In Proceedings of the 26th International Conference muvuldeepecker: A deep learning-based system for multiclass vul- onNeuralInformationProcessingSystems-Volume2,NIPS’13,pages nerability detection. IEEE Transactions on Dependable and Secure 3111–3119,USA,2013.CurranAssociatesInc. Computing,18(5):2224–2236,2021. [23] Ron Cytron, Jeanne Ferrante, Barry K Rosen, Mark N Wegman, and [45] HaoZhang,JiLuo,MengzeHu,JunYan,JianZhang,andZongyanQiu. FKennethZadeck. Efficientlycomputingstaticsingleassignmentform Detectingexceptionhandlingbugsinc++programs.In2023IEEE/ACM andthecontroldependencegraph. ACMTransactionsonProgramming 45th International Conference on Software Engineering (ICSE), pages LanguagesandSystems(TOPLAS),13(4):451–490,1991. 1084–1095.IEEE,2023.12 [46] Bin Yuan, Yifan Lu, Yilin Fang, Yueming Wu, Deqing Zou, Zhen KnowledgeDiscoveryandDataMining,volume2006,pages872–881, Li, Zhi Li, and Hai Jin. Enhancing deep learning-based vulnerability 012006. detection by building behavior graph model. In 2023 IEEE/ACM 45th [66] Yulei Sui, Xiao Cheng, Guanqin Zhang, and Haoyu Wang. Flow2vec: InternationalConferenceonSoftwareEngineering(ICSE),pages2262– Value-flow-basedprecisecodeembedding. Proc.ACMProgram.Lang., 2274.IEEE,2023. 4(OOPSLA),November2020. [47] DeqingZou,YaweiZhu,HaiJin,HengkaiYe,YZhu,HYe,Shouhuai
Xu,andZhenLi.Interpretingdeeplearning-basedvulnerabilitydetector predictionsbasedonheuristicsearching.ACMTransactionsonSoftware EngineeringandMethodology,30,082020. [48] Zhen Li, Deqing Zou, Shouhuai Xu, Zhaoxuan Chen, Yawei Zhu, and HaiJin.Vuldeelocator:Adeeplearning-basedfine-grainedvulnerability detector. IEEE Transactions on Dependable and Secure Computing, PP:1–1,042021. [49] Michael Fu and Chakkrit Tantithamthavorn. Linevul: a transformer- based line-level vulnerability prediction. In Proceedings of the 19th InternationalConferenceonMiningSoftwareRepositories,pages608– 620,2022. [50] TomGanz,MartinHa¨rterich,AlexanderWarnecke,andKonradRieck. Explaining graph neural networks for vulnerability discovery. In Proceedings of the 14th ACM Workshop on Artificial Intelligence and Security,pages145–156,2021. [51] YutaoHu,SuyuanWang,WenkeLi,JunruPeng,YuemingWu,Deqing Zou,andHaiJin.Interpretersforgnn-basedvulnerabilitydetection:Are wethereyet? InProceedingsofthe32ndACMSIGSOFTInternational SymposiumonSoftwareTestingandAnalysis,pages1407–1419,2023. [52] BaijunCheng,ShengmingZhao,KailongWang,MeizhenWang,Guang- dong Bai, Ruitao Feng, Yao Guo, Lei Ma, and Haoyu Wang. Beyond fidelity: Explaining vulnerability localization of learning-based detec- tors,2023. [53] T. Kamiya, S. Kusumoto, and K. Inoue. Ccfinder: a multilinguistic token-based code clone detection system for large scale source code. IEEETransactionsonSoftwareEngineering,28(7):654–670,2002. [54] Z.Li,S.Lu,S.Myagmar,andY.Zhou. Cp-miner:findingcopy-paste and related bugs in large-scale software code. IEEE Transactions on SoftwareEngineering,32(3):176–192,March2006. [55] H. Sajnani and C. Lopes. A parallel and efficient approach to large scaleclonedetection. In20137thInternationalWorkshoponSoftware Clones(IWSC),pages46–52,May2013. [56] HiteshSajnani,VaibhavSaini,JeffreySvajlenko,ChanchalK.Roy,and Cristina V. Lopes. Sourcerercc: Scaling code clone detection to big- code. InProceedingsofthe38thInternationalConferenceonSoftware Engineering,ICSE’16,pages1157–1168,NewYork,NY,USA,2016. ACM. [57] Jian Zhang, Xu Wang, Hongyu Zhang, Hailong Sun, Kaixuan Wang, and Xudong Liu. A novel neural source code representation based on abstractsyntaxtree.InProceedingsofthe41stInternationalConference on Software Engineering, ICSE ’19, pages 783–794, Piscataway, NJ, USA,2019.IEEEPress. [58] SongWang,TaiyueLiu,andLinTan. Automaticallylearningsemantic featuresfordefectprediction. InProceedingsofthe38thInternational Conference on Software Engineering, ICSE ’16, pages 297–308, New York,NY,USA,2016.ACM. [59] Uri Alon, Meital Zilberstein, Omer Levy, and Eran Yahav. Code2vec: Learning distributed representations of code. Proc. ACM Program. Lang.,3(POPL):40:1–40:29,January2019. [60] Miltiadis Allamanis, Marc Brockschmidt, and Mahmoud Khademi. Learning to represent programs with graphs. CoRR, abs/1711.00740, 2017. [61] Kai Chen, Peng Liu, and Yingjun Zhang. Achieving accuracy and scalability simultaneously in detecting application clones on android markets. In Proceedings of the 36th International Conference on SoftwareEngineering,ICSE2014,pages175–186,NewYork,NY,USA, 2014.ACM. [62] Mark Gabel, Lingxiao Jiang, and Zhendong Su. Scalable detection of semantic clones. In Proceedings of the 30th International Conference on Software Engineering, ICSE ’08, pages 321–330, New York, NY, USA,2008.ACM. [63] Raghavan Komondoor and Susan Horwitz. Using slicing to identify duplication in source code. In Patrick Cousot, editor, Static Analysis, pages40–56,Berlin,Heidelberg,2001.SpringerBerlinHeidelberg. [64] JensKrinke. Identifyingsimilarcodewithprogramdependencegraphs. InProceedingsoftheEighthWorkingConferenceonReverseEngineer- ing(WCRE’01),WCRE’01,pages301–,Washington,DC,USA,2001. IEEEComputerSociety. [65] Chao Liu, Fen Chen, Jiawei Han, and Philip Yu. Gplag: Detection of software plagiarism by program dependence graph analysis. In Proceedings of the 12th ACM SIGKDD International Conference on
2401.07466 Your Instructions Are Not Always Helpful: Assessing the Efficacy of Instruction Fine-tuning for Software Vulnerability Detection ImamNurBaniYusuf LingxiaoJiang SingaporeManagementUniversity SingaporeManagementUniversity imamy.2020@smu.edu.sg lxjiang@smu.edu.sg Abstract Zhanetal.,2021). However,thesetechniquessuf- fer from false positives (i.e., detect benign code Software,whilebeneficial,posespotentialcy- as vulnerable) or false negatives (i.e., miss many bersecurity risks due to inherent vulnerabili- vulnerabilities) (Chakraborty et al., 2022). Ma- ties. Detectingthesevulnerabilitiesiscrucial, chinelearninghasbeenproposedasanalternative anddeeplearninghasshownpromiseasanef- (Narayananetal.,2014;Liuetal.,2015;Maetal., fective tool for this task due to its ability to 2016),butitrequiresextensivefeatureengineering. perform well without extensive feature engi- Recently,deeplearninghasemergedasapromis- neering. However, a challenge in deploying deeplearningforvulnerabilitydetectionisthe ingtechniqueduetoitsgoodperformancewithout limitedavailabilityoftrainingdata. Recentre- theneedforextensivefeatureengineering(Lietal., searchhighlightsthedeeplearningefficacyin 2018;Fuetal.,2022;Chakrabortyetal.,2022). diversetasks. Thissuccessisattributedtoin- Thetrainingofdeeplearning-basedvulnerability structionfine-tuning,atechniquethatremains detectiontoolsfacesasignificantchallengedueto under-exploredinthecontextofvulnerability limited data availability. Typically, the instances detection. Thispaperinvestigatesthecapabil- ity of models, specifically a recent language of vulnerable code are much less frequent than model,togeneralizebeyondtheprogramming non-vulnerablecode. Thisdisparitycanleadtoa languages used in their training data. It also biastowardsthemajorityclass,potentiallycausing examinestheroleofnaturallanguageinstruc- themodeltooverlooktheminorityclass,whichin tions in enhancing this generalization. Our this context is the vulnerable code (Johnson and study evaluates the model performance on a Khoshgoftaar,2019). real-worlddatasettopredictvulnerablecode. We present key insights and lessons learned, Despite this challenge, recent researches have contributingtounderstandingthedeeplearning demonstratedtheeffectivenessofdeeplearningin applicationinsoftwarevulnerabilitydetection. varioustasks,includingthosenotencountereddur- ing training. This success is largely attributed to 1 Introduction instructionfine-tuning,atechniquethattrainsmod- elsusingtaskdescriptionsandcorrespondinginput- Softwareisintegraltovarioustechnologies,such labelpairs(Weietal.,2022a;Mishraetal.,2022; assmartphonesande-learningsystems. Although Honovich et al., 2023; Wang et al., 2023a). This softwarebringsmanybenefits,itpresentspotential method leverages task descriptions as a guiding attacksurfacesforcyber-attacksduetovulnerabil- frameworkfortaskexecution. Duringfine-tuning, ities. Thesevulnerabilities,inextremecases,can themodellearnstomatchagiventaskdescription lead to significant financial losses. For instance, with specific inputs to generate appropriate out- Revolutexperienceda$20millionlosswhenattack- puts. Consequently,themodelcaninferthecorrect ersexploitedweaknessesinitspaymentsystem.1 outputbasedontheprovidedinstructionandinput. Consequently,thedetectionofsoftwarevulnerabil- Despiteitspotential,theapplicationofinstruc- itiesisacriticaltask. tionfine-tuninginvulnerabilitydetectionremains Programanalysistechniques,suchasstaticanal- largely unexplored. This paper aims to investi- ysisanddynamicanalysis,havebeenusedtodetect gate how well models can generalize beyond the vulnerabilities in code (Zhang et al., 2018, 2019; programming languages present in their training data and examine the impact of natural language 1https://thehackernews.com/2023/07/ hackers-steal-20-million-by-exploiting.html instructionsonimprovinggeneralizationinthevul- 4202 naJ 51 ]ES.sc[ 1v66470.1042:viXranerabilitydetectiontask. roleofnaturallanguageinstructionsinimproving We have conducted the study by evaluating a generalizationperformance. Wedefinethefollow- recentlanguagemodeltopredictvulnerablecode ingResearchQuestions(RQs). fromthereal-worlddataset. Ourstudyyieldsthree RQ1: How does the model perform in the insights. First,modelsperformmoreeffectivelyin intra-lingual and cross-lingual settings? The scenarioswherethelanguageisthesameasinthe intra-lingual setting tests the model on the same trainingdata(intra-lingual)comparedtodifferent programming language used during fine-tuning, languages(cross-lingual),althoughthedifference providing a baseline for performance. The result in performance is not substantial. Second, mod- intheintra-lingualsettingwillserveabaselinefor els that do not use natural language instructions comparing with the cross-lingual setting. In con- outperformthosethatdoinbothintra-lingualand trast to the intra-lingual setting, the cross-lingual cross-lingual settings. Third, when multiple pro- evaluationteststhemodelwithprogramminglan- gramminglanguagesareaddedtothetrainingset guages different from the fine-tuning language. withoutnaturallanguageinstructions,there’sade- Thisquestionaimstoassessthemodel’sabilityto cline in model performance. Conversely, when generalizeacrossvariousprogramminglanguages. natural language instructions are combined with RQ2: How do natural language instruc-
multipleprogramminglanguagesinthefine-tuning tionsinfluencemodelperformanceintheintra- process,themodelsshowbetterperformance. lingualandcross-lingualsettings? Thisquestion Thecontributionsofthispaperisasfollows. assesses whether incorporating natural language 1. We are the first to study how well models can instructionsenhancesthemodel’svulnerabilitypre- generalizebeyondtheprogramminglanguages diction capabilities within the intra-lingual and presentintheirtrainingdatainthevulnerability cross-lingualsettings. detectiontask. RQ3: Howdoesthediversityofprogramming 2. Wearethefirsttostudytheimpactofnaturallan- languagesinthefine-tuningdatasetaffectper- guageinstructionsonimprovinggeneralization formanceintheintra-lingualandcross-lingual inthevulnerabilitydetectiontask. settings? Thisquestioninvestigatestheinfluence The structure of this paper is organized as fol- oftheprogramminglanguagediversityinthefine- lows: Section 2 outlines the Research Questions tuningdatasetonthemodelperformancetopredict (RQs). Section3describestheprocessofdataset vulnerabilitiesintheintra-lingualandcross-lingual selection. Section 4 elaborates the methodology settings. used for the model selection. Section 5 outlines 3 Dataset the experimental settings. Section 6 presents the results. Section7discussesthemanualcasestudy, Thissectiondescribesthedatasetselection,statis- lessons learned, and potential threats to validity. tics,andpreprocessingsteps. Finally,Section8concludesthepaper. 3.1 DatasetSelection 2 ResearchQuestions A number of datasets are available in the do- We frame the vulnerability prediction task as a mainofvulnerabilitydetection,includingSARD2, binary classification problem. The classification VulDeePecker (Li et al., 2018), Draper (Russell decisioncanbeformalizedasEquation1. et al., 2018), D2A (Zheng et al., 2021), Devign (Zhouetal.,2019),BigVul(Fanetal.,2020),Re- v = argmaxP(v | c) (1) v veal(Chakrabortyetal.,2022),DiverseVul(Chen etal.,2023),CrossVul(Nikitopoulosetal.,2021), The model receives a code snippet c as the input. andCVEFixes(Bhandarietal.,2021). The objective of the model is to make prediction VulDeePecker, SARD, BigVul, Draper, D2A, v, where v ∈ (vulnerable, non-vulnerable). The Devign, BigVul, Reveal, and DiverseVul are lim- predictionisbasedontheconditionalprobability itedtotwoprogramminglanguages,whichareC P(v|c),whichrepresentsthelikelihoodofthecode and C++. Moreover, Draper and D2A are anno- beingvulnerablegiventhecodesnippetc. tatedbystaticanalyzers. Hence,DraperandD2A Based on the problem formulation above, this maycontainfalsepositiveandfalsenegativecases. study aims to examine model generalization be- yondthelanguagesinthefine-tuningdataandthe 2https://samate.nist.gov/SARD/SARDcoversfiveprogramminglanguages. How- 4.1 SelectingModelCandidates ever,SARDisasyntheticdatasetandmaynotre- Modelsareevaluatedagainst3criteria: theymust flectreal-worldvulnerabilities. Similarly,CrossVul beopen-sourceforcustomdatafine-tuning,capa- and CVEFixes also contain at least five program- ble of being fine-tuned on a single 24GB mem- ming languages. However, these datasets reflect oryGPU,andnotpreviouslyinstruction-tunedto real-world vulnerabilities better than SARD be- ensureperformanceimprovementsareduesolely causebotharecuratedfromreal-worldsecurityis- to our fine-tuning efforts. From the first filter- sues. Nevertheless,wechooseCVEFixesbecause ing,fivemodelsareconsidered: CodeLlama(7B) it contains a broader range of vulnerability types (Rozière et al., 2023), CodeT5+ (770M) (Wang (i.e.,CWEId)thanCrossVul,i.e.,193vs167types. etal.,2023b),CodeT5(770M)(Wangetal.,2021), Llama (7B) (Touvron et al., 2023), Mistral (7B) 3.2 DatasetPreprocessing (Jiang et al., 2023), and Yi (6B)3, CodeLlama, Theinitialdatasetcontains116,057instances. We CodeT5+, and CodeT5 are chosen because they excludeinstanceswithmorethan990codetokens are specifically pretrained for code-related tasks. toadheretothemaximumcontextlengthof1024 Conversely,Llama2,MistralandYiarechosenas in our experiment, due to the memory constraint. representatives of models pre-trained on general Thefirstexclusionstepresultsin67,692instances. corpora. The selection excludes the larger vari- Then, we only include dominant languages: C, ants of CodeT5+ due to the lack of optimization PHP,andPython. Wechoosethesethreelanguages withFlashAttention2(Dao,2023),whichrestricts becausetheyrepresentdifferentprogramminguse fine-tuningonourGPU. cases and have distinct syntax. Then, we sample 4.2 PreliminaryExperimentalSetting randomly2,750instancesfromeachlanguagefor fine-tuningsetand250fortestingset. Wechoose Wefine-tuneandevaluatethemodelusingalllan- thisnumbersuchthattheproportionbetweenthe guagesinourdataset,whichincludesC,PHP,and vulnerable and non-vulnerable instances are the Python,toidentifyamodelwithastrongbaseper- sameacrossdifferentprogramminglanguagesbe- formance. Weleverageaccuracyastheevaluation tweenthefine-tuningandtestingsets. Intheend, metric. We compute accuracy by calculating the we have 8,250 instances for fine-tuning and 750 ratio of correctly predicted instances to the total