valgrind-memcheck-catch.dhover×99all
#!/usr/bin/env dub
/+ dub.sdl:
    name "sanitizers_valgrind_memcheck_catch"
    platforms "linux"
    targetPath "build"
    dflags "-g"
    dependency "sparkles:core-cli" path="../../../.."
    dflags "-I$PACKAGE_DIR/.." "-i=valgrind_helpers"
+/
/**
 * Valgrind memcheck catching a heap use-after-free in an UNinstrumented D
 * binary, with a machine-parseable report: the probe re-execs itself under
 * `valgrind --xml=yes --error-exitcode=99`, the child performs the invalid
 * read, and the parent parses the XML error stream and asserts on the error
 * kind, source location, and exit code — the no-recompile pipeline a
 * `--valgrind` runner mode would drive.
 *
 *   1. The child `malloc`s, `free`s, then reads the freed block. No sanitizer
 *      flags are involved: memcheck sees the `free` through its malloc
 *      replacement, marks the block unaddressable (A bits), and flags the
 *      read as `InvalidRead`. This works identically for DMD-compiled
 *      binaries — valgrind is DMD's only memory-error path.
 *   2. `--error-exitcode=99` turns "any error was reported" into exit code 99
 *      (default: the child's own exit code), giving the runner a cheap
 *      error-occurred signal without parsing.
 *   3. `--xml=yes --xml-file=` emits the protocol-4 XML stream; the parent
 *      extracts `<kind>InvalidRead</kind>` and the `<file>`/`<line>` of the
 *      faulting frame — per-finding data a runner can attach to a test.
 *   4. Unlike ASan, the child is not killed at the fault: memcheck reports
 *      and lets the program continue (the child prints its read-after-free
 *      value and exits normally; only `--error-exitcode` marks the run).
 *
 * Companion to docs/research/sanitizers/valgrind.md
 *   § "Runtime control and report capture" (the no-recompile XML + exit-code
 *   pipeline).
 *
 * Run with: dub run --single valgrind-memcheck-catch.d
 *
 * Environment recorded: Linux 6.18.26, AMD Ryzen 9 7940HX, valgrind 3.26.0
 * (nixpkgs), LDC 1.41.0 and DMD 2.112.1 (both verified — no instrumentation
 * flags, so both compilers exercise the identical path).
 *
 * Portability: hosts without `valgrind` on `PATH` print a `SKIP:` line and
 * exit 0. Linux-only (`platforms "linux"`): nixpkgs valgrind does not build
 * on Apple Silicon.
 */
module 
(module) sanitizers_valgrind_memcheck_catch

Valgrind memcheck catching a heap use-after-free in an UNinstrumented D binary, with a machine-parseable report: the probe re-execs itself under valgrind --xml=yes --error-exitcode=99, the child performs the invalid read, and the parent parses the XML error stream and asserts on the error kind, source location, and exit code — the no-recompile pipeline a --valgrind runner mode would drive.

  1. The child mallocs, frees, then reads the freed block. No sanitizer flags are involved: memcheck sees the free through its malloc replacement, marks the block unaddressable (A bits), and flags the read as InvalidRead. This works identically for DMD-compiled binaries — valgrind is DMD's only memory-error path.

  2. --error-exitcode=99 turns "any error was reported" into exit code 99 (default: the child's own exit code), giving the runner a cheap error-occurred signal without parsing.

  3. --xml=yes --xml-file= emits the protocol-4 XML stream; the parent extracts <kind>InvalidRead</kind> and the <file>/<line> of the faulting frame — per-finding data a runner can attach to a test.

  4. Unlike ASan, the child is not killed at the fault: memcheck reports and lets the program continue (the child prints its read-after-free value and exits normally; only --error-exitcode marks the run).

Companion to docs/research/sanitizers/valgrind.md § "Runtime control and report capture" (the no-recompile XML + exit-code pipeline).

Run with: dub run --single valgrind-memcheck-catch.d

Environment recorded: Linux 6.18.26, AMD Ryzen 9 7940HX, valgrind 3.26.0 (nixpkgs), LDC 1.41.0 and DMD 2.112.1 (both verified — no instrumentation flags, so both compilers exercise the identical path).

Portability

hosts without valgrind on PATH print a SKIP: line and exit 0. Linux-only (platforms "linux"): nixpkgs valgrind does not build on Apple Silicon.

sanitizers_valgrind_memcheck_catch
;
version (
linux
linux
)
{ import
(package) std
std
.
(module) std.stdio
Category Symbols
File handles _popen File isFileHandle openNetwork stderr stdin stdout
Reading chunks lines readf readfln readln
Writing toFile write writef writefln writeln
Misc KeepTerminator LockType StdioException

Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio is publically imported when importing std.stdio.

There are three layers of I/O:

  1. The lowest layer is the operating system layer. The two main schemes are Windows and Posix.

  2. C's stdio.h which unifies the two operating system schemes.

  3. std.stdio, this module, unifies the various stdio.h implementations into a high level package for D programs.

Source

std/stdio.d

@copyrightCopyright The D Language Foundation 2007-.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Alex Rønne Petersen
stdio
:
(alias template) sanitizers_valgrind_memcheck_catch.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))

Equivalent to writef(fmt, args, '\n').

writefln
;
import
(module) valgrind_helpers

Shared helpers for the examples/valgrind-*.d probes.

Deliberately one directory above examples/: ci --example-files globs docs/research/sanitizers/examples/*.d, and a git pathspec's * matches / too — so anything under examples/, including a subdirectory, is picked up and run as an example. This file has no main and no dub.sdl header, so that would simply fail. Living here keeps it out of the glob while the examples pull it in with sourceFiles "../valgrind_helpers.d".

valgrind_helpers
:
(alias) sanitizers_valgrind_memcheck_catch.valgrindCanInstrument = bool valgrind_helpers.valgrindCanInstrument(out string reason)

Whether valgrind can actually instrument a program here — not merely whether it answers --version.

The launcher answering a version string proves only that it is on PATH. On CircleCI's AWS machine executor (kernel 6.14-aws) valgrind 3.26 answers --version, emits its full XML preamble, and then wedges: the memcheck-amd64- process sleeps in do_wait forever. A version-only probe reads that as healthy and sends an example into a hang instead of the skip it was designed to take.

So instrument something trivial under a deadline. true is the cheapest guest there is, and a valgrind that cannot finish it in valgrindProbeDeadline cannot run these examples either. The deadline is what turns a wedged valgrind into a SKIP rather than a hang — std.process.execute has no timeout, which is why this goes through executeMonitored instead.

@paramreason set to a human-readable explanation when the result is false@returnstrue when valgrind ran true to a clean exit within the deadline.
valgrindCanInstrument
;
enum
(constant) string sanitizers_valgrind_memcheck_catch.childEnvVar = "SANITIZERS_PROBE_CHILD"
childEnvVar
= "SANITIZERS_PROBE_CHILD";
/// The faulty demo the child runs: classic heap use-after-free. Memcheck /// reports the read but the program continues and exits 0 on its own. void
void sanitizers_valgrind_memcheck_catch.faultyDemo()

The faulty demo the child runs: classic heap use-after-free. Memcheck reports the read but the program continues and exits 0 on its own.

faultyDemo
()
{ import
(package) core
core
.
(package) core.stdc
stdc
.
(module) core.stdc.stdio

D header file for C99 <stdio.h>

pubs.opengroup.org/onlinepubs/009695399/basedefs/stdio.h.html, stdio.h

Source

core/stdc/stdio.d

@copyrightCopyright Sean Kelly 2005 - 2009.@licenseDistributed under the Boost Software License 1.0. (See accompanying file LICENSE)@authorsSean Kelly, Alex Rønne Petersen@standardsISO/IEC 9899:1999 (E)
stdio
:
(alias) printf = int core.stdc.stdio.printf(scope const(char*) format, scope const ...) nothrow @nogc
printf
;
import
(package) core
core
.
(package) core.stdc
stdc
.
(module) core.stdc.stdlib

D header file for C99.

pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html, stdlib.h

Source

core/stdc/stdlib.d

@copyrightCopyright Sean Kelly 2005 - 2014.@licenseDistributed under the Boost Software License 1.0. (See accompanying file LICENSE)@authorsSean Kelly@standardsISO/IEC 9899:1999 (E)
stdlib
:
(alias) free = void core.stdc.stdlib.free(void* ptr) nothrow @nogc
free
,
(alias) malloc = void* core.stdc.stdlib.malloc(ulong size) nothrow @nogc
malloc
;
int*
(local variable) int* p
p
= cast(int*)
void* core.stdc.stdlib.malloc(ulong size) nothrow @nogc
malloc
(4 * int.
(constant) ulong int.sizeof = 4LU
sizeof
);
(local variable) int* p
p
[0] = 42;
void core.stdc.stdlib.free(void* ptr) nothrow @nogc
free
(
(local variable) int* p
p
);
int core.stdc.stdio.printf(scope const(char*) format, scope const ...) nothrow @nogc
printf
("read after free: %d\n",
(local variable) int* p
p
[0]); // memcheck: InvalidRead (size 4)
} int
int sanitizers_valgrind_memcheck_catch.run()
run
()
{ import
(package) std
std
.
(package) std.algorithm
algorithm
.
(module) std.algorithm.searching

This is a submodule of std.algorithm. It contains generic searching algorithms.

Function Name Description
all all!"a > 0"([1, 2, 3, 4]) returns true because all elements are positive
any any!"a > 0"([1, 2, -3, -4]) returns true because at least one element is positive
balancedParens balancedParens("((1 + 1) / 2)", '(', ')') returns true because the string has balanced parentheses.
boyerMooreFinder find("hello world", boyerMooreFinder("or")) returns "orld" using the Boyer-Moore algorithm.
canFind canFind("hello world", "or") returns true.
count Counts all elements or elements matching a predicate, specific element or sub-range.

count([1, 2, 1]) returns 3, count([1, 2, 1], 1) returns 2 and count!"a < 0"([1, -3, 0]) returns 1. | | countUntil | countUntil(a, b) returns the number of steps taken in a to reach b; for example, countUntil("hello!", "o") returns 4. | | commonPrefix | commonPrefix("parakeet", "parachute") returns "para". | | endsWith | endsWith("rocks", "ks") returns true. | | extrema | extrema([2, 1, 3, 5, 4]) returns [1, 5]. | | find | find("hello world", "or") returns "orld" using linear search. (For binary search refer to SortedRange.) | | findAdjacent | findAdjacent([1, 2, 3, 3, 4]) returns the subrange starting with two equal adjacent elements, i.e. [3, 3, 4]. | | findAmong | findAmong("abcd", "qcx") returns "cd" because 'c' is among "qcx". | | findSkip | If a = "abcde", then findSkip(a, "x") returns false and leaves a unchanged, whereas findSkip(a, "c") advances a to "de" and returns true. | | findSplit | findSplit("abcdefg", "de") returns a tuple of three ranges "abc", "de", and "fg". | | findSplitAfter | findSplitAfter("abcdefg", "de") returns a tuple of two ranges "abcde" and "fg". | | findSplitBefore | findSplitBefore("abcdefg", "de") returns a tuple of two ranges "abc" and "defg". | | minCount | minCount([2, 1, 1, 4, 1]) returns tuple(1, 3). | | maxCount | maxCount([2, 4, 1, 4, 1]) returns tuple(4, 2). | | minElement | Selects the minimal element of a range. minElement([3, 4, 1, 2]) returns 1. | | maxElement | Selects the maximal element of a range. maxElement([3, 4, 1, 2]) returns 4. | | minIndex | Index of the minimal element of a range. minIndex([3, 4, 1, 2]) returns 2. | | maxIndex | Index of the maximal element of a range. maxIndex([3, 4, 1, 2]) returns 1. | | minPos | minPos([2, 3, 1, 3, 4, 1]) returns the subrange [1, 3, 4, 1], i.e., positions the range at the first occurrence of its minimal element. | | maxPos | maxPos([2, 3, 1, 3, 4, 1]) returns the subrange [4, 1], i.e., positions the range at the first occurrence of its maximal element. | | skipOver | Assume a = "blah". Then skipOver(a, "bi") leaves a unchanged and returns false, whereas skipOver(a, "bl") advances a to refer to "ah" and returns true. | | startsWith | startsWith("hello, world", "hello") returns true. | | until | Lazily iterates a range until a specific value is found. |

Source

std/algorithm/searching.d

@copyrightAndrei Alexandrescu 2008-.@licenseBoost License 1.0.@authorsAndrei Alexandrescu
searching
:
(alias template) canFind = std.algorithm.searching.canFind(alias pred = "a == b")

Convenience function. Like find, but only returns whether or not the search was successful.

For more information about pred see $(LREF find).

See_Also: $(REF among, std,algorithm,comparison) for checking a value against multiple arguments.

canFind
,
(alias template) find = std.algorithm.searching.find(alias pred, InputRange)(InputRange haystack) if (isInputRange!InputRange)

Finds an element e of an $(REF_ALTTEXT input range, isInputRange, std,range,primitives) where `pred(e)` is `true`. $(P $(PANEL $(UL $(LI `find` behaves similarly to `dropWhile` in other languages.) $(LI To _find the last matching element in a $(REF_ALTTEXT bidirectional, isBidirectionalRange, std,range,primitives) `haystack`, call `find!pred(retro(haystack))`. See $(REF retro, std,range).) )))

Complexity: find performs $(BIGOH walkLength(haystack)) evaluations of pred.

Params:

    pred = The predicate to match an element.
    haystack = The $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
               searched in.

Returns: haystack advanced such that the front element satisfies pred. If no such element exists, returns an empty haystack.

find
;
import
(package) std
std
.
(module) std.file

Utilities for manipulating files and scanning directories. Functions in this module handle files as a unit, e.g., read or write one file at a time. For opening files and manipulating them via handles refer to module std.stdio.

Category Functions
General exists isDir isFile isSymlink rename thisExePath
Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir
Files append copy read readText remove slurp write
Symlinks symlink readLink
Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes
Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged
Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace

Source

std/file.d

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias template) exists = std.file.exists(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Determine whether the given file (or directory) _exists. Params: name = string or range of characters representing the file _name Returns: true if the file name specified as input exists

exists
,
(alias template) readText = std.file.readText(S = string, R)(auto ref R name) if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)))

Reads and validates (using $(REF validate, std, utf)) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail.

    Params:
        S = the string type of the file
        name = string or range of characters representing the file _name

    Returns: Array of characters read.

    Throws: $(LREF FileException) if there is an error reading the file,
            $(REF UTFException, std, utf) on UTF decoding error.

    See_Also: $(REF read, std,file) for reading a binary file.
readText
,
(alias template) remove = std.file.remove(R)(R name) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)

Delete file name.

Params: name = string or range of characters representing the file _name

Throws: $(LREF FileException) on error.

remove
,
(alias) tempDir = string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist: $(OL $(LI The directory given by the TMPDIR environment variable.) $(LI The directory given by the `TEMP` environment variable.) $(LI The directory given by the TMP environment variable.) $(LI `/tmp/`) $(LI /var/tmp/) $(LI /usr/tmp/) )

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's $(LINK2 http://docs.python.org/library/tempfile.html#tempfile.tempdir, tempfile.tempdir).

Returns: On Windows, this function returns the result of calling the Windows API function $(LINK2 http://msdn.microsoft.com/en-us/library/windows/desktop/aa364992.aspx, GetTempPath).

    On POSIX platforms, it searches through the following list of directories
    and returns the first one which is found to exist:
    $(OL
        $(LI The directory given by the `TMPDIR` environment variable.)
        $(LI The directory given by the `TEMP` environment variable.)
        $(LI The directory given by the `TMP` environment variable.)
        $(LI `/tmp`)
        $(LI `/var/tmp`)
        $(LI `/usr/tmp`)
    )

    On all platforms, `tempDir` returns `"."` on failure, representing
    the current working directory.
tempDir
;
import
(package) std
std
.
(module) std.format

This package provides string formatting functionality using printf style format strings.

Submodule Function Name Description
package
format
Converts its arguments according to a format string into a string.

| package | sformat | Converts its arguments according to a format string into a buffer. |

| package | FormatException | Signals a problem while formatting. |

| write | formattedWrite | Converts its arguments according to a format string and writes the result to an output range. |

| write | formatValue | Formats a value of any type according to a format specifier and writes the result to an output range. |

| read | formattedRead | Reads an input range according to a format string and stores the read values into its arguments. |

| read | unformatValue | Reads a value from the given input range and converts it according to a format specifier. |

| spec | FormatSpec | A general handler for format strings. |

| spec | singleSpec | Helper function that returns a FormatSpec for a single format specifier. |

Limitation

This package does not support localization, but adheres to the rounding mode of the floating point unit, if available.

Format Strings

The functions contained in this package use format strings. A format string describes the layout of another string for reading or writing purposes. A format string is composed of normal text interspersed with format specifiers. A format specifier starts with a percentage sign '%', optionally followed by one or more parameters and ends with a format indicator. A format indicator may be a simple format character or a compound indicator.

Format strings are composed according to the following grammar:

FormatString: FormatStringItem FormatString FormatStringItem: Character FormatSpecifier FormatSpecifier: '%' Parameters FormatIndicator

FormatIndicator: FormatCharacter CompoundIndicator FormatCharacter: see remark below CompoundIndicator: '(' FormatString '%)' '(' FormatString '%|' Delimiter '%)' Delimiter empty Character Delimiter

Parameters: Position Flags Width Precision Separator Position: empty Integer '$'** *Integer* **':'** *Integer* **'$' Integer ':' '$'** *Flags*: *empty* *Flag* *Flags* *Flag*: **'-'**|**'+'**|**'&nbsp;'**|**'0'**|**'#'**|**'='** *Width*: *OptionalPositionalInteger* *Precision*: *empty* **'.'** *OptionalPositionalInteger* *Separator*: *empty* **','** *OptionalInteger* **','** *OptionalInteger* **'?'** *OptionalInteger*: *empty* *Integer* **'*'** *OptionalPositionalInteger*: *OptionalInteger* **'*'** *Integer* **'$'

Character '%%' AnyCharacterExceptPercent Integer: NonZeroDigit Digits Digits: empty Digit Digits NonZeroDigit: '1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9' Digit: '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7'|'8'|'9'

Note

FormatCharacter is unspecified. It can be any character that has no other purpose in this grammar, but it is recommended to assign (lower- and uppercase) letters.

Note

The Parameters of a CompoundIndicator are currently limited to a '-' flag.

Format Indicator

The format indicator can either be a single character or an expression surrounded by '%(' and '%)'. It specifies the basic manner in which a value will be formatted and is the minimum requirement to format a value.

The following characters can be used as format characters:

FormatCharacter Semantics
's'
To be formatted in a human readable format.
Can be used with all types.
'c'
To be formatted as a character.
'd'
To be formatted as a signed decimal integer.
'u'
To be formatted as a decimal image of the underlying bit representation.
'b'
To be formatted as a binary image of the underlying bit representation.
'o'
To be formatted as an octal image of the underlying bit representation.
'x' / 'X'
To be formatted as a hexadecimal image of the underlying bit representation.
'e' / 'E'
To be formatted as a real number in decimal scientific notation.
'f' / 'F'
To be formatted as a real number in decimal natural notation.
'g' / 'G'
To be formatted as a real number in decimal short notation.
Depending on the number, a scientific notation or
a natural notation is used.
'a' / 'A'
To be formatted as a real number in hexadecimal scientific notation.
'r'
To be formatted as raw bytes.
The output may not be printable and depends on endianness.

The compound indicator can be used to describe compound types like arrays or structs in more detail. A compound type is enclosed within '%(' and '%)'. The enclosed sub-format string is applied to individual elements. The trailing portion of the sub-format string following the specifier for the element is interpreted as the delimiter, and is therefore omitted following the last element. The '%|' specifier may be used to explicitly indicate the start of the delimiter, so that the preceding portion of the string will be included following the last element.

The format string inside of the compound indicator should contain exactly one format specifier (two in case of associative arrays), which specifies the formatting mode of the elements of the compound type. This format specifier can be a compound indicator itself.

Note

Inside a compound indicator, strings and characters are escaped automatically. To avoid this behavior, use "%-(" instead of "%(".

Flags

There are several flags that affect the outcome of the formatting.

Flag Semantics
'-'
When the formatted result is shorter than the value
given by the width parameter, the output is left
justified. Without the '-' flag, the output remains
right justified.

There are two exceptions where the '-' flag has a different meaning: (1) with 'r' it denotes to use little endian and (2) in case of a compound indicator it means that no special handling of the members is applied. | | '=' | When the formatted result is shorter than the value given by the width parameter, the output is centered. If the central position is not possible it is moved slightly to the right. In this case, if '-' flag is present in addition to the '=' flag, it is moved slightly to the left. | | '+'&nbsp;/&nbsp;*'&nbsp;'* | Applies to numerical values. By default, positive numbers are not formatted to include the + sign. With one of these two flags present, positive numbers are preceded by a plus sign or a space. When both flags are present, a plus sign is used.

In case of 'r', a big endian format is used. | | '0' | Is applied to numerical values that are printed right justified. If the zero flag is present, the space left to the number is filled with zeros instead of spaces. | | '#' | Denotes that an alternative output must be used. This depends on the type to be formatted and the format character used. See the sections below for more information. |

Width, Precision and Separator

The width parameter specifies the minimum width of the result.

The meaning of precision depends on the format indicator. For integers it denotes the minimum number of digits printed, for real numbers it denotes the number of fractional digits and for strings and compound types it denotes the maximum number of elements that are included in the output.

A separator is used for formatting numbers. If it is specified, the output is divided into chunks of three digits, separated by a ','. The number of digits in a chunk can be given explicitly by providing a number or a ''* after the ','.

In all three cases the number of digits can be replaced by a ''*. In this scenario, the next argument is used as the number of digits. If the argument is a negative number, the precision and separator parameters are considered unspecified. For width, the absolute value is used and the '-' flag is set.

The separator can also be followed by a '?'. In that case, an additional argument is used to specify the symbol that should be used to separate the chunks.

Position

By default, the arguments are processed in the provided order. With the position parameter it is possible to address arguments directly. It is also possible to denote a series of arguments with two numbers separated by ':', that are all processed in the same way. The second number can be omitted. In that case the series ends with the last argument.

It's also possible to use positional arguments for width, precision and separator by adding a number and a '$' after the ''*.

Types

This section describes the result of combining types with format characters. It is organized in 2 subsections: a list of general information regarding the formatting of types in the presence of format characters and a table that contains details for every available combination of type and format character.

When formatting types, the following rules apply:

  • If the format character is upper case, the resulting string will be formatted using upper case letters.

  • The default precision for floating point numbers is 6 digits.

  • Rounding of floating point numbers adheres to the rounding mode of the floating point unit, if available.

  • The floating point values NaN and Infinity are formatted as nan and inf, possibly preceded by '+' or '-' sign.

  • Formatting reals is only supported for 64 bit reals and 80 bit reals. All other reals are cast to double before they are formatted. This will cause the result to be inf for very large numbers.

  • Characters and strings formatted with the 's' format character inside of compound types are surrounded by single and double quotes and unprintable characters are escaped. To avoid this, a '-' flag can be specified for the compound specifier (e.g. "%-(%s%)" instead of "%(%s%)" ).

  • Structs, unions, classes and interfaces are formatted by calling a toString method if available. See module std.format.write for more details.

  • Only part of these combinations can be used for reading. See module std.format.read for more detailed information.

This table contains descriptions for every possible combination of type and format character:

<th scope="col" width="20%">Type</th> <th scope="col" width="20%">Format Character</th> Formatted as...
<td rowspan="1">null</td> 's'
null

|<td rowspan="3">bool</td> 's' | false or true |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integrals 0 or 1 with the same format character.

Please note, that 'o' and 'x' with '#' flag might produce unexpected results due to special handling of the value 0. |

| 'r' | \0 or \1 |

|<td rowspan="4">Integral</td> 's', 'd' | A signed decimal number. The '#' flag is ignored. |

| 'b', 'o', 'u', 'x', 'X' | An unsigned binary, decimal, octal or hexadecimal number.

In case of 'o' and 'x', the '#' flag denotes that the number must be preceded by 0 and 0x, with the exception of the value 0, where this does not apply. For 'b' and 'u' the '#' flag has no effect. |

| 'e', 'E', 'f', 'F', 'g', 'G', 'a', 'A' | As a floating point value with the same specifier.

Default precision is large enough to add all digits of the integral value.

In case of 'a' and 'A', the integral digit can be any hexadecimal digit. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="5">Floating Point</td> 'e', 'E' | Scientific notation: Exactly one integral digit followed by a dot and fractional digits, followed by the exponent. The exponent is formatted as 'e' followed by a '+' or '-' sign, followed by at least two digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'f', 'F' | Natural notation: Integral digits followed by a dot and fractional digits.

When there are no fractional digits and the '#' flag is not present, the dot is omitted.

Please note: the difference between 'f' and 'F' is only visible for NaN and Infinity. |

| 's', 'g', 'G' | Short notation: If the absolute value is larger than 10 ^^ precision or smaller than 0.0001, the scientific notation is used. If not, the natural notation is applied.

In both cases precision denotes the count of all digits, including the integral digits. Trailing zeros (including a trailing dot) are removed.

If '#' flag is present, trailing zeros are not removed. |

| 'a', 'A' | Hexadecimal scientific notation: 0x followed by 1 (or 0 in case of value zero or denormalized number) followed by a dot, fractional digits in hexadecimal notation and an exponent. The exponent is build by p, followed by a sign and the exponent in decimal notation.

When there are no fractional digits and the '#' flag is not present, the dot is omitted. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">Character</td> 's', 'c' | As the character.

Inside of a compound indicator 's' is treated differently: The character is surrounded by single quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'b', 'd', 'o', 'u', 'x', 'X' | As the integral that represents the character. |

| 'r' | Characters taken directly from the binary representation. |

|<td rowspan="3">String</td> 's' | The sequence of characters that form the string.

Inside of a compound indicator the string is surrounded by double quotes and non printable characters are escaped. This can be avoided by preceding the compound indicator with a '-' flag (e.g. "%-(%s%)"). |

| 'r' | The sequence of characters, each formatted with 'r'. |

| compound | As an array of characters. |

|<td rowspan="3">Array</td> 's' | When the elements are characters, the array is formatted as a string. In all other cases the array is surrounded by square brackets and the elements are separated by a comma and a space. If the elements are strings, they are surrounded by double quotes and non printable characters are escaped. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="2">Associative Array</td> 's' | As a sequence of the elements in unpredictable order. The output is surrounded by square brackets. The elements are separated by a comma and a space. The elements are formatted as key:value. |

| compound | As a sequence of the elements in unpredictable order. Each element is formatted according to the specifications given inside of the compound specifier. The first specifier is used for formatting the key and the second specifier is used for formatting the value. The order can be changed with positional arguments. For example "%(%2$s (%1$s), %)" will write the value, followed by the key in parenthesis. |

|<td rowspan="2">Enum</td> 's' | The name of the value. If the name is not available, the base value is used, preceeded by a cast. |

| All, but 's' | Enums can be formatted with all format characters that can be used with the base value. In that case they are formatted like the base value. |

|<td rowspan="3">Input Range</td> 's' | When the elements of the range are characters, they are written like a string. In all other cases, the elements are enclosed by square brackets and separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Struct</td> 's' | When the struct has neither an applicable toString nor is an input range, it is formatted as follows: StructType(field1, field2, ...). |

|<td rowspan="1">Class</td> 's' | When the class has neither an applicable toString nor is an input range, it is formatted as the fully qualified name of the class. |

|<td rowspan="1">Union</td> 's' | When the union has neither an applicable toString nor is an input range, it is formatted as its base name. |

|<td rowspan="2">Pointer</td> 's' | A null pointer is formatted as 'null'. All other pointers are formatted as hexadecimal numbers with the format character 'X'. |

| 'x', 'X' | Formatted as a hexadecimal number. |

|<td rowspan="3">SIMD vector</td> 's' | The array is surrounded by square brackets and the elements are separated by a comma and a space. |

| 'r' | The sequence of the elements, each formatted with 'r'. |

| compound | The sequence of the elements, each formatted according to the specifications given inside of the compound specifier. |

|<td rowspan="1">Delegate</td> 's', 'r', compound | As the .stringof of this delegate treated as a string.

Please note: The implementation is currently buggy and its use is discouraged. |

Source

std/format/package.d

Examples

Simple use:

// Easiest way is to use `%s` everywhere:
assert(format("I got %s %s for %s euros.", 30, "eggs", 5.27) == "I got 30 eggs for 5.27 euros.");

// Other format characters provide more control:
assert(format("I got %b %(%X%) for %f euros.", 30, "eggs", 5.27) == "I got 11110 65676773 for 5.270000 euros.");

Compound specifiers allow formatting arrays and other compound types:

/*
The trailing end of the sub-format string following the specifier for
each item is interpreted as the array delimiter, and is therefore
omitted following the last array item:
 */
    assert(format("My items are %(%s %).", [1,2,3]) == "My items are 1 2 3.");
    assert(format("My items are %(%s, %).", [1,2,3]) == "My items are 1, 2, 3.");

/*
The "%|" delimiter specifier may be used to indicate where the
delimiter begins, so that the portion of the format string prior to
it will be retained in the last array element:
 */
    assert(format("My items are %(-%s-%|, %).", [1,2,3]) == "My items are -1-, -2-, -3-.");

/*
These compound format specifiers may be nested in the case of a
nested array argument:
 */
    auto mat = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]];

    assert(format("%(%(%d %) - %)", mat), "1 2 3 - 4 5 6 - 7 8 9");
    assert(format("[%(%(%d %) - %)]", mat), "[1 2 3 - 4 5 6 - 7 8 9]");
    assert(format("[%([%(%d %)]%| - %)]", mat), "[1 2 3] - [4 5 6] - [7 8 9]");

/*
Strings and characters are escaped automatically inside compound
format specifiers. To avoid this behavior, use "%-(" instead of "%(":
 */
    assert(format("My friends are %s.", ["John", "Nancy"]) == `My friends are ["John", "Nancy"].`);
    assert(format("My friends are %(%s, %).", ["John", "Nancy"]) == `My friends are "John", "Nancy".`);
    assert(format("My friends are %-(%s, %).", ["John", "Nancy"]) == `My friends are John, Nancy.`);

Using parameters:

// Flags can be used to influence to outcome:
assert(format("%g != %+#g", 3.14, 3.14) == "3.14 != +3.14000");

// Width and precision help to arrange the formatted result:
assert(format(">%10.2f<", 1234.56789) == ">   1234.57<");

// Numbers can be grouped:
assert(format("%,4d", int.max) == "21,4748,3647");

// It's possible to specify the position of an argument:
assert(format("%3$s %1$s", 3, 17, 5) == "5 3");

Providing parameters as arguments:

// Width as argument
assert(format(">%*s<", 10, "abc") == ">       abc<");

// Precision as argument
assert(format(">%.*f<", 5, 123.2) == ">123.20000<");

// Grouping as argument
assert(format("%,*d", 1, int.max) == "2,1,4,7,4,8,3,6,4,7");

// Grouping separator as argument
assert(format("%,3?d", '_', int.max) == "2_147_483_647");

// All at once
assert(format("%*.*,*?d", 20, 15, 6, '/', int.max) == "   000/002147/483647");
@copyrightCopyright The D Language Foundation 2000-2021.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, and Kenji Hara
format
:
(alias template) format = std.format.format(Char, Args...)(in Char[] fmt, Args args) if (isSomeChar!Char)

Converts its arguments according to a format string into a string.

The second version of format takes the format string as template argument. In this case, it is checked for consistency at compile-time and produces slightly faster code, because the length of the output buffer can be estimated in advance.

Params: fmt = a $(MREF_ALTTEXT format string, std,format) args = a variadic list of arguments to be formatted Char = character type of fmt Args = a variadic list of types of the arguments

Returns: The formatted string.

Throws: A $(LREF FormatException) if formatting did not succeed.

See_Also: $(LREF sformat) for a variant, that tries to avoid garbage collection.

format
;
import
(package) std
std
.
(module) std.path

This module is used to manipulate path strings.

All functions, with the exception of expandTilde (and in some cases absolutePath and relativePath), are pure string manipulation functions; they don't depend on any state outside the program, nor do they perform any actual file system actions. This has the consequence that the module does not make any distinction between a path that points to a directory and a path that points to a file, and it does not know whether or not the object pointed to by the path actually exists in the file system. To differentiate between these cases, use isDir and exists.

Note that on Windows, both the backslash (\) and the slash (/) are in principle valid directory separators. This module treats them both on equal footing, but in cases where a new separator is added, a backslash will be used. Furthermore, the buildNormalizedPath function will replace all slashes with backslashes on that platform.

In general, the functions in this module assume that the input paths are well-formed. (That is, they should not contain invalid characters, they should follow the file system's path format, etc.) The result of calling a function on an ill-formed path is undefined. When there is a chance that a path or a file name is invalid (for instance, when it has been input by the user), it may sometimes be desirable to use the isValidFilename and isValidPath functions to check this.

Most functions do not perform any memory allocations, and if a string is returned, it is usually a slice of an input string. If a function allocates, this is explicitly mentioned in the documentation.

Category Functions
Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde
Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive
Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath
Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension
Other filenameCharCmp filenameCmp globMatch CaseSensitive

Source

std/path.d

@authorsLars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Khne, Andrei Alexandrescu@copyrightCopyright (c) 2000-2014, the authors. All rights reserved.@licenseBoost License 1.0
path
:
(alias template) buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))

Combines one or more path segments.

    This function takes a set of path segments, given as an input
    range of string elements or as a set of string arguments,
    and concatenates them with each other.  Directory separators
    are inserted between segments if necessary.  If any of the
    path segments are absolute (as defined by $(LREF isAbsolute)), the
    preceding segments will be dropped.

    On Windows, if one of the path segments are rooted, but not absolute
    (e.g. $(D `\foo`)), all preceding path segments down to the previous
    root will be dropped.  (See below for an example.)

    This function always allocates memory to hold the resulting path.
    The variadic overload is guaranteed to only perform a single
    allocation, as is the range version if `paths` is a forward
    range.

    Params:
        segments = An $(REF_ALTTEXT input range, isInputRange, std,range,primitives)
        of segments to assemble the path from.
    Returns: The assembled path.
buildPath
;
import
(package) std
std
.
(module) std.process

Functions for starting and interacting with other processes, and for working with the current process' execution environment.

Process handling

  • `spawnProcess` spawns a new `process`, optionally assigning it an
        

    arbitrary set of standard input, output, and error streams. The function returns immediately, leaving the child process to execute in parallel with its parent. All other functions in this module that spawn processes are built around spawnProcess.

  • `wait` makes the parent `process` wait for a child `process` to
        

    terminate. In general one should always do this, to avoid child processes becoming "zombies" when the parent process exits. Scope guards are perfect for this – see the spawnProcess documentation for examples. tryWait is similar to wait, but does not block if the process has not yet terminated.

  • `pipeProcess` also spawns a child `process` which runs
        

    in parallel with its parent. However, instead of taking arbitrary streams, it automatically creates a set of pipes that allow the parent to communicate with the child through the child's standard input, output, and/or error streams. This function corresponds roughly to C's popen function.

  • `execute` starts a new `process` and waits for it
        

    to complete before returning. Additionally, it captures the process' standard output and error streams and returns the output of these as a string.

  • `spawnShell`, `pipeShell` and `executeShell` work like
        

    spawnProcess, pipeProcess and execute, respectively, except that they take a single command string and run it through the current user's default command interpreter. executeShell corresponds roughly to C's system function.

  • `kill` attempts to terminate a running `process`.
    
    

The following table compactly summarises the different process creation functions and how they relate to each other:

Runs program directly
Runs shell command
Low-level process creation
spawnProcess
spawnShell
Automatic input/output redirection using pipes
pipeProcess
pipeShell
Execute and wait for completion, collect output
execute
executeShell

Other functionality

  • `pipe` is used to create unidirectional pipes.
    
  • `environment` is an interface through which the current `process`'
        

    environment variables can be read and manipulated.

  • `escapeShellCommand` and `escapeShellFileName` are useful
        

    for constructing shell command lines in a portable way.

Source

std/process.d

Note

Most of the functionality in this module is not available on iOS, tvOS and watchOS. The only functions available on those platforms are: environment, thisProcessID and thisThreadID.

@authorsLars Tandle Kyllingstad, Steven Schveighoffer, Vladimir Panteleev@copyrightCopyright (c) 2013, the authors. All rights reserved.@licenseBoost License 1.0.
process
:
(class) std.process.environment

Manipulates environment variables using an associative-array-like interface.

This class contains only static methods, and cannot be instantiated. See below for examples of use.

environment
,
(alias) execute = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safe

Executes the given program or shell command and returns its exit code and output.

execute and executeShell start a new process using $(LREF spawnProcess) and $(LREF spawnShell), respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code.

auto dmd = execute("dmd", "myapp.d"); if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l"); if (ls.status != 0) writeln("Failed to retrieve file listing"); else writeln(ls.output);

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

Params: args = An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See $(LREF spawnProcess) for details.) program = The program name, $(I without) command-line arguments. (See $(LREF spawnProcess) for details.) command = A shell command which is passed verbatim to the command interpreter. (See $(LREF spawnShell) for details.) env = Additional environment variables for the child process. (See $(LREF spawnProcess) for details.) config = Flags that control process creation. See $(LREF Config) for an overview of available flags, and note that the retainStd... flags have no effect in this function. maxOutput = The maximum number of bytes of output that should be captured. workDir = The working directory for the new process. By default the child process inherits the parent's working directory. shellPath = The path to the shell to use to run the specified program. By default this is $(LREF nativeShell).

Returns: An $(D std.typecons.Tuple!(int, "status", string, "output")).

POSIX_specific: If the process is terminated by a signal, the status field of the return value will contain a negative number whose absolute value is the signal number. (See $(LREF wait) for details.)

Throws: $(LREF ProcessException) on failure to start the process.$(BR) $(REF StdioException, std,stdio) on failure to capture output.

execute
,
(alias) thisProcessID = int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example:

writefln("Current process ID: %d", thisProcessID); ---

thisProcessID
;
if (
(class) std.process.environment

Manipulates environment variables using an associative-array-like interface.

This class contains only static methods, and cannot be instantiated. See below for examples of use.

environment
.
string std.process.environment.get(scope const(char)[] name, string defaultValue = null) @safe

Retrieves the value of the environment variable with the given name, or a default value if the variable doesn't exist.

Unlike environment.opIndex, this function never throws on Posix.

auto sh = environment.get("SHELL", "/bin/sh");

This function is also useful in checking for the existence of an environment variable.

auto myVar = environment.get("MYVAR");
if (myVar is null)
{
    // Environment variable doesn't exist.
    // Note that we have to use 'is' for the comparison, since
    // myVar == null is also true if the variable exists but is
    // empty.
}
@paramname name of the environment variable to retrieve@paramdefaultValue default value to return if the environment variable doesn't exist.@returnsthe value of the environment variable if found, otherwise null if the environment doesn't exist.@throwsUTFException if the variable contains invalid UTF-16 characters (Windows only).
get
(
(constant) string sanitizers_valgrind_memcheck_catch.childEnvVar = "SANITIZERS_PROBE_CHILD"
childEnvVar
) == "valgrind-uaf")
{
void sanitizers_valgrind_memcheck_catch.faultyDemo()

The faulty demo the child runs: classic heap use-after-free. Memcheck reports the read but the program continues and exits 0 on its own.

faultyDemo
();
return 0; // memcheck reports; the child itself exits cleanly } // Parent: require valgrind on PATH, else SKIP (the devshell carries // it; bare `nix run .#ci` hosts may not).
(alias) object.string = string
string
(local variable) string whyNotUsable
whyNotUsable
;
if (!
bool valgrind_helpers.valgrindCanInstrument(out string reason)

Whether valgrind can actually instrument a program here — not merely whether it answers --version.

The launcher answering a version string proves only that it is on PATH. On CircleCI's AWS machine executor (kernel 6.14-aws) valgrind 3.26 answers --version, emits its full XML preamble, and then wedges: the memcheck-amd64- process sleeps in do_wait forever. A version-only probe reads that as healthy and sends an example into a hang instead of the skip it was designed to take.

So instrument something trivial under a deadline. true is the cheapest guest there is, and a valgrind that cannot finish it in valgrindProbeDeadline cannot run these examples either. The deadline is what turns a wedged valgrind into a SKIP rather than a hang — std.process.execute has no timeout, which is why this goes through executeMonitored instead.

@paramreason set to a human-readable explanation when the result is false@returnstrue when valgrind ran true to a clean exit within the deadline.
valgrindCanInstrument
(
(local variable) string whyNotUsable
whyNotUsable
))
{
void std.stdio.writefln!(char, string)(in char[] fmt, string __param_1) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("SKIP: %s",
(local variable) string whyNotUsable
whyNotUsable
);
return 0; }
void std.stdio.writefln!char(in char[] fmt) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("using valgrind");
import
(package) std
std
.
(module) std.file

Utilities for manipulating files and scanning directories. Functions in this module handle files as a unit, e.g., read or write one file at a time. For opening files and manipulating them via handles refer to module std.stdio.

Category Functions
General exists isDir isFile isSymlink rename thisExePath
Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir
Files append copy read readText remove slurp write
Symlinks symlink readLink
Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes
Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged
Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace

Source

std/file.d

@copyrightCopyright The D Language Foundation 2007 - 2011.@seeThe official tutorial for an introduction to working with files in D, module std.stdio for opening files and manipulating them via handles, and module std.path for manipulating path strings.@licenseBoost License 1.0.@authorsWalter Bright, Andrei Alexandrescu, Jonathan M Davis
file
:
(alias) thisExePath = string std.file.thisExePath() @trusted

Returns the full path of the current executable.

Returns: The path of the executable as a string.

Throws: $(REF1 Exception, object)

thisExePath
;
const
(local variable) const(string) xmlFile
xmlFile
=
string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safe

Combines one or more path segments.

This function takes a set of path segments, given as an input range of string elements or as a set of string arguments, and concatenates them with each other. Directory separators are inserted between segments if necessary. If any of the path segments are absolute (as defined by isAbsolute), the preceding segments will be dropped.

On Windows, if one of the path segments are rooted, but not absolute (e.g. \foo), all preceding path segments down to the previous root will be dropped. (See below for an example.)

This function always allocates memory to hold the resulting path. The variadic overload is guaranteed to only perform a single allocation, as is the range version if paths is a forward range.

Examples

version (Posix)
{
    assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
    assert(buildPath("/foo/", "bar/baz")  == "/foo/bar/baz");
    assert(buildPath("/foo", "/bar")      == "/bar");
}

version (Windows)
{
    assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
    assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
    assert(buildPath("foo", `d:\bar`)     == `d:\bar`);
    assert(buildPath("foo", `\bar`)       == `\bar`);
    assert(buildPath(`c:\foo`, `\bar`)    == `c:\bar`);
}
@paramsegments An input range of segments to assemble the path from.@returnsThe assembled path.
buildPath
(
string std.file.tempDir() @trusted

Returns the path to a directory for temporary files. On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp/

  5. /var/tmp/

  6. /usr/tmp/

On all platforms, tempDir returns the current working directory on failure.

The return value of the function is cached, so the procedures described below will only be performed the first time the function is called. All subsequent runs will return the same string, regardless of whether environment variables and directory structures have changed in the meantime.

The POSIX tempDir algorithm is inspired by Python's tempfile.tempdir.

Examples

import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;

// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;

myFile.write("hello");
assert(myFile.readText == "hello");
@returns

On Windows, this function returns the result of calling the Windows API function GetTempPath.

On POSIX platforms, it searches through the following list of directories and returns the first one which is found to exist:

  1. The directory given by the TMPDIR environment variable.

  2. The directory given by the TEMP environment variable.

  3. The directory given by the TMP environment variable.

  4. /tmp

  5. /var/tmp

  6. /usr/tmp

On all platforms, tempDir returns "." on failure, representing the current working directory.

tempDir
,
string std.format.format!("vg-memcheck-catch-%d.xml", int)(int __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"vg-memcheck-catch-%d.xml"(
int std.process.thisProcessID() nothrow @nogc @property @trusted

Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example

writefln("Current process ID: %d", thisProcessID);
thisProcessID
));
scope (exit) if (
(local variable) const(string) xmlFile
xmlFile
.
bool std.file.exists!string(string name) nothrow @nogc @safe

Determine whether the given file (or directory) exists.

@paramname string or range of characters representing the file name@returnstrue if the file name specified as input exists
exists
)
(local variable) const(string) xmlFile
xmlFile
.
void std.file.remove!string(string name) @safe

Delete file name.

@paramname string or range of characters representing the file name@throwsFileException on error.
remove
();
const
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) child
child
=
std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safe

Executes the given program or shell command and returns its exit code and output.

execute and executeShell start a new process using spawnProcess and spawnShell, respectively, and wait for the process to complete before returning. The functions capture what the child process prints to both its standard output and standard error streams, and return this together with its exit code.

auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);

auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);

The args/program/command, env and config parameters are forwarded straight to the underlying spawn functions, and we refer to their documentation for details.

POSIX specific

If the process is terminated by a signal, the status field of the return value will contain a negative number whose absolute value is the signal number. (See wait for details.)

@paramargs An array which contains the program name as the zeroth element and any command-line arguments in the following elements. (See spawnProcess for details.)@paramprogram The program name, without command-line arguments. (See spawnProcess for details.)@paramcommand A shell command which is passed verbatim to the command interpreter. (See spawnShell for details.)@paramenv Additional environment variables for the child process. (See spawnProcess for details.)@paramconfig Flags that control process creation. See Config for an overview of available flags, and note that the retainStd... flags have no effect in this function.@parammaxOutput The maximum number of bytes of output that should be captured.@paramworkDir The working directory for the new process. By default the child process inherits the parent's working directory.@paramshellPath The path to the shell to use to run the specified program. By default this is nativeShell.@returnsAn std.typecons.Tuple!(int, "status", string, "output").@throws

ProcessException on failure to start the process.

StdioException on failure to capture output.

execute
(
[ "valgrind", "--xml=yes", "--xml-file=" ~
(local variable) const(string) xmlFile
xmlFile
,
"--error-exitcode=99",
string std.file.thisExePath() @trusted

Returns the full path of the current executable.

Examples

import std.path : isAbsolute;
auto path = thisExePath();

assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
@returnsThe path of the executable as a string.@throwsException
thisExePath
], [
(constant) string sanitizers_valgrind_memcheck_catch.childEnvVar = "SANITIZERS_PROBE_CHILD"
childEnvVar
: "valgrind-uaf"]);
// 1. --error-exitcode: an error was reported, so valgrind exits 99 // even though the child itself exited 0 (memcheck keeps it alive). assert(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) child
child
.status == 99,
string std.format.format!("expected exit 99 from --error-exitcode, got %d", const(int))(const(int) __param_0) pure @safe

Examples

The format string can be checked at compile-time:

auto s = format!"%s is %s"("Pi", 3.14);
assert(s == "Pi is 3.14");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// s = format!"%s is %d"("Pi", 3.14);
format
!"expected exit 99 from --error-exitcode, got %d"(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) child
child
.status));
void std.stdio.writefln!(char, const(int))(in char[] fmt, const(int) __param_1) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("child exit code: %d (from --error-exitcode; the child itself exited 0)",
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) child
child
.status);
// 2. The child ran PAST the defect — the no-halt contrast to ASan. assert(
(local variable) const(std.typecons.Tuple!(int, "status", string, "output")) child
child
.output.
bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safe

Convenience function. Like find, but only returns whether or not the search was successful.

For more information about pred see find.

Examples

const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));

// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);

assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);

Example using a custom predicate. Note that the needle appears as the second argument of the predicate.

auto words = [
    "apple",
    "beeswax",
    "cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));

Search for multiple items in an array of items (search for needles in an array of haystacks)

string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
("read after free: 42"),
"child should continue past the invalid read");
void std.stdio.writefln!(char, string)(in char[] fmt, string __param_1) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("child continued past the defect: %s", "read after free: 42");
// 3. The XML stream carries the parseable finding. const
(local variable) const(string) xml
xml
=
string std.file.readText!(string, const(string))(ref const(string) name) @safe

Reads and validates (using validate) a text file. S can be an array of any character type. However, no width or endian conversions are performed. So, if the width or endianness of the characters in the given file differ from the width or endianness of the element type of S, then validation will fail.

Examples

Read file with UTF-8 text.

write(deleteme, "abc"); // deleteme is the name of a temporary file
scope(exit) remove(deleteme);
string content = readText(deleteme);
assert(content == "abc");
@paramS the string type of the file@paramname string or range of characters representing the file name@returnsArray of characters read.@throwsFileException if there is an error reading the file, UTFException on UTF decoding error.@seeread for reading a binary file.
readText
(
(local variable) const(string) xmlFile
xmlFile
);
assert(
(local variable) const(string) xml
xml
.
bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safe

Convenience function. Like find, but only returns whether or not the search was successful.

For more information about pred see find.

Examples

const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));

// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);

assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);

Example using a custom predicate. Note that the needle appears as the second argument of the predicate.

auto words = [
    "apple",
    "beeswax",
    "cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));

Search for multiple items in an array of items (search for needles in an array of haystacks)

string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
("<protocoltool>memcheck</protocoltool>"), "protocol-4 tool tag");
assert(
(local variable) const(string) xml
xml
.
bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safe

Convenience function. Like find, but only returns whether or not the search was successful.

For more information about pred see find.

Examples

const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));

// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);

assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);

Example using a custom predicate. Note that the needle appears as the second argument of the predicate.

auto words = [
    "apple",
    "beeswax",
    "cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));

Search for multiple items in an array of items (search for needles in an array of haystacks)

string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
("<kind>InvalidRead</kind>"),
"expected <kind>InvalidRead</kind> in the XML error stream"); // Match the tail, not the whole tag: DWARF records the source path as // it was handed to the compiler, so `<file>` is the bare basename for // some invocations and the full relative path for others (adding any // `-I` is enough to flip it). The property under test is that the // faulting frame names *this file*, which both forms satisfy. assert(
(local variable) const(string) xml
xml
.
bool std.algorithm.searching.canFind!().canFind!(string, string)(string haystack, scope string needle) pure nothrow @nogc @safe

Convenience function. Like find, but only returns whether or not the search was successful.

For more information about pred see find.

Examples

const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));

// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);

assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);

Example using a custom predicate. Note that the needle appears as the second argument of the predicate.

auto words = [
    "apple",
    "beeswax",
    "cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));

Search for multiple items in an array of items (search for needles in an array of haystacks)

string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
@see

among for checking a value against multiple arguments.

Returns true if and only if needle can be found in range. Performs O(haystack.length) evaluations of pred.

canFind
("valgrind-memcheck-catch.d</file>"),
"expected the faulting frame to carry this file's name");
void std.stdio.writefln!(char, string)(in char[] fmt, string __param_1) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("XML report: <kind>InvalidRead</kind> at %s",
"<file>…valgrind-memcheck-catch.d</file>");
void std.stdio.writefln!char(in char[] fmt) @safe

Equivalent to writef(fmt, args, '\n').

writefln
("PASS: memcheck caught the use-after-free in an uninstrumented "
~ "binary; XML + --error-exitcode form a parseable per-run pipeline"); return 0; } } int
int D main()
main
()
{ version (
linux
linux
)
return
int sanitizers_valgrind_memcheck_catch.run()
run
();
else { import std.stdio : writefln; writefln("SKIP: valgrind probes are Linux-only here"); return 0; } }