Function contracts and roles¶
Visao knows what a library function does from its contract. A contract is an ACSL block that is attached to a function by its symbol name. The analyzer does not know any function by its name. It reads the contract and the roles in the contract.
Contract files¶
Contract files have the .contract extension. The format is:
# comment
@symbol read(fd, buf, count)
/*@
@ requires count == 0 || \valid(buf + (0 .. count - 1));
@ tagged "role:input", "role:writes:1";
*/
The @symbol line gives the symbol and the names of its parameters.
Visao binds the names to the parameters of the real declaration by
position, so the host header can use other names.
Visao reads contracts from these directories:
<stdlib>/c/contracts/Contracts of C and C++ library functions: the C standard library, POSIX, Linux, macOS and Windows. C, C++, Objective-C, RuC and assembly use these contracts.
<stdlib>/LANGUAGE/contracts/Contracts of the library functions of one language, for example
<stdlib>/python/contracts/or<stdlib>/java/contracts/. The directory name is the language name of the--languageoption.<stdlib>/roles/Roles of names that the frontends make for every language, for example
!throw. Visao reads only the roles from these files.
A contract applies only to the analysis of its language. The Python
open and the C open are two different functions with two
different contracts.
Visao finds the contract of a call by the name of the called function:
When the program or a library model declares the function, Visao attaches the contract to the declaration.
When the program calls a function that it does not declare, Visao attaches the contract to the called function at the first call.
The name and the arguments of a call are the ones the frontend gives the call:
A method call
x.m(a)callsmwith the argumentsx, a. The receiver is argument 0, so the contract is@symbol m(self, a).A call through an imported module keeps the module name: the Python
os.system(c)callsos.systemwith the argumentc.A Rust path keeps the last part:
File::open(p)callsopen.
Rules for the ACSL block of an entry:
Write the
requiresclauses before theensuresclauses. The ACSL grammar sets this order.Do not give a parameter the name of an ACSL keyword, for example
default.Use
p != \nullfor “not null”. In a script language, write it only for an argument that is never a number: the value\nullis 0.An
ensuresclause can have alternatives, for example\result == -1 || (\result >= 0 && \result <= count). The result gets the range that includes all alternatives, here-1tocount.
An entry with only tagged clauses gives roles. Visao does not attach
it, and the call stays unknown to the value analysis.
One symbol can have entries in more than one file. Visao adds the roles
of all entries together. An entry that has ACSL clauses other than
tagged replaces the ACSL block of an earlier entry.
A function in the analyzed source can have roles too. Write the roles in the annotation of the function:
/*@ tagged "role:input"; */
int read_packet(char *buf, int len);
System state¶
A contract can read and change the state of the system the program runs on: the operating system, the CPU, the hardware and the threads. The state is a set of state variables. A state variable is a number that exists only in the analysis.
Declare a state variable in a contract file:
@state os_irq_off = 0
@balanced os_irq_off
@state os_context = 0
@entry hardirq os_context = 2, os_irq_off = 1
@state NAME = VALUEDeclares the state variable
NAME. Each function starts with the variable atVALUE.@balanced NAMEEach function must return with
NAMEat the value it had when the function started. Visao checks this at eachreturnand at the end of the function.@entry PROFILE NAME = VALUE, ...Gives the values a function starts with when the system runs it in the way
PROFILEnames, for example as an interrupt handler.
A contract uses a state variable by its name. In an ensures clause,
\old(NAME) is the value before the call:
@symbol local_irq_disable()
/*@ ensures os_irq_off == \old(os_irq_off) + 1; */
@symbol msleep(ms)
/*@ requires \report(os_irq_off == 0 && os_context == 0,
"WrongExecutionContext"); */
These roles give a function its entry profile:
role:handler:N:PROFILEThe function passed in argument
Nruns with the entry profilePROFILE. Use it on the function that registers a handler, for examplerequest_irqorsignal.role:entry:PROFILEThe function runs with the entry profile
PROFILE. Write it on an interrupt handler in the analyzed source.
A function called in a function of the program shares the state of its
caller. The program can call a function it defines. Then Visao checks
the state requirements of the library calls that this function makes
before its first branch or return.
The findings of this section:
WrongExecutionContextA call needs another state of the system.
StateNotRestoredA function returns with a balanced state variable at a value other than the one it started with.
The models of the target systems are in these directories. They apply to the C family:
<stdlib>/os/OS/contracts/The model of the target OS:
linux,macos,windowsorbaremetal.<stdlib>/os/posix/contracts/applies to Linux and macOS.<stdlib>/cpu/CPU/contracts/The model of the target CPU, for example
armorx86_64.
An entry of a system model adds its clauses to the library contract of
the same symbol. The target comes from the build. The environment
variables VISAO_MODEL_OS and VISAO_MODEL_CPU select another
model, for example to analyze kernel code with the headers of the host.
Function summaries¶
Visao analyzes each function of the program on its own. A call of a function of the program uses the contract of that function. A function without a contract gets a summary from the analysis of its body:
the range of its result, for example
\result >= 1 && \result <= 3;a result that is never null;
a result that can be null: the function returns null on one path and a different pointer on another path, for example
find(key). A return of null when a pointer parameter is null, for exampleif (!attr) return NULL;, does not count. A caller that dereferences the result without a check is reported;the pointer parameters that the function dereferences before it checks them, outside each branch. A call that gives null to such a parameter is reported, for example
get_id(NULL)orget_id(malloc(n));the change the function makes to a state variable, for example
os_irq_off == \old(os_irq_off) + 1;the pointer parameters that the function frees on each way out where the parameter is not null, for example
void key_free(struct key *k) { if (k == NULL) return; ...; free(k); }. A call of the function frees the argument;the negative values below
-1that the function returns, and the functions whose result it returns. A caller that compares the result with-1only is reported when the function can return a different negative value;the pointer parameter that the function gives to
reallocand returns the result of, for examplexreallocarray. The function getsrole:reallocates:N;the parameter that is the size of the block that the function allocates and returns, for example
void *xmalloc(struct ctx *c, size_t size) { void *p = calloc(1, size); ...; return p; }. A return of null keeps this fact. The function getsrole:alloc_size:N. When the function also returns a different value, it getsrole:alloc_size_conflictand no size;the pointer parameters that the function keeps after it returns, in a structure through a pointer or in a global variable. The function gets
role:retains:N;the pointer parameters through which the function writes data from outside, for example
sshbuf_get_u32(b, &len). The function getsrole:taints_out:N. A value that the function makes from bytes, for examplep[0] << 8 | p[1], is data from outside.the parameters that reach an argument of a sink, directly or through the variables and the functions that the function gives them to, for example
gitInit(input)that builds a command frominput.pathforexec. A call that gives data from outside to such a parameter is reported, with the sink call as a note;the variable that a call with
role:wraps:Nmakes, for exampleexecAsync = promisify(exec). The variable gets the roles of the function in argumentN.
A function declared not to return (__attribute__((noreturn)),
_Noreturn) ends the path of its caller, as a library function with
role:abort does. A function that calls such a function before its
first branch or return does not return either.
Visao analyzes the called functions before their callers, so the caller gets the summary.
A function without parameters that always returns one constant, for
example static int staticReturnsTrue(void) { return 1; }, is a
setting of the program. The caller uses its value to find the paths that
can run. Visao does not report ConditionAlwaysTrue or
ConditionAlwaysFalse for a condition on that value: with a different
setting, the condition has a different result. A function with no branch and no early return that
changes a balanced state variable is a wrapper, for example a lock
function. Visao does not report StateNotRestored for it. Its callers
get the change through the summary.
The caller uses the range of a result in the same way as the range of a
variable. This is also true for a call in a condition, for example
if (pick(a) > 10). When the range of each operand makes the condition
always true or always false, Visao reports ConditionAlwaysTrue or
ConditionAlwaysFalse. An outer condition also gives a range, for
example x < 1 is always false in the body of if (x >= 1).
Visao uses the relations between variables too: in the body of
if (x < y && y < 10) the condition x > 20 is always false. A loop
stops when its condition is false or at a break. After the loop, a
variable has one of the values it has at these points. After
for (i = 0; i < 10; i++) the condition i < 5 is always false.
After while (i < 100) { if (c) break; i++; } the condition
i > 100 is always false. A continue gives its values to the
next iteration.
In the body of a loop the ranges hold for all iterations: in the same
loop i > 20 is always false, and i == 5 gives no finding.
Calls between languages¶
A function of the program with a contract or a summary is available to
the other languages of the run under its name. A call from another
language uses that contract: Visao checks the requires clauses at the
call and uses the ensures clauses after it.
These calls get the contract:
a call through Python
ctypesorcffi, for examplelib.foo(x);a function in a Rust
extern "C"block;a Go call through cgo, for example
C.foo(x);a C# method with
DllImport;a Java
nativemethod. The C functionJava_pkg_Class_methodgives its contract to the methodmethod, without the two JNI parameters.
When the analysis of the function finds a violated ensures clause,
the contract is refuted. The callers then check its requires clauses
and do not use its ensures clauses.
Visao analyzes C, C++, Rust and Go files before the other languages of
the run, also with -j. The functions these languages export are then
known when a Python, Java or C# file calls them.
Roles¶
A role is a string in a tagged clause. It starts with role:.
Some roles have parameters. A parameter is separated by :.
Argument numbers start at 0. In a method call, argument 0 is the
receiver.
Resources¶
role:acquire:CLASSThe result is a new resource of the class
CLASS.role:acquire_on_success:CLASSThe result is a new resource of the class
CLASSonly when the call succeeds.role:release:CLASS:NThe function releases the resource in argument
N. The class tells what the release does:memory,malloc,new,new[]andgcfree memory.mutex,rwlock,spinandlockunlock.The other classes close a handle.
role:lock:CLASS:NThe function locks the lock in argument
N.role:try_lockThe lock of
role:lockcan fail (pthread_mutex_trylock). After the call, the lock can be free. A lock that a try-lock takes is not reported as held at the end of the function.role:init:CLASS:NThe function makes the lock in argument
Nready for use (pthread_mutex_init). After the call, the lock is not locked. An unlock before a lock is reported.role:alloc_size:NThe size of the new block is argument
N.role:alloc_size:N*Mgives the size as the product of two arguments.role:reallocates:NThe function releases the block in argument
Nand returns a new block (realloc). The facts about the old block become false. When the result is not null, the old block is free: a use of the old pointer or afreeof it is reported. When the result is null, the old block stays valid.role:retains:NThe function keeps the pointer in argument
Nafter it returns. An argument can point into an array, for example&options.fw[i]. When another function of the program gives that array torealloc, the call is reported: after the move, the kept pointer points into freed memory.role:nullable_resultThe result can be null. A use of the result before a check is a defect.
role:freshThe result is a new object, for example a literal or a
new. It is never null.role:null_testThe result is true when the receiver is null (Ruby
nil?, Rustis_none). A call on a null receiver does not fail. A branch on the result is a null check of the receiver.role:nonnull_testThe result is true when the receiver is not null (Rust
is_some). A branch on the result is a null check of the receiver.
The rules use these resource classes:
Memory:
malloc,malloc0(zeroed memory),new,new[],gc,stack,heapmem(HeapAlloc),local,global,cotask,bstr,aligned,malloca,vm, and the reference-countedcf,objcanddispatch. A release frees the memory.Locks:
mutex,rwlock,spin,lock,srw. A release unlocks.Handles: every other class, for example
FILE,fd,DIR,pipe,db,handle(a Windows handle),heap(a heap fromHeapCreate),find,module(a loaded library),map(a mapped view),key(a registry key). A release closes the handle. A handle that is not closed is a handle leak.
The class sets are in XResourceTracker::isMemoryClass,
isLockClass and isHandleClass.
A function of the program does not get the roles of a library name. Visao reads what its body does to the resources of its parameters:
A release, a lock, an unlock or an init of a parameter before the first branch, loop or return of the body is done on every path. The function then has the same effect on its argument. For a lock, the parameter can also hold the lock in a member:
&p->m.A lock that the function makes in a local, initializes and stores through a parameter (
*out = l) is a new lock that is not locked.
In C, a function with external linkage gives this effect to calls in other files of the run. A static function does not.
Control flow¶
role:abortThe function does not return.
role:assertThe function is an assertion handler. It stops the program because an assertion failed.
role:branch_hintThe function returns its argument 0 and tells the compiler which branch is likely (
__builtin_expect).role:result_neededThe result is the only report of a failure (
fgets,scanf,setuid). A call that is a statement and discards the result is reported. A cast tovoiddiscards the result on purpose and is not reported.
Data from outside¶
role:inputThe function reads data from outside the program. Its result and the buffers it writes are tainted.
role:input:functionThe same, but only when the call is a function call, not a method call (Go
fmt.Scanagainstrows.Scan).On a dotted name of a property, for example
process.env, the role marks a read of the property.process.env.HOMEis tainted. On the name of a global variable, for example_GETin PHP, the role marks a read of the variable.$_GET["page"]is tainted. A local variable or a parameter with the same name is not. A call of a method of such a property, for examplerequest.values.items(), returns input too.role:input_handler:PThe function registers a handler of requests from outside, for example an MCP
server.toolor an HTTPapp.get. ParameterPof each function that the call gets as an argument holds the request and is tainted. A closure in the handler that reads the request sees the same taint.role:input_handler:*The same, but every parameter holds a part of the request, for example a route of Flask or FastAPI. In Python, a decorator gets the function that it decorates:
@app.route("/x")overdef viewis the callapp.route("/x", view).On the name of an annotation or an attribute, the role applies to the method that has it. For example,
@GetMappingin Spring and[HttpPost]in ASP.NET Core make the method a handler. A function that the call gets inside a wrapper is a handler too:app.post(p, catchErrors(async (req, res) => ...)).In PHP, the annotations of a docblock count as annotations (
@Route("/api/{id}")of Symfony), and so do the attributes (#[Route('/api/{id}')]).role:input_type_beside:TOn the name of a class: a parameter of this class is the request when the function also has a parameter of class
T. For example, in Go,r *http.Requestnext tow http.ResponseWriteris the request of a handler. The route table that registers the handler can be out of the analysis. A request that the program makes has no response writer next to it.role:input_name_beside:NOn the name of a parameter. A parameter with this name and no known class is the request when the function also has a parameter named
N. For example,reqnext toresis the request of an Express handler.role:taints_out:NThe function writes data from outside through the pointer in argument
N. After the call, the object that the pointer points to is tainted.role:taint_passesThe result is tainted when an argument is tainted (
atoi). When the function also hasrole:format_scan:N, the arguments after the format are tainted too (sscanf).role:number_resultThe result is a number that the function makes of its arguments (
strconv.Atoi,parseInt,len). The result stays tainted, but it has no syntax of a path, a command, a query or code. It does not count at a sink. A function of the program that returns a parameter only in this form has the same effect. A parameter of a number type (int,bool,double) does not count at a sink either. A 64-bit integer is not in this group, because the frontends of languages without declared types give this type to all unknown values.role:sink:KINDThe function interprets its argument.
KINDis one of these:command: the function runs a program.command_shell: the same, but only withshell=True.code: the function evaluates code.path: the file system uses the argument as a file name (fopen,remove).env: the argument goes into the environment (putenv,setenv).sql: the database runs the argument as the text of a query (cursor.execute,db.Query,mysqli_query).html: the browser parses the argument as HTML of the page (insertAdjacentHTML, thedangerouslySetInnerHTMLattribute of React).url: the argument is the address of a link or the next address of the page (thehrefattribute,location.href). The browser runs the addressjavascript:...as code. A text that starts with a part of the program ("/user/" + id) has the scheme of the program, and it is not a finding.
A tainted argument is a finding.
role:sink:KIND:NThe same, but only argument
Ncounts.Ndoes not count the receiver of a method call. For example,execFileruns the program in argument0without a shell. The other arguments go to the program unchanged, and a tainted argument there is not a finding.role:sink:KIND:receiverThe same, but only the receiver counts. For example,
p.unlink()ofpathlib.Pathdeletes the file thatpnames, andp.write_text(data)writesdatainto it. Tainteddatais not a finding.role:display:NAMEThe name of the function in the text of a finding. A frontend gives some parts of the code the name of a marker. For example, the attribute
dangerouslySetInnerHTMLof a JSX element is the call!jsx_attr_dangerouslySetInnerHTML. The finding showsdangerouslySetInnerHTML.role:sink:KINDon!store_FA store into the field
Fof an object is a sink. For example,!store_innerHTMLhas the rolerole:sink:html, andel.innerHTML = qwith taintedqis a finding.role:program:NArgument
Nof acommandsink names the program. The other arguments go to that program. A shell reads them only when the program is a shell (cmd.exe,sh,bash,powershell). ThusProcess.Start("cmd.exe", "/C tool " + url)is a finding, andProcess.Start(path, url)is not. Tainted text in the name of the program is always a finding. When argumentNis an object, its field ofrole:program_fieldnames the program. When the call has no argumentN, the receiver is that object (p.Start()).role:program_field:FThe field
Fof an object holds the program ofrole:program:N(FileNameofProcessStartInfo). The analysis records the stores into the fields of a local object (si.FileName = "cmd.exe",p.StartInfo = si).role:sink_freeThe sink counts only for a call without a receiver. For example,
fs::write(path, data)of Rust writes to the file thatpathnames. A method of the same name (w.write(buf)) writes to a stream, and a tainted argument there is not a finding.role:hookThe function is a hook of React (
useState,useEffect). React finds the state of a hook by the order of the calls in a component. Thus each run of the component must call the same hooks in the same order. A call in a branch, in a loop, or after a return in a branch is a finding. A call in the callback of another hook is in a function of its own, and the rule examines that function separately.role:sink_receiver:NAMEThe sink counts only for a method call on the global
NAME. For example,document.write(html)puts HTML into the page. The methodwriteof a stream writes data, and a tainted argument there is not a finding.role:sink_max_args:NThe sink counts only for a call with
Narguments or fewer. The receiver of a method call is not counted. For example,file.delete()of Java deletes the file thatfilenames. The methoddelete(start, end)of aStringBuildertakes two numbers, and a tainted receiver there is not a finding.role:sink_skip:NArgument
Nis no part of the sink. For example, the context ofexec.CommandContext(ctx, name, args...)of Go does not run as a command. A tainted context there is not a finding.role:sink_methodThe sink counts only for a method call. For example,
db.Or(cond)of a query builder addscondto the SQL. A function of a package with the same name (cmp.Or(a, b)of Go) gives one of its arguments. A tainted argument there is not a finding.role:sql_escapeThe function escapes a text for the quotes of a query (
mysqli::real_escape_string,$db->escape($x)). The result holds the input, but the input does not count at asqlsink. It counts at all the other sinks. Give the functionrole:taint_passestoo.role:path_cleanThe result keeps only the last part of a path, or has no path separator (
os.path.basename,secure_filename,filepath.Base). Tainted data in the result does not count at apathsink. It counts at all the other sinks.role:path_contains:NThe function tests that the path in argument
Nstays inside a directory (IsSubPath(root, p)).Ndoes not count the receiver of a method call. After the call, the input in the argument does not count at apathsink.The test is a check only of a normalized path: the result of a function with
role:path_normalize, or a variable that holds one. A path as it came can contain.., androot/../xstarts withroot.role:path_contains_receiverThe same, but the receiver is the path that the function tests (
full.startsWith(root)).role:path_local:NThe function tests that the path in argument
Nhas no..part that leaves the directory and is not absolute (filepath.IsLocal). The test needs no normalization of the path first. After the call, the input in the argument does not count at apathsink.role:path_normalizeThe function returns the full or plain form of the path in its arguments (
Path.GetFullPath,os.path.realpath). The result holds the input of the path. When apath_containstest checks the result, the path that the function got is also inside the directory (Path.GetFullPath(p).StartsWith(root)).role:regex_check:P:SThe function tests the value in argument
Sagainst the pattern in argumentP.rnames the receiver. A pattern can be anchored and allow only letters, digits,_and-(^[A-Za-z0-9_-]+$). After a test with such a pattern, the input in the value does not count at a sink.A pattern that also allows
.(^[a-zA-Z0-9._-]+$) lets..through. After a test with such a pattern, the input does not count at acommand,code,sqlorenvsink. It counts at apathsink.The pattern can have groups, alternatives, literal text and repetitions (
^([a-z_]+)(?: (desc|asc))?$). The analysis takes the set of characters that a match can hold. A pattern that allows only letters, digits,_,.,,and spaces is safe at asqlsink only. A pattern with.for any character, with a negated class ([^/]) or with no anchors at both ends is no check. The anchors are^or\Aat the start and$or\zat the end (/\A[0-9]+-[0-9]*\z/in Ruby). In Ruby,s =~ patternis such a test. What the function writes into an argument (role:writes:N, the$matchesofpreg_match) is as safe as the value.A function of the program that makes such a test of a parameter and returns an error for a bad value is a validator. After a call of the validator, the input in the argument is checked in the same way.
role:contains:H:NThe function tests whether the text in argument
Hcontains the text in argumentN(name.include?(x),strings.Contains(p, x)). When the analysis knows that the second text is.., the program refuses a name that climbs out of a directory. After the call, the input in argumentHdoes not count at apathsink.role:replace:NThe function replaces the text in argument
Nwith the text in argumentN + 1(str.replace,strings.ReplaceAll). The analysis must know both texts. When the first one has/and the second one has no/, the result is the same as the result of arole:path_cleanfunction. A loop over a known set of characters (for c in '\\/:') gives each character toc.A function of the program can return such a value. For example, it removes
/and\\from a name. Each call of the function then has the same effect.When the first text is a negated class and the second text is empty (
s.replace(/[^a-zA-Z0-9]/g, '')), the result holds only the characters of the class. The analysis then treats the result as a value that passed a test against^[class]*$(seerole:regex_check).[^a-zA-Z0-9./]keeps.and/, so the result still counts at apathsink.role:wraps:NThe result is a function that does the work of the function in argument
N(util.promisify). The variable that keeps the result gets the roles of that function.role:path_lookup:NThe function finds its program through
PATHwhen the program name has no directory (system,popen,execlp). ArgumentNis the program or the command text. When the text is known and its first word is a program name without a directory, the call is reported. A shell builtin (echo,cd) is not reported.role:environment_readThe result is the value of an environment variable (
getenv).role:output:NThe function writes argument
Nout of the program (puts,write).role:output_from:NThe function writes argument
Nand all the arguments after it out of the program (printf,fprintf). A function that gives its parameter to an output getsrole:outputfor that parameter. The value of an environment variable in an output is reported.role:text_extract:S:BThe function reads a word from the stream in argument
Sinto argumentB(C++operator>>). Into a character buffer, the word stops only at white space. When no width is set on the stream, the call is reported.role:extract_width:NThe function sets the width of the stream in argument
Nfor the next word that is read (ios_base::width).role:secret_sourceThe result is a secret (a password hash, a key).
role:secret_passesThe result is a secret when an argument is a secret.
role:copies:D:SThe function copies argument
Sinto argumentD.- Points of entry
A function of the program that no code of the program calls is a point of entry. A framework, a route table or a user of a library calls it, and its parameters can hold any value. When such a parameter reaches a sink and no other input reaches the same sink, the analysis reports it at a lower severity. The receiver and parameters of a number type do not count.
The analysis reports this only for a function that looks like a handler of requests:
The function has an annotation that is not a part of the language, for example
@GetMapping.@Overridedoes not count.The name of its file or of the function has one of these words:
controller,handler,route,api,views,endpoint,servlet,webhook.The parameter has one of these names:
req,request,ctx,body,params,payload,form.
The analysis does this for all the files with
--whole-project, and for one file when it gets one file.
Buffers and memory¶
role:writes:NThe function writes into the buffer in argument
N.role:bounded_copy:NThe function copies a bounded string into argument
Nand can leave it without a terminating null (strncpy).role:mem_copy:D:S:LThe function copies
Lbytes from argumentSto argumentD. The regions must not overlap.role:mem_move:D:S:LThe same, but the regions can overlap (
memmove).role:mem_fill:D:LThe function writes
Lbytes into argumentD.role:derefs:NThe function reads through the pointer in argument
N. A null pointer there is a defect.role:borrows:NThe function uses the block in argument
Nonly while it runs. It does not free the block or keep a pointer to it, so the caller still owns the block (strcpy,memcpy).role:size_arg:NArgument
Nis a size.role:var_param:NArgument
Nis a Pascalvaroroutparameter. The call passes the variable, and the function can write into it (TryStrToInt).role:returns_into:NThe result points into the buffer in argument
N.role:format:NThe format string of a
printf-like function is argumentN.role:format_scan:NThe format string of a
scanf-like function is argumentN.role:unbounded_format_write:NThe function writes formatted text into argument
Nwithout a size (sprintf).role:string_read:NThe function reads argument
Nas a string up to its terminating null (strlen,strcat). A local array that nothing wrote has no terminator, and a read of it is reported.role:no_accessThe function does not read or write the memory that its arguments point to (
__builtin_object_size).
Paths¶
role:path_check:NThe function checks the file in argument
N(access,stat).role:path_use:NThe function acts on the file in argument
N(open,unlink). A check before a use of the same path is a race. The race is reported at the check.role:temp_nameThe result is a name for a temporary file (
mktemp,tmpnam).role:temp_name_in:NThe function writes a name for a temporary file into argument
N.role:file_open:P:F:E...The function opens the file in argument
Pwith the integer flags in argumentF. Each valueEis the flag that makes the open fail when the file exists (O_EXCL), one value for each platform.role:file_open_mode:P:MThe function opens the file in argument
Pwith the mode text in argumentM. The modexmakes the open fail when the file exists (fopen).An open of a temporary name without
O_EXCLorxis reported. Another process can put a file or a link under that name first.role:temp_create:NThe function creates a temporary file and writes its name into argument
N(mkstemp).role:file_remove:NThe function removes the file in argument
N(unlink,remove).A temporary file that the function creates and does not remove on any path is reported. A function can write the name out of the program (
role:output). Then the reader of the name gets the file, and the file is not reported.
Security¶
role:compares:A:BThe function compares argument
Awith argumentB.role:variable_time_compareThe comparison stops at the first difference. It leaks the position of that difference through time.
role:error_token:TWhen the function fails, the result is the string
T, not a null pointer (cryptof musl gives*). Use one role for each string. A function that returns such a result gets the same roles.A comparison of such a result with a value that can be
Tis reported. A check for null does not excludeT. The comparison is not reported when the code reads the characters of the result, takes its length or compares it with a literal first. It is not reported when the length of the other value on that path is different from the length of each string.role:privilege:uidThe function sets the user IDs of the process for good (
setresuid). Argument 0 is the new user.role:privilege:groupsThe function sets the supplementary groups (
initgroups).role:real_idThe function returns an ID of the user that runs the program (
getuid).role:execThe function runs a new program in the process (
execv).A change to another user before a call with
role:execis reported when the function does not set the supplementary groups first. The new program keeps the groups of the old user. A change to the user that runs the program (setuid(getuid())) is not reported.role:file_mode:NArgument
Nis the mode that the function gives to a file. The umask does not change this mode (chmod). A mode that lets other users write the file is reported. A mode with the sticky bit is not reported.role:credentials:L:PThe function takes a login in argument
Land a password in argumentP. Use-1when the function has no login argument.role:security:KINDThe function is part of the security surface.
KINDispassword,authorization,authentication,crypto,tokenorprivilege.role:dangerousThe function cannot be used safely (
gets,tmpnam).role:exception_rootThe name is the class that all exceptions of the library derive from (
std::exception). A handler of this class, or a handler that catches all exceptions (catch (...)), is reported when it does not throw the exception again.role:throw:NThe function throws argument
N(the!throwof the program model). A thrown object of the class withrole:exception_rootis reported. A function that declares that it throws this class or any exception (throw (std::exception),throw (...)) is reported too.
Threads and signals¶
role:thread_start:NThe function starts a thread that runs the routine in argument
N(pthread_create). A function of the program that takes a routine and starts a thread getsrole:thread_startfor that parameter.role:signal_handler:NThe function installs the signal handler in argument
N(signal). Another action for the same signal removes the handler. A handler in a field of a structure that the call gets (sa.sa_handlerforsigaction) is installed too. A function of the program that installs its parameter gets the role for that parameter.
The analysis gives these roles to the functions of the program:
role:thread_entryThe function is the routine of a thread. A write to a shared variable in it, or in a function that it calls, is reported when no lock is held.
role:reads_global:Gandrole:modifies_global:GThe function reads the shared variable
G, or writes it, writes through it or frees it. While a signal handler that changesGis installed, a use ofGis reported. Avolatileinteger (sig_atomic_t) is not reported.role:signal_handler_fnThe function is a signal handler. A call in it of a function that is not async-signal-safe is reported, also through the functions of the program that it calls. A call of a function that can set errno is reported when the handler does not restore errno and returns. Code that runs only when the signal number is 0 (a direct call) is not examined.
role:used_as_valueThe program gives the function to a library call as an argument (
signal,qsort,atexit). The library calls it through a pointer whose type sets its parameters, so a parameter that it does not read is not reported. The same applies to a thread routine. A constant loop without an exit in such a function, in a thread routine or inmainis not reported either.role:banned:STANDARD:RULEA coding standard bans the function, for example
role:banned:misra-c-2012:21.6.
Findings on a call¶
The frontend rules of a language use these roles. A rule reports only the finding types that it owns, so the same name in two languages does not mix the rules.
role:report_call:TYPEA call of the function is a finding of the type
TYPE.TYPEis a report type name, for exampleEvalCall.role:report_string_arg:TYPE:NA call with a string literal in argument
Nis a finding of the typeTYPE. The function runs that string as code (setTimeout("code", n)).role:returns_minus_one_if_missingThe function returns
-1when it does not find the value (indexOf).role:deletes_filesThe command deletes files (
rm).role:blocking_waitThe method blocks the thread until the task in the receiver completes (C#
Task.Wait).role:builtinThe name is a builtin of the language. An assignment to the name hides the builtin (Python
list = []).role:existence_checkThe function tests whether a value exists. It does not use the value (PHP
isset).role:glob_mode:NArgument
Nselects the mode of the command. The modesGLOBandGLOB_RECURSEfind the files one time, at configure time (CMakefile).role:minimum_versionThe command sets the minimum version of the tool and the policies of that version (CMake
cmake_minimum_required).
Signals¶
role:async_signal_safeThe function can be called from a signal handler.
role:keeps_errnoThe function does not change errno. It cannot fail, or it does not return.
role:signal_handler:NThe function installs the signal handler in argument
N.
Containers¶
role:container:OPandrole:container:OP:NA container operation.
OPiscreate,sized(the size is argumentN),empty,grow,shrink,clear,lenorread.role:iteratorThe result is an iterator into the receiver.
role:invalidates_iteratorsThe function changes the storage of the receiver. Iterators into the receiver become invalid.
role:indexed:NArgument
Nis an index into the receiver.role:consumes_receiverThe function moves the receiver. A later use of the receiver is a defect.
Values¶
role:math:FUNCTIONThe function computes a known mathematical function, so the analyzer can compute the result of a call with known arguments.
FUNCTIONisabs,fabsorsqrt.abscomputes the absolute value of an integer argument.fabsalso computes it for a floating argument.