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 --language option.

<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) calls m with the arguments x, 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) calls os.system with the argument c.

  • A Rust path keeps the last part: File::open(p) calls open.

Rules for the ACSL block of an entry:

  • Write the requires clauses before the ensures clauses. The ACSL grammar sets this order.

  • Do not give a parameter the name of an ACSL keyword, for example default.

  • Use p != \null for “not null”. In a script language, write it only for an argument that is never a number: the value \null is 0.

  • An ensures clause can have alternatives, for example \result == -1 || (\result >= 0 && \result <= count). The result gets the range that includes all alternatives, here -1 to count.

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 = VALUE

Declares the state variable NAME. Each function starts with the variable at VALUE.

@balanced NAME

Each function must return with NAME at the value it had when the function started. Visao checks this at each return and 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 PROFILE names, 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:PROFILE

The function passed in argument N runs with the entry profile PROFILE. Use it on the function that registers a handler, for example request_irq or signal.

role:entry:PROFILE

The 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:

WrongExecutionContext

A call needs another state of the system.

StateNotRestored

A 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, windows or baremetal. <stdlib>/os/posix/contracts/ applies to Linux and macOS.

<stdlib>/cpu/CPU/contracts/

The model of the target CPU, for example arm or x86_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 example if (!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) or get_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 -1 that the function returns, and the functions whose result it returns. A caller that compares the result with -1 only is reported when the function can return a different negative value;

  • the pointer parameter that the function gives to realloc and returns the result of, for example xreallocarray. The function gets role: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 gets role:alloc_size:N. When the function also returns a different value, it gets role:alloc_size_conflict and 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 gets role:taints_out:N. A value that the function makes from bytes, for example p[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 from input.path for exec. 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:N makes, for example execAsync = promisify(exec). The variable gets the roles of the function in argument N.

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 ctypes or cffi, for example lib.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 native method. The C function Java_pkg_Class_method gives its contract to the method method, 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:CLASS

The result is a new resource of the class CLASS.

role:acquire_on_success:CLASS

The result is a new resource of the class CLASS only when the call succeeds.

role:release:CLASS:N

The function releases the resource in argument N. The class tells what the release does:

  • memory, malloc, new, new[] and gc free memory.

  • mutex, rwlock, spin and lock unlock.

  • The other classes close a handle.

role:lock:CLASS:N

The function locks the lock in argument N.

role:try_lock

The lock of role:lock can 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:N

The function makes the lock in argument N ready for use (pthread_mutex_init). After the call, the lock is not locked. An unlock before a lock is reported.

role:alloc_size:N

The size of the new block is argument N. role:alloc_size:N*M gives the size as the product of two arguments.

role:reallocates:N

The function releases the block in argument N and 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 a free of it is reported. When the result is null, the old block stays valid.

role:retains:N

The function keeps the pointer in argument N after it returns. An argument can point into an array, for example &options.fw[i]. When another function of the program gives that array to realloc, the call is reported: after the move, the kept pointer points into freed memory.

role:nullable_result

The result can be null. A use of the result before a check is a defect.

role:fresh

The result is a new object, for example a literal or a new. It is never null.

role:null_test

The result is true when the receiver is null (Ruby nil?, Rust is_none). A call on a null receiver does not fail. A branch on the result is a null check of the receiver.

role:nonnull_test

The 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-counted cf, objc and dispatch. 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 from HeapCreate), 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:abort

The function does not return.

role:assert

The function is an assertion handler. It stops the program because an assertion failed.

role:branch_hint

The function returns its argument 0 and tells the compiler which branch is likely (__builtin_expect).

role:result_needed

The 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 to void discards the result on purpose and is not reported.

Data from outside

role:input

The function reads data from outside the program. Its result and the buffers it writes are tainted.

role:input:function

The same, but only when the call is a function call, not a method call (Go fmt.Scan against rows.Scan).

On a dotted name of a property, for example process.env, the role marks a read of the property. process.env.HOME is tainted. On the name of a global variable, for example _GET in 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 example request.values.items(), returns input too.

role:input_handler:P

The function registers a handler of requests from outside, for example an MCP server.tool or an HTTP app.get. Parameter P of 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") over def view is the call app.route("/x", view).

On the name of an annotation or an attribute, the role applies to the method that has it. For example, @GetMapping in 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:T

On 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.Request next to w http.ResponseWriter is 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:N

On 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, req next to res is the request of an Express handler.

role:taints_out:N

The 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_passes

The result is tainted when an argument is tainted (atoi). When the function also has role:format_scan:N, the arguments after the format are tainted too (sscanf).

role:number_result

The 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:KIND

The function interprets its argument. KIND is one of these:

  • command: the function runs a program.

  • command_shell: the same, but only with shell=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, the dangerouslySetInnerHTML attribute of React).

  • url: the argument is the address of a link or the next address of the page (the href attribute, location.href). The browser runs the address javascript:... 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:N

The same, but only argument N counts. N does not count the receiver of a method call. For example, execFile runs the program in argument 0 without a shell. The other arguments go to the program unchanged, and a tainted argument there is not a finding.

role:sink:KIND:receiver

The same, but only the receiver counts. For example, p.unlink() of pathlib.Path deletes the file that p names, and p.write_text(data) writes data into it. Tainted data is not a finding.

role:display:NAME

The 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 dangerouslySetInnerHTML of a JSX element is the call !jsx_attr_dangerouslySetInnerHTML. The finding shows dangerouslySetInnerHTML.

role:sink:KIND on !store_F

A store into the field F of an object is a sink. For example, !store_innerHTML has the role role:sink:html, and el.innerHTML = q with tainted q is a finding.

role:program:N

Argument N of a command sink 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). Thus Process.Start("cmd.exe", "/C tool " + url) is a finding, and Process.Start(path, url) is not. Tainted text in the name of the program is always a finding. When argument N is an object, its field of role:program_field names the program. When the call has no argument N, the receiver is that object (p.Start()).

role:program_field:F

The field F of an object holds the program of role:program:N (FileName of ProcessStartInfo). The analysis records the stores into the fields of a local object (si.FileName = "cmd.exe", p.StartInfo = si).

role:sink_free

The sink counts only for a call without a receiver. For example, fs::write(path, data) of Rust writes to the file that path names. A method of the same name (w.write(buf)) writes to a stream, and a tainted argument there is not a finding.

role:hook

The 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:NAME

The sink counts only for a method call on the global NAME. For example, document.write(html) puts HTML into the page. The method write of a stream writes data, and a tainted argument there is not a finding.

role:sink_max_args:N

The sink counts only for a call with N arguments or fewer. The receiver of a method call is not counted. For example, file.delete() of Java deletes the file that file names. The method delete(start, end) of a StringBuilder takes two numbers, and a tainted receiver there is not a finding.

role:sink_skip:N

Argument N is no part of the sink. For example, the context of exec.CommandContext(ctx, name, args...) of Go does not run as a command. A tainted context there is not a finding.

role:sink_method

The sink counts only for a method call. For example, db.Or(cond) of a query builder adds cond to 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_escape

The 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 a sql sink. It counts at all the other sinks. Give the function role:taint_passes too.

role:path_clean

The 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 a path sink. It counts at all the other sinks.

role:path_contains:N

The function tests that the path in argument N stays inside a directory (IsSubPath(root, p)). N does not count the receiver of a method call. After the call, the input in the argument does not count at a path sink.

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 .., and root/../x starts with root.

role:path_contains_receiver

The same, but the receiver is the path that the function tests (full.startsWith(root)).

role:path_local:N

The function tests that the path in argument N has 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 a path sink.

role:path_normalize

The 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 a path_contains test checks the result, the path that the function got is also inside the directory (Path.GetFullPath(p).StartsWith(root)).

role:regex_check:P:S

The function tests the value in argument S against the pattern in argument P. r names 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 a command, code, sql or env sink. It counts at a path sink.

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 a sql sink 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 \A at the start and $ or \z at the end (/\A[0-9]+-[0-9]*\z/ in Ruby). In Ruby, s =~ pattern is such a test. What the function writes into an argument (role:writes:N, the $matches of preg_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:N

The function tests whether the text in argument H contains the text in argument N (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 argument H does not count at a path sink.

role:replace:N

The function replaces the text in argument N with the text in argument N + 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 a role:path_clean function. A loop over a known set of characters (for c in '\\/:') gives each character to c.

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]*$ (see role:regex_check). [^a-zA-Z0-9./] keeps . and /, so the result still counts at a path sink.

role:wraps:N

The 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:N

The function finds its program through PATH when the program name has no directory (system, popen, execlp). Argument N is 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_read

The result is the value of an environment variable (getenv).

role:output:N

The function writes argument N out of the program (puts, write).

role:output_from:N

The function writes argument N and all the arguments after it out of the program (printf, fprintf). A function that gives its parameter to an output gets role:output for that parameter. The value of an environment variable in an output is reported.

role:text_extract:S:B

The function reads a word from the stream in argument S into argument B (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:N

The function sets the width of the stream in argument N for the next word that is read (ios_base::width).

role:secret_source

The result is a secret (a password hash, a key).

role:secret_passes

The result is a secret when an argument is a secret.

role:copies:D:S

The function copies argument S into argument D.

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. @Override does 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:N

The function writes into the buffer in argument N.

role:bounded_copy:N

The function copies a bounded string into argument N and can leave it without a terminating null (strncpy).

role:mem_copy:D:S:L

The function copies L bytes from argument S to argument D. The regions must not overlap.

role:mem_move:D:S:L

The same, but the regions can overlap (memmove).

role:mem_fill:D:L

The function writes L bytes into argument D.

role:derefs:N

The function reads through the pointer in argument N. A null pointer there is a defect.

role:borrows:N

The function uses the block in argument N only 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:N

Argument N is a size.

role:var_param:N

Argument N is a Pascal var or out parameter. The call passes the variable, and the function can write into it (TryStrToInt).

role:returns_into:N

The result points into the buffer in argument N.

role:format:N

The format string of a printf-like function is argument N.

role:format_scan:N

The format string of a scanf-like function is argument N.

role:unbounded_format_write:N

The function writes formatted text into argument N without a size (sprintf).

role:string_read:N

The function reads argument N as 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_access

The function does not read or write the memory that its arguments point to (__builtin_object_size).

Paths

role:path_check:N

The function checks the file in argument N (access, stat).

role:path_use:N

The 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_name

The result is a name for a temporary file (mktemp, tmpnam).

role:temp_name_in:N

The function writes a name for a temporary file into argument N.

role:file_open:P:F:E...

The function opens the file in argument P with the integer flags in argument F. Each value E is the flag that makes the open fail when the file exists (O_EXCL), one value for each platform.

role:file_open_mode:P:M

The function opens the file in argument P with the mode text in argument M. The mode x makes the open fail when the file exists (fopen).

An open of a temporary name without O_EXCL or x is reported. Another process can put a file or a link under that name first.

role:temp_create:N

The function creates a temporary file and writes its name into argument N (mkstemp).

role:file_remove:N

The 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:B

The function compares argument A with argument B.

role:variable_time_compare

The comparison stops at the first difference. It leaks the position of that difference through time.

role:error_token:T

When the function fails, the result is the string T, not a null pointer (crypt of 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 T is reported. A check for null does not exclude T. 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:uid

The function sets the user IDs of the process for good (setresuid). Argument 0 is the new user.

role:privilege:groups

The function sets the supplementary groups (initgroups).

role:real_id

The function returns an ID of the user that runs the program (getuid).

role:exec

The function runs a new program in the process (execv).

A change to another user before a call with role:exec is 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:N

Argument N is 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:P

The function takes a login in argument L and a password in argument P. Use -1 when the function has no login argument.

role:security:KIND

The function is part of the security surface. KIND is password, authorization, authentication, crypto, token or privilege.

role:dangerous

The function cannot be used safely (gets, tmpnam).

role:exception_root

The 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:N

The function throws argument N (the !throw of the program model). A thrown object of the class with role:exception_root is 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:N

The 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 gets role:thread_start for that parameter.

role:signal_handler:N

The 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_handler for sigaction) 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_entry

The 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:G and role:modifies_global:G

The function reads the shared variable G, or writes it, writes through it or frees it. While a signal handler that changes G is installed, a use of G is reported. A volatile integer (sig_atomic_t) is not reported.

role:signal_handler_fn

The 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_value

The 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 in main is not reported either.

role:banned:STANDARD:RULE

A 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:TYPE

A call of the function is a finding of the type TYPE. TYPE is a report type name, for example EvalCall.

role:report_string_arg:TYPE:N

A call with a string literal in argument N is a finding of the type TYPE. The function runs that string as code (setTimeout("code", n)).

role:returns_minus_one_if_missing

The function returns -1 when it does not find the value (indexOf).

role:deletes_files

The command deletes files (rm).

role:blocking_wait

The method blocks the thread until the task in the receiver completes (C# Task.Wait).

role:builtin

The name is a builtin of the language. An assignment to the name hides the builtin (Python list = []).

role:existence_check

The function tests whether a value exists. It does not use the value (PHP isset).

role:glob_mode:N

Argument N selects the mode of the command. The modes GLOB and GLOB_RECURSE find the files one time, at configure time (CMake file).

role:minimum_version

The command sets the minimum version of the tool and the policies of that version (CMake cmake_minimum_required).

Signals

role:async_signal_safe

The function can be called from a signal handler.

role:keeps_errno

The function does not change errno. It cannot fail, or it does not return.

role:signal_handler:N

The function installs the signal handler in argument N.

Containers

role:container:OP and role:container:OP:N

A container operation. OP is create, sized (the size is argument N), empty, grow, shrink, clear, len or read.

role:iterator

The result is an iterator into the receiver.

role:invalidates_iterators

The function changes the storage of the receiver. Iterators into the receiver become invalid.

role:indexed:N

Argument N is an index into the receiver.

role:consumes_receiver

The function moves the receiver. A later use of the receiver is a defect.

Values

role:math:FUNCTION

The function computes a known mathematical function, so the analyzer can compute the result of a call with known arguments. FUNCTION is abs, fabs or sqrt. abs computes the absolute value of an integer argument. fabs also computes it for a floating argument.