A capa do Memcheck fornece um ajudante de bash para a análise Valgrind Memcheck.
Ele também fornece um gerador de relatório HTML, formatando relatórios RAW Valgrind e destacando peças importantes para ajudá -lo a interpretar esses resultados.
Pode ser facilmente usado em seu ambiente de IC para gerar automaticamente relatórios.
Sendo uma demonstração melhor do que qualquer palavra, você pode encontrar um exemplo de relatório HTML gerado aqui.
O script memcheck_runner.sh é um invólucro que executará um binário sob a ferramenta Memcheck da Valgrind.
Para que o script memcheck_runner.sh funcione, as seguintes ferramentas devem ser instaladas e acessíveis usando a variável de ambiente do caminho:
bash Bash versão 4 e somente superior são suportados.valgrind Valgrind versão 3.13 foi testado, a versão mais antiga pode não funcionar como pretendido Aqui está o seu uso (ele pode ser acessado usando a opção --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.
A única opção obrigatória é o --output-name , que definirá o caminho e o nome do arquivo de saída.
Se o caminho não existir, será criado.
A extensão .memcheck será automaticamente adicionada a ele para compatibilidade com o script generate_html_report.sh .
Exemplo:
$ 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 " Você pode especificar um arquivo de supressão de violação usando a opção --ignore .
Esse arquivo de supressão deve seguir as regras do arquivo de supressão de Valgrind.
As supressões podem ser geradas dentro do relatório usando a opção --gen-suppressions .
A supressão será assim no relatório:
[...]
==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 chamada produzirá o relatório do Valgind para o arquivo filename.memcheck no diretório my/output/path/ , que neste exemplo foi criado.
A análise Valgrind foi executada usando o true binário, passando por muitos parâmetros.
Da documentação 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.
Passar o --fullpath-after para memcheck_runner.sh o encaminhará diretamente para Valgrind, tendo o efeito descrito anteriormente.
Por enquanto, as opções de Valgrind não são personalizáveis.
As seguintes opções são usadas:
--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 mais detalhes, consulte a documentação do Valgrind.
O script generate_html_report.sh gerará um relatório HTML com todos os arquivos de resultado do MemCheck em um determinado diretório.
Para o script generate_html_report.sh para funcionar, as seguintes ferramentas devem ser instaladas e acessíveis usando a variável do ambiente do caminho:
bash Bash versão 4 e somente superior são suportados.gawk GNU AWK 4.1.4 foi testado, a versão mais antiga pode não funcionar como pretendido Aqui está o seu uso (ele pode ser acessado usando a opção --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.
Existem dois parâmetros obrigatórios para o gerador:
--input-dir que define o caminho em que os relatórios do Memcheck a serem processados são..memcheck que encontrar.--output-dir , que define o caminho no qual o relatório HTML será gerado. Se as configurações de violação padrão não se encaixarem em você, cada criticidade de violação poderá ser ajustada.
Um arquivo de configuração, com todas as configurações de criticidade disponível e seus valores padrão, pode ser gerado usando a opção --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. O arquivo de configuração padrão é gerado no diretório atual no arquivo memcheck-cover.config .
Você pode alterar qualquer criticidade para atender às suas necessidades e passá -la para o gerador usando a opção --config .
Se alguma criticidade estiver faltando no arquivo, o padrão será aplicado.
A passagem de qualquer arquivo de configuração com parâmetros inválidos ou valores de parâmetros resultará em um erro.
Por exemplo:
Error: Invalid configuration value 'dummy' for parameter: memcheck_violation_criticality['contains_unaddressable'] => A criticidade dummy não existeError: Invalid configuration parameter: memcheck_violation_criticality['dummy_param'] => a tecla dummy_param não existe para memcheck_violation_criticalityAqui está um exemplo de geração, com a seguinte árvore:
my/output/path/
├── another_dir/
│ ├── a_report.memcheck
│ └── other_report.memcheck
└── filename.memcheck
Vamos executar o gerador 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...O resultado será assim:
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 opção está disponível apenas no arquivo de configuração (consulte -g |--generate-config opção).
Pode ser definido preenchendo a seguinte matriz associativa:
memcheck_path_prefix_replacement[ " <prefix_to_replace> " ]= " <replacement_value> " Onde o prefixo prefix_to_replace é o prefixo do caminho a ser substituído
E o valor replacement_value é o valor de substituição (pode ser deixado vazio para remover o prefixo completa)
Por exemplo, configuração:
memcheck_path_prefix_replacement[ " /var/user/repo " ]= " <repo> "Converteria a seguinte linha de relatório:
==1== at 0x10101042: myFunc() (/var/user/repo/src/lib1/MyClass.cpp:14)
Para:
==1== at 0x10101042: myFunc() (<repo>/src/lib1/MyClass.cpp:14)
Vários substituições podem ser definidas
Esta opção está disponível apenas no arquivo de configuração (consulte -g |--generate-config opção).
Pode ser definido preenchendo as seguintes matrizes associativas (ambas são necessárias):
memcheck_url_prefix_replacement[ " <path_prefix> " ]= " <repository_url_prefix> "
memcheck_url_prefix_replacement_type[ " <path_prefix> " ]= " <repository_type> " Onde o key path_prefix é o prefixo do caminho do arquivo no diretório raiz do repositório.
O valor repository_url_prefix é o prefixo do servidor de controle de origem no repositório.
Aqui estão algum exemplo:
E o valor repository_type é um dos tipos de servidor suportados (o caso não importa):
Por exemplo, configuração:
memcheck_url_prefix_replacement[ " /var/user/repo/ " ]= " https://github.com/example/example_project/blob/master/ "
memcheck_url_prefix_replacement_type[ " /var/user/repo/ " ]= " github "Converteria a seguinte linha de relatório:
==1== at 0x10101042: myFunc() (/var/user/repo/src/lib1/MyClass.cpp:14)
Para:
==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>)
Vários substituições podem ser definidas