La cubierta de MemCheck proporciona un ayudante de Bash para el análisis de Memcheck de Valgrind.
También proporciona un formato del generador de informes HTML Valgrind Raw informes y destacando partes importantes para ayudarlo a interpretar esos resultados.
Se puede usar fácilmente en su entorno CI para generar informes automáticamente.
Una demostración que es mejor que cualquier palabra, puede encontrar un ejemplo de informe HTML generado aquí.
El script memcheck_runner.sh es un envoltorio que ejecutará un binario bajo la herramienta MemCheck de Valgrind.
Para que funcione el script memcheck_runner.sh , las siguientes herramientas deben ser instaladas y accesibles utilizando la variable de entorno de ruta:
bash Bash Versión 4 y Superior solo son compatibles.valgrind Valgrind versión 3.13, la versión anterior podría no funcionar según lo previsto Aquí está su uso (se puede acceder utilizando la opción --help ):
Usage: memcheck_runner.sh [OPTIONS]... -- [BIN] [BIN_ARG]...
Runs the BIN with the BIN_ARGs through valgrind memcheck analyser.
Options:
-h|--help Displays this help message.
-i|--ignore=FILE Provides valgrind FILE as the suppression file.
-o|--output-name=NAME [MANDATORY] Defines the output file name
(will be suffixed with the .memcheck extension).
-s|--gen-suppressions Enables valgrind suppression generation in the output
file, those can be used to create a suppression file.
--fullpath-after= (with nothing after the '=')
Show full source paths in call stacks.
--fullpath-after=STR Like --fullpath-after=, but only show the part of the
path after 'STR'. Allows removal of path prefixes.
Use this flag multiple times to specify a set of
prefixes to remove.
La única opción obligatoria es el --output-name , que definirá la ruta y el nombre del archivo de salida.
Si la ruta no existe, se creará.
La extensión .memcheck se le agregará automáticamente para compatibilidad con el script generate_html_report.sh .
Ejemplo:
$ memcheck_runner.sh --output-name " my/output/path/filename " -- true can take useless params and still be one true self
Info: Output file set to: ' my/output/path/filename.memcheck '
Info: Creating output directory ' my/output/path/ '
Info: Running the following cmd with valgrind:
" true " " can " " take " " useless " " params " " and " " still " " be " " one " " true " " self " Puede especificar un archivo de supresión de violación utilizando la opción --ignore .
Dicho archivo de supresión debe seguir las reglas del archivo de supresión de Valgrind.
Las supresiones se pueden generar dentro del informe utilizando la opción --gen-suppressions .
La supresión se verá así en el informe:
[...]
==21849== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==21849== at 0x4C3017F: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==21849== by 0x108687: breakage::evil_definitely_lost_func() (main.cpp:4)
==21849== by 0x10869B: main (main.cpp:10)
==21849==
{
<insert_a_suppression_name_here>
Memcheck:Leak
match-leak-kinds: definite
fun:_Znwm
fun:_ZN8breakage25evil_definitely_lost_funcEv
fun:main
}
==21849== LEAK SUMMARY:
==21849== definitely lost: 4 bytes in 1 blocks
[...]
Esta llamada emitirá el informe de Valgind al archivo filename.memcheck dentro del directorio my/output/path/ , que en este ejemplo se creó.
El análisis de Valgrind se ejecutó utilizando el true binario, pasándolo muchos parámetros.
De la documentación de Valgrind:
By default Valgrind only shows the filenames in stack traces, but not full paths to source files.
When using Valgrind in large projects where the sources reside in multiple different directories, this can be inconvenient.
`--fullpath-after` provides a flexible solution to this problem.
When this option is present, the path to each source file is shown, with the following all-important caveat:
if string is found in the path, then the path up to and including string is omitted, else the path is shown unmodified.
Note that string is not required to be a prefix of the path.
For example, consider a file named /home/janedoe/blah/src/foo/bar/xyzzy.c. Specifying --fullpath-after=/home/janedoe/blah/src/ will cause Valgrind to show the name as foo/bar/xyzzy.c.
Because the string is not required to be a prefix, --fullpath-after=src/ will produce the same output. This is useful when the path contains arbitrary machine-generated characters.
For example, the path /my/build/dir/C32A1B47/blah/src/foo/xyzzy can be pruned to foo/xyzzy using --fullpath-after=/blah/src/.
If you simply want to see the full path, just specify an empty string: --fullpath-after=. This isn't a special case, merely a logical consequence of the above rules.
Finally, you can use --fullpath-after multiple times. Any appearance of it causes Valgrind to switch to producing full paths and applying the above filtering rule.
Each produced path is compared against all the --fullpath-after-specified strings, in the order specified. The first string to match causes the path to be truncated as described above.
If none match, the full path is shown.
This facilitates chopping off prefixes when the sources are drawn from a number of unrelated directories.
Pasar el --fullpath-after de memcheck_runner.sh lo reenviará directamente a Valgrind, con el efecto descrito anteriormente.
Por ahora, las opciones de Valgrind no son personalizables.
Se utilizan las siguientes opciones:
--track-origins=yes--leak-check=full--show-reachable=yes--show-leak-kinds=all--show-leak-kinds=all--show-leak-kinds=definite,indirect,possible,reachable--num-callers=50--fair-sched=yesPara obtener más detalles, consulte la documentación de Valgrind.
El script generate_html_report.sh generará un informe HTML con todos los archivos de resultados de MemCheck en un directorio determinado.
Para que funcione el script generate_html_report.sh , las siguientes herramientas deben ser instaladas y accesibles utilizando la variable de entorno de ruta:
bash Bash Versión 4 y Superior solo son compatibles.gawk GNU AWK 4.1.4 fue probado, la versión anterior podría no funcionar según lo previsto Aquí está su uso (se puede acceder utilizando la opción --help ):
Usage: generate_html_report.sh [OPTIONS]...
Parses all .memcheck files from a given directory and generates an HTML
report.
Options:
-h|--help Displays this help message.
-g|--generate-config Generates a 'memcheck-cover.config' file in the current
directory, containing the default configuration values.
-c|--config=FILE Loads the configuration from FILE. An example
configuration file can be generated using the
--generate-config option.
If this option is not set, or values are missing in
FILE, the default values will be used.
-i|--input-dir=DIR [MANDATORY] Defines the input directory where the
.memcheck files are.
The files will be searched in directories recursivly.
-o|--output-dir=DIR [MANDATORY] Defines the output directory where the
HTML report will be produced.
Hay dos parámetros obligatorios para el generador:
--input-dir que define la ruta donde se procesan los informes de MemCheck..memcheck que encuentre.--output-dir que define la ruta en la que se generará el informe HTML. Si la configuración de violación predeterminada no le queda bien, cada criticidad de violación se puede ajustar.
Se puede generar un archivo de configuración, con todas las configuraciones de criticidad disponibles y sus valores predeterminados, utilizando la opción --generate-config :
$ generate_html_report.sh --generate-config
Info: Generating configuration with default values: ' memcheck-cover.config ' ...
Done. The generated configuration can be modified and then loaded
by the current script using the --config option.
If a violation is not set, the default value will be used. El archivo de configuración predeterminado se genera en el directorio actual en el archivo memcheck-cover.config .
Luego puede cambiar cualquier crítica para satisfacer sus necesidades y pasarlo al generador utilizando la opción --config .
Si falta alguna crítica del archivo, se aplicará el predeterminado.
Pasar cualquier archivo de configuración con parámetros o valores de parámetros no válidos dará como resultado un error.
Por ejemplo:
Error: Invalid configuration value 'dummy' for parameter: memcheck_violation_criticality['contains_unaddressable'] => La criticidad dummy no existeError: Invalid configuration parameter: memcheck_violation_criticality['dummy_param'] => La tecla dummy_param no existe para memcheck_violation_criticalityAquí hay un ejemplo de generación, con el siguiente árbol:
my/output/path/
├── another_dir/
│ ├── a_report.memcheck
│ └── other_report.memcheck
└── filename.memcheck
Ejecutemos el generador HTML:
generate_html_report.sh --input-dir " my/output/path/ " --output-dir " my/output/path/report/ " --config memcheck-cover.config
Info: Input directory set to: ' my/output/path/ '
Info: Loading configuration from file ' memcheck-cover.config ' ...
Info: Processing memcheck file ' filename.memcheck ' ...
Info: Processing memcheck file ' another_dir/a_report.memcheck ' ...
Info: Processing memcheck file ' another_dir/other_report.memcheck ' ...
Info: Generating index.html...El resultado se verá así:
my/output/path/report/
├── another_dir/
│ ├── a_report.memcheck.html.part.js
│ └── other_report.memcheck.html.part.js
├── filename.memcheck.html.part.js
├── index.html
├── memcheck-cover.css
└── memcheck-cover.js
Esta opción solo está disponible a través del archivo de configuración (consulte -g |-opción Generate-Config ).
Se puede definir llenando la siguiente matriz asociativa:
memcheck_path_prefix_replacement[ " <prefix_to_replace> " ]= " <replacement_value> " Donde la clave prefix_to_replace es el prefijo de la ruta a reemplazarse
Y el valor replacement_value es el valor de reemplazo (se puede dejar vacío para eliminar completamente el prefijo)
Por ejemplo, configuración:
memcheck_path_prefix_replacement[ " /var/user/repo " ]= " <repo> "Convertiría la siguiente línea de informe:
==1== at 0x10101042: myFunc() (/var/user/repo/src/lib1/MyClass.cpp:14)
A:
==1== at 0x10101042: myFunc() (<repo>/src/lib1/MyClass.cpp:14)
Se pueden definir múltiples reemplazos
Esta opción solo está disponible a través del archivo de configuración (consulte -g |-opción Generate-Config ).
Se puede definir llenando las siguientes matrices asociativas (ambas son necesarias):
memcheck_url_prefix_replacement[ " <path_prefix> " ]= " <repository_url_prefix> "
memcheck_url_prefix_replacement_type[ " <path_prefix> " ]= " <repository_type> " Donde la clave path_prefix es el prefijo de ruta del archivo en el directorio raíz del repositorio.
El valor repository_url_prefix es el prefijo del servidor de control de origen al repositorio.
Aquí hay algún ejemplo:
Y el valor repository_type es uno de los tipos de servidor compatibles (el caso no importa):
Por ejemplo, configuración:
memcheck_url_prefix_replacement[ " /var/user/repo/ " ]= " https://github.com/example/example_project/blob/master/ "
memcheck_url_prefix_replacement_type[ " /var/user/repo/ " ]= " github "Convertiría la siguiente línea de informe:
==1== at 0x10101042: myFunc() (/var/user/repo/src/lib1/MyClass.cpp:14)
A:
==1== at 0x10101042: myFunc() (<a href="https://github.com/example/example_project/blob/master/src/lib1/MyClass.cpp#L14">/var/user/repo/src/lib1/MyClass.cpp:14</a>)
Se pueden definir múltiples reemplazos