提交 a648e0c3 authored 作者: José Luis Millán's avatar José Luis Millán

Worker: code coverage

上级 7e75bd1b
.version
*.gcda
*.gcno
*.info
*.tar.gz
*.rpm
Contributing to LCOV
====================
Please read this document if you would like to help improving the LTP GCOV
extension (LCOV). In general, all types of contributions are welcome, for
example:
* Fixes for code or documentation
* Performance and compatibility improvements
* Functional enhancements
There are some rules that these contributions must follow to be acceptable for
inclusion:
1. The contribution must align with the project goals of LCOV.
2. The contribution must follow a particular format.
3. The contribution must be signed.
Once you have made sure that your contribution follows these rules, send it via
e-mail to the LTP coverage mailing list [1].
Signing your work
=================
All contributions to LCOV must be signed by putting the following line at the
end of the explanation of a patch:
Signed-off-by: Your Name <your.email@example.org>
By signing a patch, you certify the following:
By making a contribution to the LTP GCOV extension (LCOV) on
http://ltp.sourceforge.net, I certify that:
a) The contribution was created by me and I have the right to submit it
under the terms and conditions of the open source license
"GNU General Public License, version 2 or later".
(http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).
b) The contribution is made free of any other party's intellectual property
claims or rights.
c) I understand and agree that this project and the contribution are public
and that a record of the contribution (including all personal information
I submit with it, including my sign-off) is maintained indefinitely and
may be redistributed consistent with this project or the open source
license(s) involved.
Project goals
=============
The goal of LCOV is to provide a set of command line tools that can be used to
collect, process and visualize code coverage data as produced by the gcov tool
that is part of the GNU Compiler Collection (GCC) [2].
If you have an idea for a contribution but are unsure if it aligns with the
project goals, feel free to discuss the idea on the LTP coverage mailing
list [1].
Contribution format
===================
To contribute a change, please create a patch using the diff utility with the
following command line options:
diff -Naurp
Please base your changes on the most current version of LCOV. You can use the
following command line to obtain this version from the lcov Git repository:
git clone https://github.com/linux-test-project/lcov.git
Add a meaningful description of the contribution to the top of the patch. The
description should follow this format:
component: short description
detailed description
Signed-off-by: Your Name <your.email@example.org>
With your Signed-off-by, you certify the rules stated in section
"Signing your work".
--
[1] ltp-coverage@lists.sourceforge.net
[2] http://gcc.gnu.org
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
#
# Makefile for LCOV
#
# Make targets:
# - install: install LCOV tools and man pages on the system
# - uninstall: remove tools and man pages from the system
# - dist: create files required for distribution, i.e. the lcov.tar.gz
# and the lcov.rpm file. Just make sure to adjust the VERSION
# and RELEASE variables below - both version and date strings
# will be updated in all necessary files.
# - clean: remove all generated files
#
VERSION := $(shell bin/get_version.sh --version)
RELEASE := $(shell bin/get_version.sh --release)
FULL := $(shell bin/get_version.sh --full)
PREFIX := /usr/local
CFG_DIR := $(PREFIX)/etc
BIN_DIR := $(PREFIX)/bin
MAN_DIR := $(PREFIX)/share/man
TMP_DIR := $(shell mktemp -d)
FILES := $(wildcard bin/*) $(wildcard man/*) README Makefile \
$(wildcard rpm/*) lcovrc
.PHONY: all info clean install uninstall rpms test
all: info
info:
@echo "Available make targets:"
@echo " install : install binaries and man pages in DESTDIR (default /)"
@echo " uninstall : delete binaries and man pages from DESTDIR (default /)"
@echo " dist : create packages (RPM, tarball) ready for distribution"
@echo " test : perform self-tests"
clean:
rm -f lcov-*.tar.gz
rm -f lcov-*.rpm
make -C example clean
make -C test -s clean
install:
bin/install.sh bin/lcov $(DESTDIR)$(BIN_DIR)/lcov -m 755
bin/install.sh bin/genhtml $(DESTDIR)$(BIN_DIR)/genhtml -m 755
bin/install.sh bin/geninfo $(DESTDIR)$(BIN_DIR)/geninfo -m 755
bin/install.sh bin/genpng $(DESTDIR)$(BIN_DIR)/genpng -m 755
bin/install.sh bin/gendesc $(DESTDIR)$(BIN_DIR)/gendesc -m 755
bin/install.sh man/lcov.1 $(DESTDIR)$(MAN_DIR)/man1/lcov.1 -m 644
bin/install.sh man/genhtml.1 $(DESTDIR)$(MAN_DIR)/man1/genhtml.1 -m 644
bin/install.sh man/geninfo.1 $(DESTDIR)$(MAN_DIR)/man1/geninfo.1 -m 644
bin/install.sh man/genpng.1 $(DESTDIR)$(MAN_DIR)/man1/genpng.1 -m 644
bin/install.sh man/gendesc.1 $(DESTDIR)$(MAN_DIR)/man1/gendesc.1 -m 644
bin/install.sh man/lcovrc.5 $(DESTDIR)$(MAN_DIR)/man5/lcovrc.5 -m 644
bin/install.sh lcovrc $(DESTDIR)$(CFG_DIR)/lcovrc -m 644
bin/updateversion.pl $(DESTDIR)$(BIN_DIR)/lcov $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(BIN_DIR)/genhtml $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(BIN_DIR)/geninfo $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(BIN_DIR)/genpng $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(BIN_DIR)/gendesc $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(MAN_DIR)/man1/lcov.1 $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(MAN_DIR)/man1/genhtml.1 $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(MAN_DIR)/man1/geninfo.1 $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(MAN_DIR)/man1/genpng.1 $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(MAN_DIR)/man1/gendesc.1 $(VERSION) $(RELEASE) $(FULL)
bin/updateversion.pl $(DESTDIR)$(MAN_DIR)/man5/lcovrc.5 $(VERSION) $(RELEASE) $(FULL)
uninstall:
bin/install.sh --uninstall bin/lcov $(DESTDIR)$(BIN_DIR)/lcov
bin/install.sh --uninstall bin/genhtml $(DESTDIR)$(BIN_DIR)/genhtml
bin/install.sh --uninstall bin/geninfo $(DESTDIR)$(BIN_DIR)/geninfo
bin/install.sh --uninstall bin/genpng $(DESTDIR)$(BIN_DIR)/genpng
bin/install.sh --uninstall bin/gendesc $(DESTDIR)$(BIN_DIR)/gendesc
bin/install.sh --uninstall man/lcov.1 $(DESTDIR)$(MAN_DIR)/man1/lcov.1
bin/install.sh --uninstall man/genhtml.1 $(DESTDIR)$(MAN_DIR)/man1/genhtml.1
bin/install.sh --uninstall man/geninfo.1 $(DESTDIR)$(MAN_DIR)/man1/geninfo.1
bin/install.sh --uninstall man/genpng.1 $(DESTDIR)$(MAN_DIR)/man1/genpng.1
bin/install.sh --uninstall man/gendesc.1 $(DESTDIR)$(MAN_DIR)/man1/gendesc.1
bin/install.sh --uninstall man/lcovrc.5 $(DESTDIR)$(MAN_DIR)/man5/lcovrc.5
bin/install.sh --uninstall lcovrc $(DESTDIR)$(CFG_DIR)/lcovrc
dist: lcov-$(VERSION).tar.gz lcov-$(VERSION)-$(RELEASE).noarch.rpm \
lcov-$(VERSION)-$(RELEASE).src.rpm
lcov-$(VERSION).tar.gz: $(FILES)
mkdir $(TMP_DIR)/lcov-$(VERSION)
cp -r * $(TMP_DIR)/lcov-$(VERSION)
bin/copy_dates.sh . $(TMP_DIR)/lcov-$(VERSION)
make -C $(TMP_DIR)/lcov-$(VERSION) clean
bin/updateversion.pl $(TMP_DIR)/lcov-$(VERSION) $(VERSION) $(RELEASE) $(FULL)
bin/get_changes.sh > $(TMP_DIR)/lcov-$(VERSION)/CHANGES
cd $(TMP_DIR) ; \
tar cfz $(TMP_DIR)/lcov-$(VERSION).tar.gz lcov-$(VERSION)
mv $(TMP_DIR)/lcov-$(VERSION).tar.gz .
rm -rf $(TMP_DIR)
lcov-$(VERSION)-$(RELEASE).noarch.rpm: rpms
lcov-$(VERSION)-$(RELEASE).src.rpm: rpms
rpms: lcov-$(VERSION).tar.gz
mkdir $(TMP_DIR)
mkdir $(TMP_DIR)/BUILD
mkdir $(TMP_DIR)/RPMS
mkdir $(TMP_DIR)/SOURCES
mkdir $(TMP_DIR)/SRPMS
cp lcov-$(VERSION).tar.gz $(TMP_DIR)/SOURCES
cd $(TMP_DIR)/BUILD ; \
tar xfz $(TMP_DIR)/SOURCES/lcov-$(VERSION).tar.gz \
lcov-$(VERSION)/rpm/lcov.spec
rpmbuild --define '_topdir $(TMP_DIR)' \
-ba $(TMP_DIR)/BUILD/lcov-$(VERSION)/rpm/lcov.spec
mv $(TMP_DIR)/RPMS/noarch/lcov-$(VERSION)-$(RELEASE).noarch.rpm .
mv $(TMP_DIR)/SRPMS/lcov-$(VERSION)-$(RELEASE).src.rpm .
rm -rf $(TMP_DIR)
test:
@make -C test -s all
-------------------------------------------------
- README file for the LTP GCOV extension (LCOV) -
- Last changes: 2015-10-05 -
-------------------------------------------------
Description
-----------
LCOV is an extension of GCOV, a GNU tool which provides information about
what parts of a program are actually executed (i.e. "covered") while running
a particular test case. The extension consists of a set of Perl scripts
which build on the textual GCOV output to implement the following enhanced
functionality:
* HTML based output: coverage rates are additionally indicated using bar
graphs and specific colors.
* Support for large projects: overview pages allow quick browsing of
coverage data by providing three levels of detail: directory view,
file view and source code view.
LCOV was initially designed to support Linux kernel coverage measurements,
but works as well for coverage measurements on standard user space
applications.
Further README contents
-----------------------
1. Included files
2. Installing LCOV
3. An example of how to access kernel coverage data
4. An example of how to access coverage data for a user space program
5. Questions and Comments
1. Important files
------------------
README - This README file
CHANGES - List of changes between releases
bin/lcov - Tool for capturing LCOV coverage data
bin/genhtml - Tool for creating HTML output from LCOV data
bin/gendesc - Tool for creating description files as used by genhtml
bin/geninfo - Internal tool (creates LCOV data files)
bin/genpng - Internal tool (creates png overviews of source files)
bin/install.sh - Internal tool (takes care of un-/installing)
man - Directory containing man pages for included tools
example - Directory containing an example to demonstrate LCOV
lcovrc - LCOV configuration file
Makefile - Makefile providing 'install' and 'uninstall' targets
2. Installing LCOV
------------------
The LCOV package is available as either RPM or tarball from:
http://ltp.sourceforge.net/coverage/lcov.php
To install the tarball, unpack it to a directory and run:
make install
Use Git for the most recent (but possibly unstable) version:
git clone https://github.com/linux-test-project/lcov.git
Change to the resulting lcov directory and type:
make install
3. An example of how to access kernel coverage data
---------------------------------------------------
Requirements: get and install the gcov-kernel package from
http://sourceforge.net/projects/ltp
Copy the resulting gcov kernel module file to either the system wide modules
directory or the same directory as the Perl scripts. As root, do the following:
a) Resetting counters
lcov --zerocounters
b) Capturing the current coverage state to a file
lcov --capture --output-file kernel.info
c) Getting HTML output
genhtml kernel.info
Point the web browser of your choice to the resulting index.html file.
4. An example of how to access coverage data for a user space program
---------------------------------------------------------------------
Requirements: compile the program in question using GCC with the options
-fprofile-arcs and -ftest-coverage. During linking, make sure to specify
-lgcov or -coverage.
Assuming the compile directory is called "appdir", do the following:
a) Resetting counters
lcov --directory appdir --zerocounters
b) Capturing the current coverage state to a file
lcov --directory appdir --capture --output-file app.info
Note that this step only works after the application has
been started and stopped at least once. Otherwise lcov will
abort with an error mentioning that there are no data/.gcda files.
c) Getting HTML output
genhtml app.info
Point the web browser of your choice to the resulting index.html file.
Please note that independently of where the application is installed or
from which directory it is run, the --directory statement needs to
point to the directory in which the application was compiled.
For further information on the gcc profiling mechanism, please also
consult the gcov man page.
5. Questions and comments
-------------------------
See the included man pages for more information on how to use the LCOV tools.
Please email further questions or comments regarding this tool to the
LTP Mailing list at ltp-coverage@lists.sourceforge.net
#!/bin/bash
#
# Usage: copy_dates.sh SOURCE TARGET
#
# For each file found in SOURCE, set the modification time of the copy of that
# file in TARGET to either the time of the latest Git commit (if SOURCE contains
# a Git repository and the file was not modified after the last commit), or the
# modification time of the original file.
SOURCE="$1"
TARGET="$2"
if [ -z "$SOURCE" -o -z "$TARGET" ] ; then
echo "Usage: $0 SOURCE TARGET" >&2
exit 1
fi
[ -d "$SOURCE/.git" ] ; NOGIT=$?
echo "Copying modification/commit times from $SOURCE to $TARGET"
cd "$SOURCE" || exit 1
find * -type f | while read FILENAME ; do
[ ! -e "$TARGET/$FILENAME" ] && continue
# Copy modification time
touch -m "$TARGET/$FILENAME" -r "$FILENAME"
[ $NOGIT -eq 1 ] && continue # No Git
git diff --quiet -- "$FILENAME" || continue # Modified
git diff --quiet --cached -- "$FILENAME" || continue # Modified
# Apply modification time from Git commit time
TIME=$(git log --pretty=format:%cd -n 1 --date=iso -- "$FILENAME")
[ -n "$TIME" ] && touch -m "$TARGET/$FILENAME" --date "$TIME"
done
#!/usr/bin/perl -w
#
# Copyright (c) International Business Machines Corp., 2002
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# gendesc
#
# This script creates a description file as understood by genhtml.
# Input file format:
#
# For each test case:
# <test name><optional whitespace>
# <at least one whitespace character (blank/tab)><test description>
#
# Actual description may consist of several lines. By default, output is
# written to stdout. Test names consist of alphanumeric characters
# including _ and -.
#
#
# History:
# 2002-09-02: created by Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
#
use strict;
use File::Basename;
use Getopt::Long;
use Cwd qw/abs_path/;
# Constants
our $tool_dir = abs_path(dirname($0));
our $lcov_version = 'LCOV version '.`$tool_dir/get_version.sh --full`;
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $tool_name = basename($0);
# Prototypes
sub print_usage(*);
sub gen_desc();
sub warn_handler($);
sub die_handler($);
# Global variables
our $help;
our $version;
our $output_filename;
our $input_filename;
#
# Code entry point
#
$SIG{__WARN__} = \&warn_handler;
$SIG{__DIE__} = \&die_handler;
# Parse command line options
if (!GetOptions("output-filename=s" => \$output_filename,
"version" =>\$version,
"help|?" => \$help
))
{
print(STDERR "Use $tool_name --help to get usage information\n");
exit(1);
}
$input_filename = $ARGV[0];
# Check for help option
if ($help)
{
print_usage(*STDOUT);
exit(0);
}
# Check for version option
if ($version)
{
print("$tool_name: $lcov_version\n");
exit(0);
}
# Check for input filename
if (!$input_filename)
{
die("No input filename specified\n".
"Use $tool_name --help to get usage information\n");
}
# Do something
gen_desc();
#
# print_usage(handle)
#
# Write out command line usage information to given filehandle.
#
sub print_usage(*)
{
local *HANDLE = $_[0];
print(HANDLE <<END_OF_USAGE)
Usage: $tool_name [OPTIONS] INPUTFILE
Convert a test case description file into a format as understood by genhtml.
-h, --help Print this help, then exit
-v, --version Print version number, then exit
-o, --output-filename FILENAME Write description to FILENAME
For more information see: $lcov_url
END_OF_USAGE
;
}
#
# gen_desc()
#
# Read text file INPUT_FILENAME and convert the contained description to a
# format as understood by genhtml, i.e.
#
# TN:<test name>
# TD:<test description>
#
# If defined, write output to OUTPUT_FILENAME, otherwise to stdout.
#
# Die on error.
#
sub gen_desc()
{
local *INPUT_HANDLE;
local *OUTPUT_HANDLE;
my $empty_line = "ignore";
open(INPUT_HANDLE, "<", $input_filename)
or die("ERROR: cannot open $input_filename!\n");
# Open output file for writing
if ($output_filename)
{
open(OUTPUT_HANDLE, ">", $output_filename)
or die("ERROR: cannot create $output_filename!\n");
}
else
{
*OUTPUT_HANDLE = *STDOUT;
}
# Process all lines in input file
while (<INPUT_HANDLE>)
{
chomp($_);
if (/^(\w[\w-]*)(\s*)$/)
{
# Matched test name
# Name starts with alphanum or _, continues with
# alphanum, _ or -
print(OUTPUT_HANDLE "TN: $1\n");
$empty_line = "ignore";
}
elsif (/^(\s+)(\S.*?)\s*$/)
{
# Matched test description
if ($empty_line eq "insert")
{
# Write preserved empty line
print(OUTPUT_HANDLE "TD: \n");
}
print(OUTPUT_HANDLE "TD: $2\n");
$empty_line = "observe";
}
elsif (/^\s*$/)
{
# Matched empty line to preserve paragraph separation
# inside description text
if ($empty_line eq "observe")
{
$empty_line = "insert";
}
}
}
# Close output file if defined
if ($output_filename)
{
close(OUTPUT_HANDLE);
}
close(INPUT_HANDLE);
}
sub warn_handler($)
{
my ($msg) = @_;
warn("$tool_name: $msg");
}
sub die_handler($)
{
my ($msg) = @_;
die("$tool_name: $msg");
}
This source diff could not be displayed because it is too large. You can view the blob instead.
#!/usr/bin/perl -w
#
# Copyright (c) International Business Machines Corp., 2002,2012
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# geninfo
#
# This script generates .info files from data files as created by code
# instrumented with gcc's built-in profiling mechanism. Call it with
# --help and refer to the geninfo man page to get information on usage
# and available options.
#
#
# Authors:
# 2002-08-23 created by Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
# IBM Lab Boeblingen
# based on code by Manoj Iyer <manjo@mail.utexas.edu> and
# Megan Bock <mbock@us.ibm.com>
# IBM Austin
# 2002-09-05 / Peter Oberparleiter: implemented option that allows file list
# 2003-04-16 / Peter Oberparleiter: modified read_gcov so that it can also
# parse the new gcov format which is to be introduced in gcc 3.3
# 2003-04-30 / Peter Oberparleiter: made info write to STDERR, not STDOUT
# 2003-07-03 / Peter Oberparleiter: added line checksum support, added
# --no-checksum
# 2003-09-18 / Nigel Hinds: capture branch coverage data from GCOV
# 2003-12-11 / Laurent Deniel: added --follow option
# workaround gcov (<= 3.2.x) bug with empty .da files
# 2004-01-03 / Laurent Deniel: Ignore empty .bb files
# 2004-02-16 / Andreas Krebbel: Added support for .gcno/.gcda files and
# gcov versioning
# 2004-08-09 / Peter Oberparleiter: added configuration file support
# 2008-07-14 / Tom Zoerner: added --function-coverage command line option
# 2008-08-13 / Peter Oberparleiter: modified function coverage
# implementation (now enabled per default)
#
use strict;
use File::Basename;
use File::Spec::Functions qw /abs2rel catdir file_name_is_absolute splitdir
splitpath catpath/;
use Getopt::Long;
use Digest::MD5 qw(md5_base64);
use Cwd qw/abs_path/;
if( $^O eq "msys" )
{
require File::Spec::Win32;
}
# Constants
our $tool_dir = abs_path(dirname($0));
our $lcov_version = 'LCOV version '.`$tool_dir/get_version.sh --full`;
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $gcov_tool = "gcov";
our $tool_name = basename($0);
our $GCOV_VERSION_4_7_0 = 0x40700;
our $GCOV_VERSION_3_4_0 = 0x30400;
our $GCOV_VERSION_3_3_0 = 0x30300;
our $GCNO_FUNCTION_TAG = 0x01000000;
our $GCNO_LINES_TAG = 0x01450000;
our $GCNO_FILE_MAGIC = 0x67636e6f;
our $BBG_FILE_MAGIC = 0x67626267;
# Error classes which users may specify to ignore during processing
our $ERROR_GCOV = 0;
our $ERROR_SOURCE = 1;
our $ERROR_GRAPH = 2;
our %ERROR_ID = (
"gcov" => $ERROR_GCOV,
"source" => $ERROR_SOURCE,
"graph" => $ERROR_GRAPH,
);
our $EXCL_START = "LCOV_EXCL_START";
our $EXCL_STOP = "LCOV_EXCL_STOP";
# Marker to exclude branch coverage but keep function and line coveage
our $EXCL_BR_START = "LCOV_EXCL_BR_START";
our $EXCL_BR_STOP = "LCOV_EXCL_BR_STOP";
# Compatibility mode values
our $COMPAT_VALUE_OFF = 0;
our $COMPAT_VALUE_ON = 1;
our $COMPAT_VALUE_AUTO = 2;
# Compatibility mode value names
our %COMPAT_NAME_TO_VALUE = (
"off" => $COMPAT_VALUE_OFF,
"on" => $COMPAT_VALUE_ON,
"auto" => $COMPAT_VALUE_AUTO,
);
# Compatiblity modes
our $COMPAT_MODE_LIBTOOL = 1 << 0;
our $COMPAT_MODE_HAMMER = 1 << 1;
our $COMPAT_MODE_SPLIT_CRC = 1 << 2;
# Compatibility mode names
our %COMPAT_NAME_TO_MODE = (
"libtool" => $COMPAT_MODE_LIBTOOL,
"hammer" => $COMPAT_MODE_HAMMER,
"split_crc" => $COMPAT_MODE_SPLIT_CRC,
"android_4_4_0" => $COMPAT_MODE_SPLIT_CRC,
);
# Map modes to names
our %COMPAT_MODE_TO_NAME = (
$COMPAT_MODE_LIBTOOL => "libtool",
$COMPAT_MODE_HAMMER => "hammer",
$COMPAT_MODE_SPLIT_CRC => "split_crc",
);
# Compatibility mode default values
our %COMPAT_MODE_DEFAULTS = (
$COMPAT_MODE_LIBTOOL => $COMPAT_VALUE_ON,
$COMPAT_MODE_HAMMER => $COMPAT_VALUE_AUTO,
$COMPAT_MODE_SPLIT_CRC => $COMPAT_VALUE_AUTO,
);
# Compatibility mode auto-detection routines
sub compat_hammer_autodetect();
our %COMPAT_MODE_AUTO = (
$COMPAT_MODE_HAMMER => \&compat_hammer_autodetect,
$COMPAT_MODE_SPLIT_CRC => 1, # will be done later
);
our $BR_LINE = 0;
our $BR_BLOCK = 1;
our $BR_BRANCH = 2;
our $BR_TAKEN = 3;
our $BR_VEC_ENTRIES = 4;
our $BR_VEC_WIDTH = 32;
our $BR_VEC_MAX = vec(pack('b*', 1 x $BR_VEC_WIDTH), 0, $BR_VEC_WIDTH);
our $UNNAMED_BLOCK = -1;
# Prototypes
sub print_usage(*);
sub transform_pattern($);
sub gen_info($);
sub process_dafile($$);
sub match_filename($@);
sub solve_ambiguous_match($$$);
sub split_filename($);
sub solve_relative_path($$);
sub read_gcov_header($);
sub read_gcov_file($);
sub info(@);
sub map_llvm_version($);
sub version_to_str($);
sub get_gcov_version();
sub system_no_output($@);
sub read_config($);
sub apply_config($);
sub get_exclusion_data($);
sub apply_exclusion_data($$);
sub process_graphfile($$);
sub filter_fn_name($);
sub warn_handler($);
sub die_handler($);
sub graph_error($$);
sub graph_expect($);
sub graph_read(*$;$$);
sub graph_skip(*$;$);
sub uniq(@);
sub sort_uniq(@);
sub sort_uniq_lex(@);
sub graph_cleanup($);
sub graph_find_base($);
sub graph_from_bb($$$);
sub graph_add_order($$$);
sub read_bb_word(*;$);
sub read_bb_value(*;$);
sub read_bb_string(*$);
sub read_bb($);
sub read_bbg_word(*;$);
sub read_bbg_value(*;$);
sub read_bbg_string(*);
sub read_bbg_lines_record(*$$$$$);
sub read_bbg($);
sub read_gcno_word(*;$$);
sub read_gcno_value(*$;$$);
sub read_gcno_string(*$);
sub read_gcno_lines_record(*$$$$$$);
sub determine_gcno_split_crc($$$$);
sub read_gcno_function_record(*$$$$$);
sub read_gcno($);
sub get_gcov_capabilities();
sub get_overall_line($$$$);
sub print_overall_rate($$$$$$$$$);
sub br_gvec_len($);
sub br_gvec_get($$);
sub debug($);
sub int_handler();
sub parse_ignore_errors(@);
sub is_external($);
sub compat_name($);
sub parse_compat_modes($);
sub is_compat($);
sub is_compat_auto($);
# Global variables
our $gcov_version;
our $gcov_version_string;
our $graph_file_extension;
our $data_file_extension;
our @data_directory;
our $test_name = "";
our $quiet;
our $help;
our $output_filename;
our $base_directory;
our $version;
our $follow;
our $checksum;
our $no_checksum;
our $opt_compat_libtool;
our $opt_no_compat_libtool;
our $rc_adjust_src_path;# Regexp specifying parts to remove from source path
our $adjust_src_pattern;
our $adjust_src_replace;
our $adjust_testname;
our $config; # Configuration file contents
our @ignore_errors; # List of errors to ignore (parameter)
our @ignore; # List of errors to ignore (array)
our $initial;
our @include_patterns; # List of source file patterns to include
our @exclude_patterns; # List of source file patterns to exclude
our %excluded_files; # Files excluded due to include/exclude options
our $no_recursion = 0;
our $maxdepth;
our $no_markers = 0;
our $opt_derive_func_data = 0;
our $opt_external = 1;
our $opt_no_external;
our $debug = 0;
our $gcov_caps;
our @gcov_options;
our @internal_dirs;
our $opt_config_file;
our $opt_gcov_all_blocks = 1;
our $opt_compat;
our %opt_rc;
our %compat_value;
our $gcno_split_crc;
our $func_coverage = 1;
our $br_coverage = 0;
our $rc_auto_base = 1;
our $excl_line = "LCOV_EXCL_LINE";
our $excl_br_line = "LCOV_EXCL_BR_LINE";
our $cwd = `pwd`;
chomp($cwd);
#
# Code entry point
#
# Register handler routine to be called when interrupted
$SIG{"INT"} = \&int_handler;
$SIG{__WARN__} = \&warn_handler;
$SIG{__DIE__} = \&die_handler;
# Set LC_ALL so that gcov output will be in a unified format
$ENV{"LC_ALL"} = "C";
# Check command line for a configuration file name
Getopt::Long::Configure("pass_through", "no_auto_abbrev");
GetOptions("config-file=s" => \$opt_config_file,
"rc=s%" => \%opt_rc);
Getopt::Long::Configure("default");
{
# Remove spaces around rc options
my %new_opt_rc;
while (my ($key, $value) = each(%opt_rc)) {
$key =~ s/^\s+|\s+$//g;
$value =~ s/^\s+|\s+$//g;
$new_opt_rc{$key} = $value;
}
%opt_rc = %new_opt_rc;
}
# Read configuration file if available
if (defined($opt_config_file)) {
$config = read_config($opt_config_file);
} elsif (defined($ENV{"HOME"}) && (-r $ENV{"HOME"}."/.lcovrc"))
{
$config = read_config($ENV{"HOME"}."/.lcovrc");
}
elsif (-r "/etc/lcovrc")
{
$config = read_config("/etc/lcovrc");
} elsif (-r "/usr/local/etc/lcovrc")
{
$config = read_config("/usr/local/etc/lcovrc");
}
if ($config || %opt_rc)
{
# Copy configuration file and --rc values to variables
apply_config({
"geninfo_gcov_tool" => \$gcov_tool,
"geninfo_adjust_testname" => \$adjust_testname,
"geninfo_checksum" => \$checksum,
"geninfo_no_checksum" => \$no_checksum, # deprecated
"geninfo_compat_libtool" => \$opt_compat_libtool,
"geninfo_external" => \$opt_external,
"geninfo_gcov_all_blocks" => \$opt_gcov_all_blocks,
"geninfo_compat" => \$opt_compat,
"geninfo_adjust_src_path" => \$rc_adjust_src_path,
"geninfo_auto_base" => \$rc_auto_base,
"lcov_function_coverage" => \$func_coverage,
"lcov_branch_coverage" => \$br_coverage,
"lcov_excl_line" => \$excl_line,
"lcov_excl_br_line" => \$excl_br_line,
});
# Merge options
if (defined($no_checksum))
{
$checksum = ($no_checksum ? 0 : 1);
$no_checksum = undef;
}
# Check regexp
if (defined($rc_adjust_src_path)) {
my ($pattern, $replace) = split(/\s*=>\s*/,
$rc_adjust_src_path);
local $SIG{__DIE__};
eval '$adjust_src_pattern = qr>'.$pattern.'>;';
if (!defined($adjust_src_pattern)) {
my $msg = $@;
chomp($msg);
$msg =~ s/at \(eval.*$//;
warn("WARNING: invalid pattern in ".
"geninfo_adjust_src_path: $msg\n");
} elsif (!defined($replace)) {
# If no replacement is specified, simply remove pattern
$adjust_src_replace = "";
} else {
$adjust_src_replace = $replace;
}
}
for my $regexp (($excl_line, $excl_br_line)) {
eval 'qr/'.$regexp.'/';
my $error = $@;
chomp($error);
$error =~ s/at \(eval.*$//;
die("ERROR: invalid exclude pattern: $error") if $error;
}
}
# Parse command line options
if (!GetOptions("test-name|t=s" => \$test_name,
"output-filename|o=s" => \$output_filename,
"checksum" => \$checksum,
"no-checksum" => \$no_checksum,
"base-directory|b=s" => \$base_directory,
"version|v" =>\$version,
"quiet|q" => \$quiet,
"help|h|?" => \$help,
"follow|f" => \$follow,
"compat-libtool" => \$opt_compat_libtool,
"no-compat-libtool" => \$opt_no_compat_libtool,
"gcov-tool=s" => \$gcov_tool,
"ignore-errors=s" => \@ignore_errors,
"initial|i" => \$initial,
"include=s" => \@include_patterns,
"exclude=s" => \@exclude_patterns,
"no-recursion" => \$no_recursion,
"no-markers" => \$no_markers,
"derive-func-data" => \$opt_derive_func_data,
"debug" => \$debug,
"external|e" => \$opt_external,
"no-external" => \$opt_no_external,
"compat=s" => \$opt_compat,
"config-file=s" => \$opt_config_file,
"rc=s%" => \%opt_rc,
))
{
print(STDERR "Use $tool_name --help to get usage information\n");
exit(1);
}
else
{
# Merge options
if (defined($no_checksum))
{
$checksum = ($no_checksum ? 0 : 1);
$no_checksum = undef;
}
if (defined($opt_no_compat_libtool))
{
$opt_compat_libtool = ($opt_no_compat_libtool ? 0 : 1);
$opt_no_compat_libtool = undef;
}
if (defined($opt_no_external)) {
$opt_external = 0;
$opt_no_external = undef;
}
if(@include_patterns) {
# Need perlreg expressions instead of shell pattern
@include_patterns = map({ transform_pattern($_); } @include_patterns);
}
if(@exclude_patterns) {
# Need perlreg expressions instead of shell pattern
@exclude_patterns = map({ transform_pattern($_); } @exclude_patterns);
}
}
@data_directory = @ARGV;
debug("$lcov_version\n");
# Check for help option
if ($help)
{
print_usage(*STDOUT);
exit(0);
}
# Check for version option
if ($version)
{
print("$tool_name: $lcov_version\n");
exit(0);
}
# Check gcov tool
if (system_no_output(3, $gcov_tool, "--help") == -1)
{
die("ERROR: need tool $gcov_tool!\n");
}
($gcov_version, $gcov_version_string) = get_gcov_version();
# Determine gcov options
$gcov_caps = get_gcov_capabilities();
push(@gcov_options, "-b") if ($gcov_caps->{'branch-probabilities'} &&
($br_coverage || $func_coverage));
push(@gcov_options, "-c") if ($gcov_caps->{'branch-counts'} &&
$br_coverage);
push(@gcov_options, "-a") if ($gcov_caps->{'all-blocks'} &&
$opt_gcov_all_blocks && $br_coverage);
push(@gcov_options, "-p") if ($gcov_caps->{'preserve-paths'});
# Determine compatibility modes
parse_compat_modes($opt_compat);
# Determine which errors the user wants us to ignore
parse_ignore_errors(@ignore_errors);
# Make sure test names only contain valid characters
if ($test_name =~ s/\W/_/g)
{
warn("WARNING: invalid characters removed from testname!\n");
}
# Adjust test name to include uname output if requested
if ($adjust_testname)
{
$test_name .= "__".`uname -a`;
$test_name =~ s/\W/_/g;
}
# Make sure base_directory contains an absolute path specification
if ($base_directory)
{
$base_directory = solve_relative_path($cwd, $base_directory);
}
# Check for follow option
if ($follow)
{
$follow = "-follow"
}
else
{
$follow = "";
}
# Determine checksum mode
if (defined($checksum))
{
# Normalize to boolean
$checksum = ($checksum ? 1 : 0);
}
else
{
# Default is off
$checksum = 0;
}
# Determine max depth for recursion
if ($no_recursion)
{
$maxdepth = "-maxdepth 1";
}
else
{
$maxdepth = "";
}
# Check for directory name
if (!@data_directory)
{
die("No directory specified\n".
"Use $tool_name --help to get usage information\n");
}
else
{
foreach (@data_directory)
{
stat($_);
if (!-r _)
{
die("ERROR: cannot read $_!\n");
}
}
}
if ($gcov_version < $GCOV_VERSION_3_4_0)
{
if (is_compat($COMPAT_MODE_HAMMER))
{
$data_file_extension = ".da";
$graph_file_extension = ".bbg";
}
else
{
$data_file_extension = ".da";
$graph_file_extension = ".bb";
}
}
else
{
$data_file_extension = ".gcda";
$graph_file_extension = ".gcno";
}
# Check output filename
if (defined($output_filename) && ($output_filename ne "-"))
{
# Initially create output filename, data is appended
# for each data file processed
local *DUMMY_HANDLE;
open(DUMMY_HANDLE, ">", $output_filename)
or die("ERROR: cannot create $output_filename!\n");
close(DUMMY_HANDLE);
# Make $output_filename an absolute path because we're going
# to change directories while processing files
if (!($output_filename =~ /^\/(.*)$/))
{
$output_filename = $cwd."/".$output_filename;
}
}
# Build list of directories to identify external files
foreach my $entry(@data_directory, $base_directory) {
next if (!defined($entry));
push(@internal_dirs, solve_relative_path($cwd, $entry));
}
# Do something
foreach my $entry (@data_directory) {
gen_info($entry);
}
if ($initial && $br_coverage) {
warn("Note: --initial does not generate branch coverage ".
"data\n");
}
info("Finished .info-file creation\n");
exit(0);
#
# print_usage(handle)
#
# Print usage information.
#
sub print_usage(*)
{
local *HANDLE = $_[0];
print(HANDLE <<END_OF_USAGE);
Usage: $tool_name [OPTIONS] DIRECTORY
Traverse DIRECTORY and create a .info file for each data file found. Note
that you may specify more than one directory, all of which are then processed
sequentially.
-h, --help Print this help, then exit
-v, --version Print version number, then exit
-q, --quiet Do not print progress messages
-i, --initial Capture initial zero coverage data
-t, --test-name NAME Use test case name NAME for resulting data
-o, --output-filename OUTFILE Write data only to OUTFILE
-f, --follow Follow links when searching .da/.gcda files
-b, --base-directory DIR Use DIR as base directory for relative paths
--(no-)checksum Enable (disable) line checksumming
--(no-)compat-libtool Enable (disable) libtool compatibility mode
--gcov-tool TOOL Specify gcov tool location
--ignore-errors ERROR Continue after ERROR (gcov, source, graph)
--no-recursion Exclude subdirectories from processing
--no-markers Ignore exclusion markers in source code
--derive-func-data Generate function data from line data
--(no-)external Include (ignore) data for external files
--config-file FILENAME Specify configuration file location
--rc SETTING=VALUE Override configuration file setting
--compat MODE=on|off|auto Set compat MODE (libtool, hammer, split_crc)
--include PATTERN Include files matching PATTERN
--exclude PATTERN Exclude files matching PATTERN
For more information see: $lcov_url
END_OF_USAGE
;
}
#
# transform_pattern(pattern)
#
# Transform shell wildcard expression to equivalent Perl regular expression.
# Return transformed pattern.
#
sub transform_pattern($)
{
my $pattern = $_[0];
# Escape special chars
$pattern =~ s/\\/\\\\/g;
$pattern =~ s/\//\\\//g;
$pattern =~ s/\^/\\\^/g;
$pattern =~ s/\$/\\\$/g;
$pattern =~ s/\(/\\\(/g;
$pattern =~ s/\)/\\\)/g;
$pattern =~ s/\[/\\\[/g;
$pattern =~ s/\]/\\\]/g;
$pattern =~ s/\{/\\\{/g;
$pattern =~ s/\}/\\\}/g;
$pattern =~ s/\./\\\./g;
$pattern =~ s/\,/\\\,/g;
$pattern =~ s/\|/\\\|/g;
$pattern =~ s/\+/\\\+/g;
$pattern =~ s/\!/\\\!/g;
# Transform ? => (.) and * => (.*)
$pattern =~ s/\*/\(\.\*\)/g;
$pattern =~ s/\?/\(\.\)/g;
return $pattern;
}
#
# get_common_prefix(min_dir, filenames)
#
# Return the longest path prefix shared by all filenames. MIN_DIR specifies
# the minimum number of directories that a filename may have after removing
# the prefix.
#
sub get_common_prefix($@)
{
my ($min_dir, @files) = @_;
my $file;
my @prefix;
my $i;
foreach $file (@files) {
my ($v, $d, $f) = splitpath($file);
my @comp = splitdir($d);
if (!@prefix) {
@prefix = @comp;
next;
}
for ($i = 0; $i < scalar(@comp) && $i < scalar(@prefix); $i++) {
if ($comp[$i] ne $prefix[$i] ||
((scalar(@comp) - ($i + 1)) <= $min_dir)) {
delete(@prefix[$i..scalar(@prefix)]);
last;
}
}
}
return catdir(@prefix);
}
#
# gen_info(directory)
#
# Traverse DIRECTORY and create a .info file for each data file found.
# The .info file contains TEST_NAME in the following format:
#
# TN:<test name>
#
# For each source file name referenced in the data file, there is a section
# containing source code and coverage data:
#
# SF:<absolute path to the source file>
# FN:<line number of function start>,<function name> for each function
# DA:<line number>,<execution count> for each instrumented line
# LH:<number of lines with an execution count> greater than 0
# LF:<number of instrumented lines>
#
# Sections are separated by:
#
# end_of_record
#
# In addition to the main source code file there are sections for each
# #included file containing executable code. Note that the absolute path
# of a source file is generated by interpreting the contents of the respective
# graph file. Relative filenames are prefixed with the directory in which the
# graph file is found. Note also that symbolic links to the graph file will be
# resolved so that the actual file path is used instead of the path to a link.
# This approach is necessary for the mechanism to work with the /proc/gcov
# files.
#
# Die on error.
#
sub gen_info($)
{
my $directory = $_[0];
my @file_list;
my $file;
my $prefix;
my $type;
my $ext;
if ($initial) {
$type = "graph";
$ext = $graph_file_extension;
} else {
$type = "data";
$ext = $data_file_extension;
}
if (-d $directory)
{
info("Scanning $directory for $ext files ...\n");
@file_list = `find "$directory" $maxdepth $follow -name \\*$ext -type f -o -name \\*$ext -type l 2>/dev/null`;
chomp(@file_list);
if (!@file_list) {
warn("WARNING: no $ext files found in $directory - ".
"skipping!\n");
return;
}
$prefix = get_common_prefix(1, @file_list);
info("Found %d %s files in %s\n", $#file_list+1, $type,
$directory);
}
else
{
@file_list = ($directory);
$prefix = "";
}
# Process all files in list
foreach $file (@file_list) {
# Process file
if ($initial) {
process_graphfile($file, $prefix);
} else {
process_dafile($file, $prefix);
}
}
# Report whether files were excluded.
if (%excluded_files) {
info("Excluded data for %d files due to include/exclude options\n",
scalar keys %excluded_files);
}
}
#
# derive_data(contentdata, funcdata, bbdata)
#
# Calculate function coverage data by combining line coverage data and the
# list of lines belonging to a function.
#
# contentdata: [ instr1, count1, source1, instr2, count2, source2, ... ]
# instr<n>: Instrumentation flag for line n
# count<n>: Execution count for line n
# source<n>: Source code for line n
#
# funcdata: [ count1, func1, count2, func2, ... ]
# count<n>: Execution count for function number n
# func<n>: Function name for function number n
#
# bbdata: function_name -> [ line1, line2, ... ]
# line<n>: Line number belonging to the corresponding function
#
sub derive_data($$$)
{
my ($contentdata, $funcdata, $bbdata) = @_;
my @gcov_content = @{$contentdata};
my @gcov_functions = @{$funcdata};
my %fn_count;
my %ln_fn;
my $line;
my $maxline;
my %fn_name;
my $fn;
my $count;
if (!defined($bbdata)) {
return @gcov_functions;
}
# First add existing function data
while (@gcov_functions) {
$count = shift(@gcov_functions);
$fn = shift(@gcov_functions);
$fn_count{$fn} = $count;
}
# Convert line coverage data to function data
foreach $fn (keys(%{$bbdata})) {
my $line_data = $bbdata->{$fn};
my $line;
my $fninstr = 0;
if ($fn eq "") {
next;
}
# Find the lowest line count for this function
$count = 0;
foreach $line (@$line_data) {
my $linstr = $gcov_content[ ( $line - 1 ) * 3 + 0 ];
my $lcount = $gcov_content[ ( $line - 1 ) * 3 + 1 ];
next if (!$linstr);
$fninstr = 1;
if (($lcount > 0) &&
(($count == 0) || ($lcount < $count))) {
$count = $lcount;
}
}
next if (!$fninstr);
$fn_count{$fn} = $count;
}
# Check if we got data for all functions
foreach $fn (keys(%fn_name)) {
if ($fn eq "") {
next;
}
if (defined($fn_count{$fn})) {
next;
}
warn("WARNING: no derived data found for function $fn\n");
}
# Convert hash to list in @gcov_functions format
foreach $fn (sort(keys(%fn_count))) {
push(@gcov_functions, $fn_count{$fn}, $fn);
}
return @gcov_functions;
}
#
# get_filenames(directory, pattern)
#
# Return a list of filenames found in directory which match the specified
# pattern.
#
# Die on error.
#
sub get_filenames($$)
{
my ($dirname, $pattern) = @_;
my @result;
my $directory;
local *DIR;
opendir(DIR, $dirname) or
die("ERROR: cannot read directory $dirname\n");
while ($directory = readdir(DIR)) {
push(@result, $directory) if ($directory =~ /$pattern/);
}
closedir(DIR);
return @result;
}
#
# process_dafile(da_filename, dir)
#
# Create a .info file for a single data file.
#
# Die on error.
#
sub process_dafile($$)
{
my ($file, $dir) = @_;
my $da_filename; # Name of data file to process
my $da_dir; # Directory of data file
my $source_dir; # Directory of source file
my $da_basename; # data filename without ".da/.gcda" extension
my $bb_filename; # Name of respective graph file
my $bb_basename; # Basename of the original graph file
my $graph; # Contents of graph file
my $instr; # Contents of graph file part 2
my $gcov_error; # Error code of gcov tool
my $object_dir; # Directory containing all object files
my $source_filename; # Name of a source code file
my $gcov_file; # Name of a .gcov file
my @gcov_content; # Content of a .gcov file
my $gcov_branches; # Branch content of a .gcov file
my @gcov_functions; # Function calls of a .gcov file
my @gcov_list; # List of generated .gcov files
my $line_number; # Line number count
my $lines_hit; # Number of instrumented lines hit
my $lines_found; # Number of instrumented lines found
my $funcs_hit; # Number of instrumented functions hit
my $funcs_found; # Number of instrumented functions found
my $br_hit;
my $br_found;
my $source; # gcov source header information
my $object; # gcov object header information
my @matches; # List of absolute paths matching filename
my $base_dir; # Base directory for current file
my @tmp_links; # Temporary links to be cleaned up
my @result;
my $index;
my $da_renamed; # If data file is to be renamed
local *INFO_HANDLE;
info("Processing %s\n", abs2rel($file, $dir));
# Get path to data file in absolute and normalized form (begins with /,
# contains no more ../ or ./)
$da_filename = solve_relative_path($cwd, $file);
# Get directory and basename of data file
($da_dir, $da_basename) = split_filename($da_filename);
$source_dir = $da_dir;
if (is_compat($COMPAT_MODE_LIBTOOL)) {
# Avoid files from .libs dirs
$source_dir =~ s/\.libs$//;
}
if (-z $da_filename)
{
$da_renamed = 1;
}
else
{
$da_renamed = 0;
}
# Construct base_dir for current file
if ($base_directory)
{
$base_dir = $base_directory;
}
else
{
$base_dir = $source_dir;
}
# Check for writable $base_dir (gcov will try to write files there)
stat($base_dir);
if (!-w _)
{
die("ERROR: cannot write to directory $base_dir!\n");
}
# Construct name of graph file
$bb_basename = $da_basename.$graph_file_extension;
$bb_filename = "$da_dir/$bb_basename";
# Find out the real location of graph file in case we're just looking at
# a link
while (readlink($bb_filename))
{
my $last_dir = dirname($bb_filename);
$bb_filename = readlink($bb_filename);
$bb_filename = solve_relative_path($last_dir, $bb_filename);
}
# Ignore empty graph file (e.g. source file with no statement)
if (-z $bb_filename)
{
warn("WARNING: empty $bb_filename (skipped)\n");
return;
}
# Read contents of graph file into hash. We need it later to find out
# the absolute path to each .gcov file created as well as for
# information about functions and their source code positions.
if ($gcov_version < $GCOV_VERSION_3_4_0)
{
if (is_compat($COMPAT_MODE_HAMMER))
{
($instr, $graph) = read_bbg($bb_filename);
}
else
{
($instr, $graph) = read_bb($bb_filename);
}
}
else
{
($instr, $graph) = read_gcno($bb_filename);
}
# Try to find base directory automatically if requested by user
if ($rc_auto_base) {
$base_dir = find_base_from_graph($base_dir, $instr, $graph);
}
($instr, $graph) = adjust_graph_filenames($base_dir, $instr, $graph);
# Set $object_dir to real location of object files. This may differ
# from $da_dir if the graph file is just a link to the "real" object
# file location.
$object_dir = dirname($bb_filename);
# Is the data file in a different directory? (this happens e.g. with
# the gcov-kernel patch)
if ($object_dir ne $da_dir)
{
# Need to create link to data file in $object_dir
system("ln", "-s", $da_filename,
"$object_dir/$da_basename$data_file_extension")
and die ("ERROR: cannot create link $object_dir/".
"$da_basename$data_file_extension!\n");
push(@tmp_links,
"$object_dir/$da_basename$data_file_extension");
# Need to create link to graph file if basename of link
# and file are different (CONFIG_MODVERSION compat)
if ((basename($bb_filename) ne $bb_basename) &&
(! -e "$object_dir/$bb_basename")) {
symlink($bb_filename, "$object_dir/$bb_basename") or
warn("WARNING: cannot create link ".
"$object_dir/$bb_basename\n");
push(@tmp_links, "$object_dir/$bb_basename");
}
}
# Change to directory containing data files and apply GCOV
debug("chdir($base_dir)\n");
chdir($base_dir);
if ($da_renamed)
{
# Need to rename empty data file to workaround
# gcov <= 3.2.x bug (Abort)
system_no_output(3, "mv", "$da_filename", "$da_filename.ori")
and die ("ERROR: cannot rename $da_filename\n");
}
# Execute gcov command and suppress standard output
$gcov_error = system_no_output(1, $gcov_tool, $da_filename,
"-o", $object_dir, @gcov_options);
if ($da_renamed)
{
system_no_output(3, "mv", "$da_filename.ori", "$da_filename")
and die ("ERROR: cannot rename $da_filename.ori");
}
# Clean up temporary links
foreach (@tmp_links) {
unlink($_);
}
if ($gcov_error)
{
if ($ignore[$ERROR_GCOV])
{
warn("WARNING: GCOV failed for $da_filename!\n");
return;
}
die("ERROR: GCOV failed for $da_filename!\n");
}
# Collect data from resulting .gcov files and create .info file
@gcov_list = get_filenames('.', '\.gcov$');
# Check for files
if (!@gcov_list)
{
warn("WARNING: gcov did not create any files for ".
"$da_filename!\n");
}
# Check whether we're writing to a single file
if ($output_filename)
{
if ($output_filename eq "-")
{
*INFO_HANDLE = *STDOUT;
}
else
{
# Append to output file
open(INFO_HANDLE, ">>", $output_filename)
or die("ERROR: cannot write to ".
"$output_filename!\n");
}
}
else
{
# Open .info file for output
open(INFO_HANDLE, ">", "$da_filename.info")
or die("ERROR: cannot create $da_filename.info!\n");
}
# Write test name
printf(INFO_HANDLE "TN:%s\n", $test_name);
# Traverse the list of generated .gcov files and combine them into a
# single .info file
foreach $gcov_file (sort(@gcov_list))
{
my $i;
my $num;
# Skip gcov file for gcc built-in code
next if ($gcov_file eq "<built-in>.gcov");
($source, $object) = read_gcov_header($gcov_file);
if (!defined($source)) {
# Derive source file name from gcov file name if
# header format could not be parsed
$source = $gcov_file;
$source =~ s/\.gcov$//;
}
$source = solve_relative_path($base_dir, $source);
if (defined($adjust_src_pattern)) {
# Apply transformation as specified by user
$source =~ s/$adjust_src_pattern/$adjust_src_replace/g;
}
# gcov will happily create output even if there's no source code
# available - this interferes with checksum creation so we need
# to pull the emergency brake here.
if (! -r $source && $checksum)
{
if ($ignore[$ERROR_SOURCE])
{
warn("WARNING: could not read source file ".
"$source\n");
next;
}
die("ERROR: could not read source file $source\n");
}
@matches = match_filename($source, keys(%{$instr}));
# Skip files that are not mentioned in the graph file
if (!@matches)
{
warn("WARNING: cannot find an entry for ".$gcov_file.
" in $graph_file_extension file, skipping ".
"file!\n");
unlink($gcov_file);
next;
}
# Read in contents of gcov file
@result = read_gcov_file($gcov_file);
if (!defined($result[0])) {
warn("WARNING: skipping unreadable file ".
$gcov_file."\n");
unlink($gcov_file);
next;
}
@gcov_content = @{$result[0]};
$gcov_branches = $result[1];
@gcov_functions = @{$result[2]};
# Skip empty files
if (!@gcov_content)
{
warn("WARNING: skipping empty file ".$gcov_file."\n");
unlink($gcov_file);
next;
}
if (scalar(@matches) == 1)
{
# Just one match
$source_filename = $matches[0];
}
else
{
# Try to solve the ambiguity
$source_filename = solve_ambiguous_match($gcov_file,
\@matches, \@gcov_content);
}
if (@include_patterns)
{
my $keep = 0;
foreach my $pattern (@include_patterns)
{
$keep ||= ($source_filename =~ (/^$pattern$/));
}
if (!$keep)
{
$excluded_files{$source_filename} = ();
unlink($gcov_file);
next;
}
}
if (@exclude_patterns)
{
my $exclude = 0;
foreach my $pattern (@exclude_patterns)
{
$exclude ||= ($source_filename =~ (/^$pattern$/));
}
if ($exclude)
{
$excluded_files{$source_filename} = ();
unlink($gcov_file);
next;
}
}
# Skip external files if requested
if (!$opt_external) {
if (is_external($source_filename)) {
info(" ignoring data for external file ".
"$source_filename\n");
unlink($gcov_file);
next;
}
}
# Write absolute path of source file
printf(INFO_HANDLE "SF:%s\n", $source_filename);
# If requested, derive function coverage data from
# line coverage data of the first line of a function
if ($opt_derive_func_data) {
@gcov_functions =
derive_data(\@gcov_content, \@gcov_functions,
$graph->{$source_filename});
}
# Write function-related information
if (defined($graph->{$source_filename}))
{
my $fn_data = $graph->{$source_filename};
my $fn;
foreach $fn (sort
{$fn_data->{$a}->[0] <=> $fn_data->{$b}->[0]}
keys(%{$fn_data})) {
my $ln_data = $fn_data->{$fn};
my $line = $ln_data->[0];
# Skip empty function
if ($fn eq "") {
next;
}
# Remove excluded functions
if (!$no_markers) {
my $gfn;
my $found = 0;
foreach $gfn (@gcov_functions) {
if ($gfn eq $fn) {
$found = 1;
last;
}
}
if (!$found) {
next;
}
}
# Normalize function name
$fn = filter_fn_name($fn);
print(INFO_HANDLE "FN:$line,$fn\n");
}
}
#--
#-- FNDA: <call-count>, <function-name>
#-- FNF: overall count of functions
#-- FNH: overall count of functions with non-zero call count
#--
$funcs_found = 0;
$funcs_hit = 0;
while (@gcov_functions)
{
my $count = shift(@gcov_functions);
my $fn = shift(@gcov_functions);
$fn = filter_fn_name($fn);
printf(INFO_HANDLE "FNDA:$count,$fn\n");
$funcs_found++;
$funcs_hit++ if ($count > 0);
}
if ($funcs_found > 0) {
printf(INFO_HANDLE "FNF:%s\n", $funcs_found);
printf(INFO_HANDLE "FNH:%s\n", $funcs_hit);
}
# Write coverage information for each instrumented branch:
#
# BRDA:<line number>,<block number>,<branch number>,<taken>
#
# where 'taken' is the number of times the branch was taken
# or '-' if the block to which the branch belongs was never
# executed
$br_found = 0;
$br_hit = 0;
$num = br_gvec_len($gcov_branches);
for ($i = 0; $i < $num; $i++) {
my ($line, $block, $branch, $taken) =
br_gvec_get($gcov_branches, $i);
$block = $BR_VEC_MAX if ($block < 0);
print(INFO_HANDLE "BRDA:$line,$block,$branch,$taken\n");
$br_found++;
$br_hit++ if ($taken ne '-' && $taken > 0);
}
if ($br_found > 0) {
printf(INFO_HANDLE "BRF:%s\n", $br_found);
printf(INFO_HANDLE "BRH:%s\n", $br_hit);
}
# Reset line counters
$line_number = 0;
$lines_found = 0;
$lines_hit = 0;
# Write coverage information for each instrumented line
# Note: @gcov_content contains a list of (flag, count, source)
# tuple for each source code line
while (@gcov_content)
{
$line_number++;
# Check for instrumented line
if ($gcov_content[0])
{
$lines_found++;
printf(INFO_HANDLE "DA:".$line_number.",".
$gcov_content[1].($checksum ?
",". md5_base64($gcov_content[2]) : "").
"\n");
# Increase $lines_hit in case of an execution
# count>0
if ($gcov_content[1] > 0) { $lines_hit++; }
}
# Remove already processed data from array
splice(@gcov_content,0,3);
}
# Write line statistics and section separator
printf(INFO_HANDLE "LF:%s\n", $lines_found);
printf(INFO_HANDLE "LH:%s\n", $lines_hit);
print(INFO_HANDLE "end_of_record\n");
# Remove .gcov file after processing
unlink($gcov_file);
}
if (!($output_filename && ($output_filename eq "-")))
{
close(INFO_HANDLE);
}
# Change back to initial directory
chdir($cwd);
}
#
# solve_relative_path(path, dir)
#
# Solve relative path components of DIR which, if not absolute, resides in PATH.
#
sub solve_relative_path($$)
{
my $path = $_[0];
my $dir = $_[1];
my $volume;
my $directories;
my $filename;
my @dirs; # holds path elements
my $result;
# Convert from Windows path to msys path
if( $^O eq "msys" )
{
# search for a windows drive letter at the beginning
($volume, $directories, $filename) = File::Spec::Win32->splitpath( $dir );
if( $volume ne '' )
{
my $uppercase_volume;
# transform c/d\../e/f\g to Windows style c\d\..\e\f\g
$dir = File::Spec::Win32->canonpath( $dir );
# use Win32 module to retrieve path components
# $uppercase_volume is not used any further
( $uppercase_volume, $directories, $filename ) = File::Spec::Win32->splitpath( $dir );
@dirs = File::Spec::Win32->splitdir( $directories );
# prepend volume, since in msys C: is always mounted to /c
$volume =~ s|^([a-zA-Z]+):|/\L$1\E|;
unshift( @dirs, $volume );
# transform to Unix style '/' path
$directories = File::Spec->catdir( @dirs );
$dir = File::Spec->catpath( '', $directories, $filename );
} else {
# eliminate '\' path separators
$dir = File::Spec->canonpath( $dir );
}
}
$result = $dir;
# Prepend path if not absolute
if ($dir =~ /^[^\/]/)
{
$result = "$path/$result";
}
# Remove //
$result =~ s/\/\//\//g;
# Remove .
$result =~ s/\/\.\//\//g;
$result =~ s/\/\.$/\//g;
# Remove trailing /
$result =~ s/\/$//g;
# Solve ..
while ($result =~ s/\/[^\/]+\/\.\.\//\//)
{
}
# Remove preceding ..
$result =~ s/^\/\.\.\//\//g;
return $result;
}
#
# match_filename(gcov_filename, list)
#
# Return a list of those entries of LIST which match the relative filename
# GCOV_FILENAME.
#
sub match_filename($@)
{
my ($filename, @list) = @_;
my ($vol, $dir, $file) = splitpath($filename);
my @comp = splitdir($dir);
my $comps = scalar(@comp);
my $entry;
my @result;
entry:
foreach $entry (@list) {
my ($evol, $edir, $efile) = splitpath($entry);
my @ecomp;
my $ecomps;
my $i;
# Filename component must match
if ($efile ne $file) {
next;
}
# Check directory components last to first for match
@ecomp = splitdir($edir);
$ecomps = scalar(@ecomp);
if ($ecomps < $comps) {
next;
}
for ($i = 0; $i < $comps; $i++) {
if ($comp[$comps - $i - 1] ne
$ecomp[$ecomps - $i - 1]) {
next entry;
}
}
push(@result, $entry),
}
return @result;
}
#
# solve_ambiguous_match(rel_filename, matches_ref, gcov_content_ref)
#
# Try to solve ambiguous matches of mapping (gcov file) -> (source code) file
# by comparing source code provided in the GCOV file with that of the files
# in MATCHES. REL_FILENAME identifies the relative filename of the gcov
# file.
#
# Return the one real match or die if there is none.
#
sub solve_ambiguous_match($$$)
{
my $rel_name = $_[0];
my $matches = $_[1];
my $content = $_[2];
my $filename;
my $index;
my $no_match;
local *SOURCE;
# Check the list of matches
foreach $filename (@$matches)
{
# Compare file contents
open(SOURCE, "<", $filename)
or die("ERROR: cannot read $filename!\n");
$no_match = 0;
for ($index = 2; <SOURCE>; $index += 3)
{
chomp;
# Also remove CR from line-end
s/\015$//;
if ($_ ne @$content[$index])
{
$no_match = 1;
last;
}
}
close(SOURCE);
if (!$no_match)
{
info("Solved source file ambiguity for $rel_name\n");
return $filename;
}
}
die("ERROR: could not match gcov data for $rel_name!\n");
}
#
# split_filename(filename)
#
# Return (path, filename, extension) for a given FILENAME.
#
sub split_filename($)
{
my @path_components = split('/', $_[0]);
my @file_components = split('\.', pop(@path_components));
my $extension = pop(@file_components);
return (join("/",@path_components), join(".",@file_components),
$extension);
}
#
# read_gcov_header(gcov_filename)
#
# Parse file GCOV_FILENAME and return a list containing the following
# information:
#
# (source, object)
#
# where:
#
# source: complete relative path of the source code file (gcc >= 3.3 only)
# object: name of associated graph file
#
# Die on error.
#
sub read_gcov_header($)
{
my $source;
my $object;
local *INPUT;
if (!open(INPUT, "<", $_[0]))
{
if ($ignore_errors[$ERROR_GCOV])
{
warn("WARNING: cannot read $_[0]!\n");
return (undef,undef);
}
die("ERROR: cannot read $_[0]!\n");
}
while (<INPUT>)
{
chomp($_);
# Also remove CR from line-end
s/\015$//;
if (/^\s+-:\s+0:Source:(.*)$/)
{
# Source: header entry
$source = $1;
}
elsif (/^\s+-:\s+0:Object:(.*)$/)
{
# Object: header entry
$object = $1;
}
else
{
last;
}
}
close(INPUT);
return ($source, $object);
}
#
# br_gvec_len(vector)
#
# Return the number of entries in the branch coverage vector.
#
sub br_gvec_len($)
{
my ($vec) = @_;
return 0 if (!defined($vec));
return (length($vec) * 8 / $BR_VEC_WIDTH) / $BR_VEC_ENTRIES;
}
#
# br_gvec_get(vector, number)
#
# Return an entry from the branch coverage vector.
#
sub br_gvec_get($$)
{
my ($vec, $num) = @_;
my $line;
my $block;
my $branch;
my $taken;
my $offset = $num * $BR_VEC_ENTRIES;
# Retrieve data from vector
$line = vec($vec, $offset + $BR_LINE, $BR_VEC_WIDTH);
$block = vec($vec, $offset + $BR_BLOCK, $BR_VEC_WIDTH);
$block = -1 if ($block == $BR_VEC_MAX);
$branch = vec($vec, $offset + $BR_BRANCH, $BR_VEC_WIDTH);
$taken = vec($vec, $offset + $BR_TAKEN, $BR_VEC_WIDTH);
# Decode taken value from an integer
if ($taken == 0) {
$taken = "-";
} else {
$taken--;
}
return ($line, $block, $branch, $taken);
}
#
# br_gvec_push(vector, line, block, branch, taken)
#
# Add an entry to the branch coverage vector.
#
sub br_gvec_push($$$$$)
{
my ($vec, $line, $block, $branch, $taken) = @_;
my $offset;
$vec = "" if (!defined($vec));
$offset = br_gvec_len($vec) * $BR_VEC_ENTRIES;
$block = $BR_VEC_MAX if $block < 0;
# Encode taken value into an integer
if ($taken eq "-") {
$taken = 0;
} else {
$taken++;
}
# Add to vector
vec($vec, $offset + $BR_LINE, $BR_VEC_WIDTH) = $line;
vec($vec, $offset + $BR_BLOCK, $BR_VEC_WIDTH) = $block;
vec($vec, $offset + $BR_BRANCH, $BR_VEC_WIDTH) = $branch;
vec($vec, $offset + $BR_TAKEN, $BR_VEC_WIDTH) = $taken;
return $vec;
}
#
# read_gcov_file(gcov_filename)
#
# Parse file GCOV_FILENAME (.gcov file format) and return the list:
# (reference to gcov_content, reference to gcov_branch, reference to gcov_func)
#
# gcov_content is a list of 3 elements
# (flag, count, source) for each source code line:
#
# $result[($line_number-1)*3+0] = instrumentation flag for line $line_number
# $result[($line_number-1)*3+1] = execution count for line $line_number
# $result[($line_number-1)*3+2] = source code text for line $line_number
#
# gcov_branch is a vector of 4 4-byte long elements for each branch:
# line number, block number, branch number, count + 1 or 0
#
# gcov_func is a list of 2 elements
# (number of calls, function name) for each function
#
# Die on error.
#
sub read_gcov_file($)
{
my $filename = $_[0];
my @result = ();
my $branches = "";
my @functions = ();
my $number;
my $exclude_flag = 0;
my $exclude_line = 0;
my $exclude_br_flag = 0;
my $exclude_branch = 0;
my $last_block = $UNNAMED_BLOCK;
my $last_line = 0;
local *INPUT;
if (!open(INPUT, "<", $filename)) {
if ($ignore_errors[$ERROR_GCOV])
{
warn("WARNING: cannot read $filename!\n");
return (undef, undef, undef);
}
die("ERROR: cannot read $filename!\n");
}
if ($gcov_version < $GCOV_VERSION_3_3_0)
{
# Expect gcov format as used in gcc < 3.3
while (<INPUT>)
{
chomp($_);
# Also remove CR from line-end
s/\015$//;
if (/^branch\s+(\d+)\s+taken\s+=\s+(\d+)/) {
next if (!$br_coverage);
next if ($exclude_line);
next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, $2);
} elsif (/^branch\s+(\d+)\s+never\s+executed/) {
next if (!$br_coverage);
next if ($exclude_line);
next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, '-');
}
elsif (/^call/ || /^function/)
{
# Function call return data
}
else
{
$last_line++;
# Check for exclusion markers
if (!$no_markers) {
if (/$EXCL_STOP/) {
$exclude_flag = 0;
} elsif (/$EXCL_START/) {
$exclude_flag = 1;
}
if (/$excl_line/ || $exclude_flag) {
$exclude_line = 1;
} else {
$exclude_line = 0;
}
}
# Check for exclusion markers (branch exclude)
if (!$no_markers) {
if (/$EXCL_BR_STOP/) {
$exclude_br_flag = 0;
} elsif (/$EXCL_BR_START/) {
$exclude_br_flag = 1;
}
if (/$excl_br_line/ || $exclude_br_flag) {
$exclude_branch = 1;
} else {
$exclude_branch = 0;
}
}
# Source code execution data
if (/^\t\t(.*)$/)
{
# Uninstrumented line
push(@result, 0);
push(@result, 0);
push(@result, $1);
next;
}
$number = (split(" ",substr($_, 0, 16)))[0];
# Check for zero count which is indicated
# by ######
if ($number eq "######") { $number = 0; }
if ($exclude_line) {
# Register uninstrumented line instead
push(@result, 0);
push(@result, 0);
} else {
push(@result, 1);
push(@result, $number);
}
push(@result, substr($_, 16));
}
}
}
else
{
# Expect gcov format as used in gcc >= 3.3
while (<INPUT>)
{
chomp($_);
# Also remove CR from line-end
s/\015$//;
if (/^\s*(\d+|\$+):\s*(\d+)-block\s+(\d+)\s*$/) {
# Block information - used to group related
# branches
$last_line = $2;
$last_block = $3;
} elsif (/^branch\s+(\d+)\s+taken\s+(\d+)/) {
next if (!$br_coverage);
next if ($exclude_line);
next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, $2);
} elsif (/^branch\s+(\d+)\s+never\s+executed/) {
next if (!$br_coverage);
next if ($exclude_line);
next if ($exclude_branch);
$branches = br_gvec_push($branches, $last_line,
$last_block, $1, '-');
}
elsif (/^function\s+(.+)\s+called\s+(\d+)\s+/)
{
next if (!$func_coverage);
if ($exclude_line) {
next;
}
push(@functions, $2, $1);
}
elsif (/^call/)
{
# Function call return data
}
elsif (/^\s*([^:]+):\s*([^:]+):(.*)$/)
{
my ($count, $line, $code) = ($1, $2, $3);
$last_line = $line;
$last_block = $UNNAMED_BLOCK;
# Check for exclusion markers
if (!$no_markers) {
if (/$EXCL_STOP/) {
$exclude_flag = 0;
} elsif (/$EXCL_START/) {
$exclude_flag = 1;
}
if (/$excl_line/ || $exclude_flag) {
$exclude_line = 1;
} else {
$exclude_line = 0;
}
}
# Check for exclusion markers (branch exclude)
if (!$no_markers) {
if (/$EXCL_BR_STOP/) {
$exclude_br_flag = 0;
} elsif (/$EXCL_BR_START/) {
$exclude_br_flag = 1;
}
if (/$excl_br_line/ || $exclude_br_flag) {
$exclude_branch = 1;
} else {
$exclude_branch = 0;
}
}
# <exec count>:<line number>:<source code>
if ($line eq "0")
{
# Extra data
}
elsif ($count eq "-")
{
# Uninstrumented line
push(@result, 0);
push(@result, 0);
push(@result, $code);
}
else
{
if ($exclude_line) {
push(@result, 0);
push(@result, 0);
} else {
# Check for zero count
if ($count =~ /^[#=]/) {
$count = 0;
}
push(@result, 1);
push(@result, $count);
}
push(@result, $code);
}
}
}
}
close(INPUT);
if ($exclude_flag || $exclude_br_flag) {
warn("WARNING: unterminated exclusion section in $filename\n");
}
return(\@result, $branches, \@functions);
}
# Map LLVM versions to the version of GCC gcov which they emulate.
sub map_llvm_version($)
{
my ($ver) = @_;
return 0x040200 if ($ver >= 0x030400);
warn("WARNING: This version of LLVM's gcov is unknown. ".
"Assuming it emulates GCC gcov version 4.2.\n");
return 0x040200;
}
# Return a readable version of encoded gcov version.
sub version_to_str($)
{
my ($ver) = @_;
my ($a, $b, $c);
$a = $ver >> 16 & 0xff;
$b = $ver >> 8 & 0xff;
$c = $ver & 0xff;
return "$a.$b.$c";
}
#
# Get the GCOV tool version. Return an integer number which represents the
# GCOV version. Version numbers can be compared using standard integer
# operations.
#
sub get_gcov_version()
{
local *HANDLE;
my $version_string;
my $result;
my ($a, $b, $c) = (4, 2, 0); # Fallback version
# Examples for gcov version output:
#
# gcov (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
#
# gcov (crosstool-NG 1.18.0) 4.7.2
#
# LLVM (http://llvm.org/):
# LLVM version 3.4svn
#
# Apple LLVM version 8.0.0 (clang-800.0.38)
# Optimized build.
# Default target: x86_64-apple-darwin16.0.0
# Host CPU: haswell
open(GCOV_PIPE, "-|", "$gcov_tool --version")
or die("ERROR: cannot retrieve gcov version!\n");
local $/;
$version_string = <GCOV_PIPE>;
close(GCOV_PIPE);
# Remove all bracketed information
$version_string =~ s/\([^\)]*\)//g;
if ($version_string =~ /(\d+)\.(\d+)(\.(\d+))?/) {
($a, $b, $c) = ($1, $2, $4);
$c = 0 if (!defined($c));
} else {
warn("WARNING: cannot determine gcov version - ".
"assuming $a.$b.$c\n");
}
$result = $a << 16 | $b << 8 | $c;
if ($version_string =~ /LLVM/) {
$result = map_llvm_version($result);
info("Found LLVM gcov version $a.$b.$c, which emulates gcov ".
"version ".version_to_str($result)."\n");
} else {
info("Found gcov version: ".version_to_str($result)."\n");
}
return ($result, $version_string);
}
#
# info(printf_parameter)
#
# Use printf to write PRINTF_PARAMETER to stdout only when the $quiet flag
# is not set.
#
sub info(@)
{
if (!$quiet)
{
# Print info string
if (defined($output_filename) && ($output_filename eq "-"))
{
# Don't interfere with the .info output to STDOUT
printf(STDERR @_);
}
else
{
printf(@_);
}
}
}
#
# int_handler()
#
# Called when the script was interrupted by an INT signal (e.g. CTRl-C)
#
sub int_handler()
{
if ($cwd) { chdir($cwd); }
info("Aborted.\n");
exit(1);
}
#
# system_no_output(mode, parameters)
#
# Call an external program using PARAMETERS while suppressing depending on
# the value of MODE:
#
# MODE & 1: suppress STDOUT
# MODE & 2: suppress STDERR
#
# Return 0 on success, non-zero otherwise.
#
sub system_no_output($@)
{
my $mode = shift;
my $result;
local *OLD_STDERR;
local *OLD_STDOUT;
# Save old stdout and stderr handles
($mode & 1) && open(OLD_STDOUT, ">>&", "STDOUT");
($mode & 2) && open(OLD_STDERR, ">>&", "STDERR");
# Redirect to /dev/null
($mode & 1) && open(STDOUT, ">", "/dev/null");
($mode & 2) && open(STDERR, ">", "/dev/null");
debug("system(".join(' ', @_).")\n");
system(@_);
$result = $?;
# Close redirected handles
($mode & 1) && close(STDOUT);
($mode & 2) && close(STDERR);
# Restore old handles
($mode & 1) && open(STDOUT, ">>&", "OLD_STDOUT");
($mode & 2) && open(STDERR, ">>&", "OLD_STDERR");
return $result;
}
#
# read_config(filename)
#
# Read configuration file FILENAME and return a reference to a hash containing
# all valid key=value pairs found.
#
sub read_config($)
{
my $filename = $_[0];
my %result;
my $key;
my $value;
local *HANDLE;
if (!open(HANDLE, "<", $filename))
{
warn("WARNING: cannot read configuration file $filename\n");
return undef;
}
while (<HANDLE>)
{
chomp;
# Skip comments
s/#.*//;
# Remove leading blanks
s/^\s+//;
# Remove trailing blanks
s/\s+$//;
next unless length;
($key, $value) = split(/\s*=\s*/, $_, 2);
if (defined($key) && defined($value))
{
$result{$key} = $value;
}
else
{
warn("WARNING: malformed statement in line $. ".
"of configuration file $filename\n");
}
}
close(HANDLE);
return \%result;
}
#
# apply_config(REF)
#
# REF is a reference to a hash containing the following mapping:
#
# key_string => var_ref
#
# where KEY_STRING is a keyword and VAR_REF is a reference to an associated
# variable. If the global configuration hashes CONFIG or OPT_RC contain a value
# for keyword KEY_STRING, VAR_REF will be assigned the value for that keyword.
#
sub apply_config($)
{
my $ref = $_[0];
foreach (keys(%{$ref}))
{
if (defined($opt_rc{$_})) {
${$ref->{$_}} = $opt_rc{$_};
} elsif (defined($config->{$_})) {
${$ref->{$_}} = $config->{$_};
}
}
}
#
# get_exclusion_data(filename)
#
# Scan specified source code file for exclusion markers and return
# linenumber -> 1
# for all lines which should be excluded.
#
sub get_exclusion_data($)
{
my ($filename) = @_;
my %list;
my $flag = 0;
local *HANDLE;
if (!open(HANDLE, "<", $filename)) {
warn("WARNING: could not open $filename\n");
return undef;
}
while (<HANDLE>) {
if (/$EXCL_STOP/) {
$flag = 0;
} elsif (/$EXCL_START/) {
$flag = 1;
}
if (/$excl_line/ || $flag) {
$list{$.} = 1;
}
}
close(HANDLE);
if ($flag) {
warn("WARNING: unterminated exclusion section in $filename\n");
}
return \%list;
}
#
# apply_exclusion_data(instr, graph)
#
# Remove lines from instr and graph data structures which are marked
# for exclusion in the source code file.
#
# Return adjusted (instr, graph).
#
# graph : file name -> function data
# function data : function name -> line data
# line data : [ line1, line2, ... ]
#
# instr : filename -> line data
# line data : [ line1, line2, ... ]
#
sub apply_exclusion_data($$)
{
my ($instr, $graph) = @_;
my $filename;
my %excl_data;
my $excl_read_failed = 0;
# Collect exclusion marker data
foreach $filename (sort_uniq_lex(keys(%{$graph}), keys(%{$instr}))) {
my $excl = get_exclusion_data($filename);
# Skip and note if file could not be read
if (!defined($excl)) {
$excl_read_failed = 1;
next;
}
# Add to collection if there are markers
$excl_data{$filename} = $excl if (keys(%{$excl}) > 0);
}
# Warn if not all source files could be read
if ($excl_read_failed) {
warn("WARNING: some exclusion markers may be ignored\n");
}
# Skip if no markers were found
return ($instr, $graph) if (keys(%excl_data) == 0);
# Apply exclusion marker data to graph
foreach $filename (keys(%excl_data)) {
my $function_data = $graph->{$filename};
my $excl = $excl_data{$filename};
my $function;
next if (!defined($function_data));
foreach $function (keys(%{$function_data})) {
my $line_data = $function_data->{$function};
my $line;
my @new_data;
# To be consistent with exclusion parser in non-initial
# case we need to remove a function if the first line
# was excluded
if ($excl->{$line_data->[0]}) {
delete($function_data->{$function});
next;
}
# Copy only lines which are not excluded
foreach $line (@{$line_data}) {
push(@new_data, $line) if (!$excl->{$line});
}
# Store modified list
if (scalar(@new_data) > 0) {
$function_data->{$function} = \@new_data;
} else {
# All of this function was excluded
delete($function_data->{$function});
}
}
# Check if all functions of this file were excluded
if (keys(%{$function_data}) == 0) {
delete($graph->{$filename});
}
}
# Apply exclusion marker data to instr
foreach $filename (keys(%excl_data)) {
my $line_data = $instr->{$filename};
my $excl = $excl_data{$filename};
my $line;
my @new_data;
next if (!defined($line_data));
# Copy only lines which are not excluded
foreach $line (@{$line_data}) {
push(@new_data, $line) if (!$excl->{$line});
}
# Store modified list
$instr->{$filename} = \@new_data;
}
return ($instr, $graph);
}
sub process_graphfile($$)
{
my ($file, $dir) = @_;
my $graph_filename = $file;
my $graph_dir;
my $graph_basename;
my $source_dir;
my $base_dir;
my $graph;
my $instr;
my $filename;
local *INFO_HANDLE;
info("Processing %s\n", abs2rel($file, $dir));
# Get path to data file in absolute and normalized form (begins with /,
# contains no more ../ or ./)
$graph_filename = solve_relative_path($cwd, $graph_filename);
# Get directory and basename of data file
($graph_dir, $graph_basename) = split_filename($graph_filename);
$source_dir = $graph_dir;
if (is_compat($COMPAT_MODE_LIBTOOL)) {
# Avoid files from .libs dirs
$source_dir =~ s/\.libs$//;
}
# Construct base_dir for current file
if ($base_directory)
{
$base_dir = $base_directory;
}
else
{
$base_dir = $source_dir;
}
# Ignore empty graph file (e.g. source file with no statement)
if (-z $graph_filename)
{
warn("WARNING: empty $graph_filename (skipped)\n");
return;
}
if ($gcov_version < $GCOV_VERSION_3_4_0)
{
if (is_compat($COMPAT_MODE_HAMMER))
{
($instr, $graph) = read_bbg($graph_filename);
}
else
{
($instr, $graph) = read_bb($graph_filename);
}
}
else
{
($instr, $graph) = read_gcno($graph_filename);
}
# Try to find base directory automatically if requested by user
if ($rc_auto_base) {
$base_dir = find_base_from_graph($base_dir, $instr, $graph);
}
($instr, $graph) = adjust_graph_filenames($base_dir, $instr, $graph);
if (!$no_markers) {
# Apply exclusion marker data to graph file data
($instr, $graph) = apply_exclusion_data($instr, $graph);
}
# Check whether we're writing to a single file
if ($output_filename)
{
if ($output_filename eq "-")
{
*INFO_HANDLE = *STDOUT;
}
else
{
# Append to output file
open(INFO_HANDLE, ">>", $output_filename)
or die("ERROR: cannot write to ".
"$output_filename!\n");
}
}
else
{
# Open .info file for output
open(INFO_HANDLE, ">", "$graph_filename.info")
or die("ERROR: cannot create $graph_filename.info!\n");
}
# Write test name
printf(INFO_HANDLE "TN:%s\n", $test_name);
foreach $filename (sort(keys(%{$instr})))
{
my $funcdata = $graph->{$filename};
my $line;
my $linedata;
# Skip external files if requested
if (!$opt_external) {
if (is_external($filename)) {
info(" ignoring data for external file ".
"$filename\n");
next;
}
}
print(INFO_HANDLE "SF:$filename\n");
if (defined($funcdata) && $func_coverage) {
my @functions = sort {$funcdata->{$a}->[0] <=>
$funcdata->{$b}->[0]}
keys(%{$funcdata});
my $func;
# Gather list of instrumented lines and functions
foreach $func (@functions) {
$linedata = $funcdata->{$func};
# Print function name and starting line
print(INFO_HANDLE "FN:".$linedata->[0].
",".filter_fn_name($func)."\n");
}
# Print zero function coverage data
foreach $func (@functions) {
print(INFO_HANDLE "FNDA:0,".
filter_fn_name($func)."\n");
}
# Print function summary
print(INFO_HANDLE "FNF:".scalar(@functions)."\n");
print(INFO_HANDLE "FNH:0\n");
}
# Print zero line coverage data
foreach $line (@{$instr->{$filename}}) {
print(INFO_HANDLE "DA:$line,0\n");
}
# Print line summary
print(INFO_HANDLE "LF:".scalar(@{$instr->{$filename}})."\n");
print(INFO_HANDLE "LH:0\n");
print(INFO_HANDLE "end_of_record\n");
}
if (!($output_filename && ($output_filename eq "-")))
{
close(INFO_HANDLE);
}
}
sub filter_fn_name($)
{
my ($fn) = @_;
# Remove characters used internally as function name delimiters
$fn =~ s/[,=]/_/g;
return $fn;
}
sub warn_handler($)
{
my ($msg) = @_;
warn("$tool_name: $msg");
}
sub die_handler($)
{
my ($msg) = @_;
die("$tool_name: $msg");
}
#
# graph_error(filename, message)
#
# Print message about error in graph file. If ignore_graph_error is set, return.
# Otherwise abort.
#
sub graph_error($$)
{
my ($filename, $msg) = @_;
if ($ignore[$ERROR_GRAPH]) {
warn("WARNING: $filename: $msg - skipping\n");
return;
}
die("ERROR: $filename: $msg\n");
}
#
# graph_expect(description)
#
# If debug is set to a non-zero value, print the specified description of what
# is expected to be read next from the graph file.
#
sub graph_expect($)
{
my ($msg) = @_;
if (!$debug || !defined($msg)) {
return;
}
print(STDERR "DEBUG: expecting $msg\n");
}
#
# graph_read(handle, bytes[, description, peek])
#
# Read and return the specified number of bytes from handle. Return undef
# if the number of bytes could not be read. If PEEK is non-zero, reset
# file position after read.
#
sub graph_read(*$;$$)
{
my ($handle, $length, $desc, $peek) = @_;
my $data;
my $result;
my $pos;
graph_expect($desc);
if ($peek) {
$pos = tell($handle);
if ($pos == -1) {
warn("Could not get current file position: $!\n");
return undef;
}
}
$result = read($handle, $data, $length);
if ($debug) {
my $op = $peek ? "peek" : "read";
my $ascii = "";
my $hex = "";
my $i;
print(STDERR "DEBUG: $op($length)=$result: ");
for ($i = 0; $i < length($data); $i++) {
my $c = substr($data, $i, 1);;
my $n = ord($c);
$hex .= sprintf("%02x ", $n);
if ($n >= 32 && $n <= 127) {
$ascii .= $c;
} else {
$ascii .= ".";
}
}
print(STDERR "$hex |$ascii|");
print(STDERR "\n");
}
if ($peek) {
if (!seek($handle, $pos, 0)) {
warn("Could not set file position: $!\n");
return undef;
}
}
if ($result != $length) {
return undef;
}
return $data;
}
#
# graph_skip(handle, bytes[, description])
#
# Read and discard the specified number of bytes from handle. Return non-zero
# if bytes could be read, zero otherwise.
#
sub graph_skip(*$;$)
{
my ($handle, $length, $desc) = @_;
if (defined(graph_read($handle, $length, $desc))) {
return 1;
}
return 0;
}
#
# uniq(list)
#
# Return list without duplicate entries.
#
sub uniq(@)
{
my (@list) = @_;
my @new_list;
my %known;
foreach my $item (@list) {
next if ($known{$item});
$known{$item} = 1;
push(@new_list, $item);
}
return @new_list;
}
#
# sort_uniq(list)
#
# Return list in numerically ascending order and without duplicate entries.
#
sub sort_uniq(@)
{
my (@list) = @_;
my %hash;
foreach (@list) {
$hash{$_} = 1;
}
return sort { $a <=> $b } keys(%hash);
}
#
# sort_uniq_lex(list)
#
# Return list in lexically ascending order and without duplicate entries.
#
sub sort_uniq_lex(@)
{
my (@list) = @_;
my %hash;
foreach (@list) {
$hash{$_} = 1;
}
return sort keys(%hash);
}
#
# parent_dir(dir)
#
# Return parent directory for DIR. DIR must not contain relative path
# components.
#
sub parent_dir($)
{
my ($dir) = @_;
my ($v, $d, $f) = splitpath($dir, 1);
my @dirs = splitdir($d);
pop(@dirs);
return catpath($v, catdir(@dirs), $f);
}
#
# find_base_from_graph(base_dir, instr, graph)
#
# Try to determine the base directory of the graph file specified by INSTR
# and GRAPH. The base directory is the base for all relative filenames in
# the graph file. It is defined by the current working directory at time
# of compiling the source file.
#
# This function implements a heuristic which relies on the following
# assumptions:
# - all files used for compilation are still present at their location
# - the base directory is either BASE_DIR or one of its parent directories
# - files by the same name are not present in multiple parent directories
#
sub find_base_from_graph($$$)
{
my ($base_dir, $instr, $graph) = @_;
my $old_base;
my $best_miss;
my $best_base;
my %rel_files;
# Determine list of relative paths
foreach my $filename (keys(%{$instr}), keys(%{$graph})) {
next if (file_name_is_absolute($filename));
$rel_files{$filename} = 1;
}
# Early exit if there are no relative paths
return $base_dir if (!%rel_files);
do {
my $miss = 0;
foreach my $filename (keys(%rel_files)) {
if (!-e solve_relative_path($base_dir, $filename)) {
$miss++;
}
}
debug("base_dir=$base_dir miss=$miss\n");
# Exit if we find an exact match with no misses
return $base_dir if ($miss == 0);
# No exact match, aim for the one with the least source file
# misses
if (!defined($best_base) || $miss < $best_miss) {
$best_base = $base_dir;
$best_miss = $miss;
}
# Repeat until there's no more parent directory
$old_base = $base_dir;
$base_dir = parent_dir($base_dir);
} while ($old_base ne $base_dir);
return $best_base;
}
#
# adjust_graph_filenames(base_dir, instr, graph)
#
# Make relative paths in INSTR and GRAPH absolute and apply
# geninfo_adjust_src_path setting to graph file data.
#
sub adjust_graph_filenames($$$)
{
my ($base_dir, $instr, $graph) = @_;
foreach my $filename (keys(%{$instr})) {
my $old_filename = $filename;
# Convert to absolute canonical form
$filename = solve_relative_path($base_dir, $filename);
# Apply adjustment
if (defined($adjust_src_pattern)) {
$filename =~ s/$adjust_src_pattern/$adjust_src_replace/g;
}
if ($filename ne $old_filename) {
$instr->{$filename} = delete($instr->{$old_filename});
}
}
foreach my $filename (keys(%{$graph})) {
my $old_filename = $filename;
# Make absolute
# Convert to absolute canonical form
$filename = solve_relative_path($base_dir, $filename);
# Apply adjustment
if (defined($adjust_src_pattern)) {
$filename =~ s/$adjust_src_pattern/$adjust_src_replace/g;
}
if ($filename ne $old_filename) {
$graph->{$filename} = delete($graph->{$old_filename});
}
}
return ($instr, $graph);
}
#
# graph_cleanup(graph)
#
# Remove entries for functions with no lines. Remove duplicate line numbers.
# Sort list of line numbers numerically ascending.
#
sub graph_cleanup($)
{
my ($graph) = @_;
my $filename;
foreach $filename (keys(%{$graph})) {
my $per_file = $graph->{$filename};
my $function;
foreach $function (keys(%{$per_file})) {
my $lines = $per_file->{$function};
if (scalar(@$lines) == 0) {
# Remove empty function
delete($per_file->{$function});
next;
}
# Normalize list
$per_file->{$function} = [ uniq(@$lines) ];
}
if (scalar(keys(%{$per_file})) == 0) {
# Remove empty file
delete($graph->{$filename});
}
}
}
#
# graph_find_base(bb)
#
# Try to identify the filename which is the base source file for the
# specified bb data.
#
sub graph_find_base($)
{
my ($bb) = @_;
my %file_count;
my $basefile;
my $file;
my $func;
my $filedata;
my $count;
my $num;
# Identify base name for this bb data.
foreach $func (keys(%{$bb})) {
$filedata = $bb->{$func};
foreach $file (keys(%{$filedata})) {
$count = $file_count{$file};
# Count file occurrence
$file_count{$file} = defined($count) ? $count + 1 : 1;
}
}
$count = 0;
$num = 0;
foreach $file (keys(%file_count)) {
if ($file_count{$file} > $count) {
# The file that contains code for the most functions
# is likely the base file
$count = $file_count{$file};
$num = 1;
$basefile = $file;
} elsif ($file_count{$file} == $count) {
# If more than one file could be the basefile, we
# don't have a basefile
$basefile = undef;
}
}
return $basefile;
}
#
# graph_from_bb(bb, fileorder, bb_filename)
#
# Convert data from bb to the graph format and list of instrumented lines.
# Returns (instr, graph).
#
# bb : function name -> file data
# : undef -> file order
# file data : filename -> line data
# line data : [ line1, line2, ... ]
#
# file order : function name -> [ filename1, filename2, ... ]
#
# graph : file name -> function data
# function data : function name -> line data
# line data : [ line1, line2, ... ]
#
# instr : filename -> line data
# line data : [ line1, line2, ... ]
#
sub graph_from_bb($$$)
{
my ($bb, $fileorder, $bb_filename) = @_;
my $graph = {};
my $instr = {};
my $basefile;
my $file;
my $func;
my $filedata;
my $linedata;
my $order;
$basefile = graph_find_base($bb);
# Create graph structure
foreach $func (keys(%{$bb})) {
$filedata = $bb->{$func};
$order = $fileorder->{$func};
# Account for lines in functions
if (defined($basefile) && defined($filedata->{$basefile})) {
# If the basefile contributes to this function,
# account this function to the basefile.
$graph->{$basefile}->{$func} = $filedata->{$basefile};
} else {
# If the basefile does not contribute to this function,
# account this function to the first file contributing
# lines.
$graph->{$order->[0]}->{$func} =
$filedata->{$order->[0]};
}
foreach $file (keys(%{$filedata})) {
# Account for instrumented lines
$linedata = $filedata->{$file};
push(@{$instr->{$file}}, @$linedata);
}
}
# Clean up array of instrumented lines
foreach $file (keys(%{$instr})) {
$instr->{$file} = [ sort_uniq(@{$instr->{$file}}) ];
}
return ($instr, $graph);
}
#
# graph_add_order(fileorder, function, filename)
#
# Add an entry for filename to the fileorder data set for function.
#
sub graph_add_order($$$)
{
my ($fileorder, $function, $filename) = @_;
my $item;
my $list;
$list = $fileorder->{$function};
foreach $item (@$list) {
if ($item eq $filename) {
return;
}
}
push(@$list, $filename);
$fileorder->{$function} = $list;
}
#
# read_bb_word(handle[, description])
#
# Read and return a word in .bb format from handle.
#
sub read_bb_word(*;$)
{
my ($handle, $desc) = @_;
return graph_read($handle, 4, $desc);
}
#
# read_bb_value(handle[, description])
#
# Read a word in .bb format from handle and return the word and its integer
# value.
#
sub read_bb_value(*;$)
{
my ($handle, $desc) = @_;
my $word;
$word = read_bb_word($handle, $desc);
return undef if (!defined($word));
return ($word, unpack("V", $word));
}
#
# read_bb_string(handle, delimiter)
#
# Read and return a string in .bb format from handle up to the specified
# delimiter value.
#
sub read_bb_string(*$)
{
my ($handle, $delimiter) = @_;
my $word;
my $value;
my $string = "";
graph_expect("string");
do {
($word, $value) = read_bb_value($handle, "string or delimiter");
return undef if (!defined($value));
if ($value != $delimiter) {
$string .= $word;
}
} while ($value != $delimiter);
$string =~ s/\0//g;
return $string;
}
#
# read_bb(filename)
#
# Read the contents of the specified .bb file and return (instr, graph), where:
#
# instr : filename -> line data
# line data : [ line1, line2, ... ]
#
# graph : filename -> file_data
# file_data : function name -> line_data
# line_data : [ line1, line2, ... ]
#
# See the gcov info pages of gcc 2.95 for a description of the .bb file format.
#
sub read_bb($)
{
my ($bb_filename) = @_;
my $minus_one = 0x80000001;
my $minus_two = 0x80000002;
my $value;
my $filename;
my $function;
my $bb = {};
my $fileorder = {};
my $instr;
my $graph;
local *HANDLE;
open(HANDLE, "<", $bb_filename) or goto open_error;
binmode(HANDLE);
while (!eof(HANDLE)) {
$value = read_bb_value(*HANDLE, "data word");
goto incomplete if (!defined($value));
if ($value == $minus_one) {
# Source file name
graph_expect("filename");
$filename = read_bb_string(*HANDLE, $minus_one);
goto incomplete if (!defined($filename));
} elsif ($value == $minus_two) {
# Function name
graph_expect("function name");
$function = read_bb_string(*HANDLE, $minus_two);
goto incomplete if (!defined($function));
} elsif ($value > 0) {
# Line number
if (!defined($filename) || !defined($function)) {
warn("WARNING: unassigned line number ".
"$value\n");
next;
}
push(@{$bb->{$function}->{$filename}}, $value);
graph_add_order($fileorder, $function, $filename);
}
}
close(HANDLE);
($instr, $graph) = graph_from_bb($bb, $fileorder, $bb_filename);
graph_cleanup($graph);
return ($instr, $graph);
open_error:
graph_error($bb_filename, "could not open file");
return undef;
incomplete:
graph_error($bb_filename, "reached unexpected end of file");
return undef;
}
#
# read_bbg_word(handle[, description])
#
# Read and return a word in .bbg format.
#
sub read_bbg_word(*;$)
{
my ($handle, $desc) = @_;
return graph_read($handle, 4, $desc);
}
#
# read_bbg_value(handle[, description])
#
# Read a word in .bbg format from handle and return its integer value.
#
sub read_bbg_value(*;$)
{
my ($handle, $desc) = @_;
my $word;
$word = read_bbg_word($handle, $desc);
return undef if (!defined($word));
return unpack("N", $word);
}
#
# read_bbg_string(handle)
#
# Read and return a string in .bbg format.
#
sub read_bbg_string(*)
{
my ($handle, $desc) = @_;
my $length;
my $string;
graph_expect("string");
# Read string length
$length = read_bbg_value($handle, "string length");
return undef if (!defined($length));
if ($length == 0) {
return "";
}
# Read string
$string = graph_read($handle, $length, "string");
return undef if (!defined($string));
# Skip padding
graph_skip($handle, 4 - $length % 4, "string padding") or return undef;
return $string;
}
#
# read_bbg_lines_record(handle, bbg_filename, bb, fileorder, filename,
# function)
#
# Read a bbg format lines record from handle and add the relevant data to
# bb and fileorder. Return filename on success, undef on error.
#
sub read_bbg_lines_record(*$$$$$)
{
my ($handle, $bbg_filename, $bb, $fileorder, $filename, $function) = @_;
my $string;
my $lineno;
graph_expect("lines record");
# Skip basic block index
graph_skip($handle, 4, "basic block index") or return undef;
while (1) {
# Read line number
$lineno = read_bbg_value($handle, "line number");
return undef if (!defined($lineno));
if ($lineno == 0) {
# Got a marker for a new filename
graph_expect("filename");
$string = read_bbg_string($handle);
return undef if (!defined($string));
# Check for end of record
if ($string eq "") {
return $filename;
}
$filename = $string;
if (!exists($bb->{$function}->{$filename})) {
$bb->{$function}->{$filename} = [];
}
next;
}
# Got an actual line number
if (!defined($filename)) {
warn("WARNING: unassigned line number in ".
"$bbg_filename\n");
next;
}
push(@{$bb->{$function}->{$filename}}, $lineno);
graph_add_order($fileorder, $function, $filename);
}
}
#
# read_bbg(filename)
#
# Read the contents of the specified .bbg file and return the following mapping:
# graph: filename -> file_data
# file_data: function name -> line_data
# line_data: [ line1, line2, ... ]
#
# See the gcov-io.h file in the SLES 9 gcc 3.3.3 source code for a description
# of the .bbg format.
#
sub read_bbg($)
{
my ($bbg_filename) = @_;
my $file_magic = 0x67626267;
my $tag_function = 0x01000000;
my $tag_lines = 0x01450000;
my $word;
my $tag;
my $length;
my $function;
my $filename;
my $bb = {};
my $fileorder = {};
my $instr;
my $graph;
local *HANDLE;
open(HANDLE, "<", $bbg_filename) or goto open_error;
binmode(HANDLE);
# Read magic
$word = read_bbg_value(*HANDLE, "file magic");
goto incomplete if (!defined($word));
# Check magic
if ($word != $file_magic) {
goto magic_error;
}
# Skip version
graph_skip(*HANDLE, 4, "version") or goto incomplete;
while (!eof(HANDLE)) {
# Read record tag
$tag = read_bbg_value(*HANDLE, "record tag");
goto incomplete if (!defined($tag));
# Read record length
$length = read_bbg_value(*HANDLE, "record length");
goto incomplete if (!defined($tag));
if ($tag == $tag_function) {
graph_expect("function record");
# Read function name
graph_expect("function name");
$function = read_bbg_string(*HANDLE);
goto incomplete if (!defined($function));
$filename = undef;
# Skip function checksum
graph_skip(*HANDLE, 4, "function checksum")
or goto incomplete;
} elsif ($tag == $tag_lines) {
# Read lines record
$filename = read_bbg_lines_record(HANDLE, $bbg_filename,
$bb, $fileorder, $filename,
$function);
goto incomplete if (!defined($filename));
} else {
# Skip record contents
graph_skip(*HANDLE, $length, "unhandled record")
or goto incomplete;
}
}
close(HANDLE);
($instr, $graph) = graph_from_bb($bb, $fileorder, $bbg_filename);
graph_cleanup($graph);
return ($instr, $graph);
open_error:
graph_error($bbg_filename, "could not open file");
return undef;
incomplete:
graph_error($bbg_filename, "reached unexpected end of file");
return undef;
magic_error:
graph_error($bbg_filename, "found unrecognized bbg file magic");
return undef;
}
#
# read_gcno_word(handle[, description, peek])
#
# Read and return a word in .gcno format.
#
sub read_gcno_word(*;$$)
{
my ($handle, $desc, $peek) = @_;
return graph_read($handle, 4, $desc, $peek);
}
#
# read_gcno_value(handle, big_endian[, description, peek])
#
# Read a word in .gcno format from handle and return its integer value
# according to the specified endianness. If PEEK is non-zero, reset file
# position after read.
#
sub read_gcno_value(*$;$$)
{
my ($handle, $big_endian, $desc, $peek) = @_;
my $word;
my $pos;
$word = read_gcno_word($handle, $desc, $peek);
return undef if (!defined($word));
if ($big_endian) {
return unpack("N", $word);
} else {
return unpack("V", $word);
}
}
#
# read_gcno_string(handle, big_endian)
#
# Read and return a string in .gcno format.
#
sub read_gcno_string(*$)
{
my ($handle, $big_endian) = @_;
my $length;
my $string;
graph_expect("string");
# Read string length
$length = read_gcno_value($handle, $big_endian, "string length");
return undef if (!defined($length));
if ($length == 0) {
return "";
}
$length *= 4;
# Read string
$string = graph_read($handle, $length, "string and padding");
return undef if (!defined($string));
$string =~ s/\0//g;
return $string;
}
#
# read_gcno_lines_record(handle, gcno_filename, bb, fileorder, filename,
# function, big_endian)
#
# Read a gcno format lines record from handle and add the relevant data to
# bb and fileorder. Return filename on success, undef on error.
#
sub read_gcno_lines_record(*$$$$$$)
{
my ($handle, $gcno_filename, $bb, $fileorder, $filename, $function,
$big_endian) = @_;
my $string;
my $lineno;
graph_expect("lines record");
# Skip basic block index
graph_skip($handle, 4, "basic block index") or return undef;
while (1) {
# Read line number
$lineno = read_gcno_value($handle, $big_endian, "line number");
return undef if (!defined($lineno));
if ($lineno == 0) {
# Got a marker for a new filename
graph_expect("filename");
$string = read_gcno_string($handle, $big_endian);
return undef if (!defined($string));
# Check for end of record
if ($string eq "") {
return $filename;
}
$filename = $string;
if (!exists($bb->{$function}->{$filename})) {
$bb->{$function}->{$filename} = [];
}
next;
}
# Got an actual line number
if (!defined($filename)) {
warn("WARNING: unassigned line number in ".
"$gcno_filename\n");
next;
}
# Add to list
push(@{$bb->{$function}->{$filename}}, $lineno);
graph_add_order($fileorder, $function, $filename);
}
}
#
# determine_gcno_split_crc(handle, big_endian, rec_length, version)
#
# Determine if HANDLE refers to a .gcno file with a split checksum function
# record format. Return non-zero in case of split checksum format, zero
# otherwise, undef in case of read error.
#
sub determine_gcno_split_crc($$$$)
{
my ($handle, $big_endian, $rec_length, $version) = @_;
my $strlen;
my $overlong_string;
return 1 if ($version >= $GCOV_VERSION_4_7_0);
return 1 if (is_compat($COMPAT_MODE_SPLIT_CRC));
# Heuristic:
# Decide format based on contents of next word in record:
# - pre-gcc 4.7
# This is the function name length / 4 which should be
# less than the remaining record length
# - gcc 4.7
# This is a checksum, likely with high-order bits set,
# resulting in a large number
$strlen = read_gcno_value($handle, $big_endian, undef, 1);
return undef if (!defined($strlen));
$overlong_string = 1 if ($strlen * 4 >= $rec_length - 12);
if ($overlong_string) {
if (is_compat_auto($COMPAT_MODE_SPLIT_CRC)) {
info("Auto-detected compatibility mode for split ".
"checksum .gcno file format\n");
return 1;
} else {
# Sanity check
warn("Found overlong string in function record: ".
"try '--compat split_crc'\n");
}
}
return 0;
}
#
# read_gcno_function_record(handle, graph, big_endian, rec_length, version)
#
# Read a gcno format function record from handle and add the relevant data
# to graph. Return (filename, function) on success, undef on error.
#
sub read_gcno_function_record(*$$$$$)
{
my ($handle, $bb, $fileorder, $big_endian, $rec_length, $version) = @_;
my $filename;
my $function;
my $lineno;
my $lines;
graph_expect("function record");
# Skip ident and checksum
graph_skip($handle, 8, "function ident and checksum") or return undef;
# Determine if this is a function record with split checksums
if (!defined($gcno_split_crc)) {
$gcno_split_crc = determine_gcno_split_crc($handle, $big_endian,
$rec_length,
$version);
return undef if (!defined($gcno_split_crc));
}
# Skip cfg checksum word in case of split checksums
graph_skip($handle, 4, "function cfg checksum") if ($gcno_split_crc);
# Read function name
graph_expect("function name");
$function = read_gcno_string($handle, $big_endian);
return undef if (!defined($function));
# Read filename
graph_expect("filename");
$filename = read_gcno_string($handle, $big_endian);
return undef if (!defined($filename));
# Read first line number
$lineno = read_gcno_value($handle, $big_endian, "initial line number");
return undef if (!defined($lineno));
# Add to list
push(@{$bb->{$function}->{$filename}}, $lineno);
graph_add_order($fileorder, $function, $filename);
return ($filename, $function);
}
#
# map_gcno_version
#
# Map version number as found in .gcno files to the format used in geninfo.
#
sub map_gcno_version($)
{
my ($version) = @_;
my ($a, $b, $c);
my ($major, $minor);
$a = $version >> 24;
$b = $version >> 16 & 0xff;
$c = $version >> 8 & 0xff;
if ($a < ord('A')) {
$major = $a - ord('0');
$minor = ($b - ord('0')) * 10 + $c - ord('0');
} else {
$major = ($a - ord('A')) * 10 + $b - ord('0');
$minor = $c - ord('0');
}
return $major << 16 | $minor << 8;
}
#
# read_gcno(filename)
#
# Read the contents of the specified .gcno file and return the following
# mapping:
# graph: filename -> file_data
# file_data: function name -> line_data
# line_data: [ line1, line2, ... ]
#
# See the gcov-io.h file in the gcc 3.3 source code for a description of
# the .gcno format.
#
sub read_gcno($)
{
my ($gcno_filename) = @_;
my $file_magic = 0x67636e6f;
my $tag_function = 0x01000000;
my $tag_lines = 0x01450000;
my $big_endian;
my $word;
my $tag;
my $length;
my $filename;
my $function;
my $bb = {};
my $fileorder = {};
my $instr;
my $graph;
my $filelength;
my $version;
local *HANDLE;
open(HANDLE, "<", $gcno_filename) or goto open_error;
$filelength = (stat(HANDLE))[7];
binmode(HANDLE);
# Read magic
$word = read_gcno_word(*HANDLE, "file magic");
goto incomplete if (!defined($word));
# Determine file endianness
if (unpack("N", $word) == $file_magic) {
$big_endian = 1;
} elsif (unpack("V", $word) == $file_magic) {
$big_endian = 0;
} else {
goto magic_error;
}
# Read version
$version = read_gcno_value(*HANDLE, $big_endian, "compiler version");
$version = map_gcno_version($version);
debug(sprintf("found version 0x%08x\n", $version));
# Skip stamp
graph_skip(*HANDLE, 4, "file timestamp") or goto incomplete;
while (!eof(HANDLE)) {
my $next_pos;
my $curr_pos;
# Read record tag
$tag = read_gcno_value(*HANDLE, $big_endian, "record tag");
goto incomplete if (!defined($tag));
# Read record length
$length = read_gcno_value(*HANDLE, $big_endian,
"record length");
goto incomplete if (!defined($length));
# Convert length to bytes
$length *= 4;
# Calculate start of next record
$next_pos = tell(HANDLE);
goto tell_error if ($next_pos == -1);
$next_pos += $length;
# Catch garbage at the end of a gcno file
if ($next_pos > $filelength) {
debug("Overlong record: file_length=$filelength ".
"rec_length=$length\n");
warn("WARNING: $gcno_filename: Overlong record at end ".
"of file!\n");
last;
}
# Process record
if ($tag == $tag_function) {
($filename, $function) = read_gcno_function_record(
*HANDLE, $bb, $fileorder, $big_endian,
$length, $version);
goto incomplete if (!defined($function));
} elsif ($tag == $tag_lines) {
# Read lines record
$filename = read_gcno_lines_record(*HANDLE,
$gcno_filename, $bb, $fileorder,
$filename, $function,
$big_endian);
goto incomplete if (!defined($filename));
} else {
# Skip record contents
graph_skip(*HANDLE, $length, "unhandled record")
or goto incomplete;
}
# Ensure that we are at the start of the next record
$curr_pos = tell(HANDLE);
goto tell_error if ($curr_pos == -1);
next if ($curr_pos == $next_pos);
goto record_error if ($curr_pos > $next_pos);
graph_skip(*HANDLE, $next_pos - $curr_pos,
"unhandled record content")
or goto incomplete;
}
close(HANDLE);
($instr, $graph) = graph_from_bb($bb, $fileorder, $gcno_filename);
graph_cleanup($graph);
return ($instr, $graph);
open_error:
graph_error($gcno_filename, "could not open file");
return undef;
incomplete:
graph_error($gcno_filename, "reached unexpected end of file");
return undef;
magic_error:
graph_error($gcno_filename, "found unrecognized gcno file magic");
return undef;
tell_error:
graph_error($gcno_filename, "could not determine file position");
return undef;
record_error:
graph_error($gcno_filename, "found unrecognized record format");
return undef;
}
sub debug($)
{
my ($msg) = @_;
return if (!$debug);
print(STDERR "DEBUG: $msg");
}
#
# get_gcov_capabilities
#
# Determine the list of available gcov options.
#
sub get_gcov_capabilities()
{
my $help = `$gcov_tool --help`;
my %capabilities;
my %short_option_translations = (
'a' => 'all-blocks',
'b' => 'branch-probabilities',
'c' => 'branch-counts',
'f' => 'function-summaries',
'h' => 'help',
'l' => 'long-file-names',
'n' => 'no-output',
'o' => 'object-directory',
'p' => 'preserve-paths',
'u' => 'unconditional-branches',
'v' => 'version',
);
foreach (split(/\n/, $help)) {
my $capability;
if (/--(\S+)/) {
$capability = $1;
} else {
# If the line provides a short option, translate it.
next if (!/^\s*-(\S)\s/);
$capability = $short_option_translations{$1};
next if not defined($capability);
}
next if ($capability eq 'help');
next if ($capability eq 'version');
next if ($capability eq 'object-directory');
$capabilities{$capability} = 1;
debug("gcov has capability '$capability'\n");
}
return \%capabilities;
}
#
# parse_ignore_errors(@ignore_errors)
#
# Parse user input about which errors to ignore.
#
sub parse_ignore_errors(@)
{
my (@ignore_errors) = @_;
my @items;
my $item;
return if (!@ignore_errors);
foreach $item (@ignore_errors) {
$item =~ s/\s//g;
if ($item =~ /,/) {
# Split and add comma-separated parameters
push(@items, split(/,/, $item));
} else {
# Add single parameter
push(@items, $item);
}
}
foreach $item (@items) {
my $item_id = $ERROR_ID{lc($item)};
if (!defined($item_id)) {
die("ERROR: unknown argument for --ignore-errors: ".
"$item\n");
}
$ignore[$item_id] = 1;
}
}
#
# is_external(filename)
#
# Determine if a file is located outside of the specified data directories.
#
sub is_external($)
{
my ($filename) = @_;
my $dir;
foreach $dir (@internal_dirs) {
return 0 if ($filename =~ /^\Q$dir\/\E/);
}
return 1;
}
#
# compat_name(mode)
#
# Return the name of compatibility mode MODE.
#
sub compat_name($)
{
my ($mode) = @_;
my $name = $COMPAT_MODE_TO_NAME{$mode};
return $name if (defined($name));
return "<unknown>";
}
#
# parse_compat_modes(opt)
#
# Determine compatibility mode settings.
#
sub parse_compat_modes($)
{
my ($opt) = @_;
my @opt_list;
my %specified;
# Initialize with defaults
%compat_value = %COMPAT_MODE_DEFAULTS;
# Add old style specifications
if (defined($opt_compat_libtool)) {
$compat_value{$COMPAT_MODE_LIBTOOL} =
$opt_compat_libtool ? $COMPAT_VALUE_ON
: $COMPAT_VALUE_OFF;
}
# Parse settings
if (defined($opt)) {
@opt_list = split(/\s*,\s*/, $opt);
}
foreach my $directive (@opt_list) {
my ($mode, $value);
# Either
# mode=off|on|auto or
# mode (implies on)
if ($directive !~ /^(\w+)=(\w+)$/ &&
$directive !~ /^(\w+)$/) {
die("ERROR: Unknown compatibility mode specification: ".
"$directive!\n");
}
# Determine mode
$mode = $COMPAT_NAME_TO_MODE{lc($1)};
if (!defined($mode)) {
die("ERROR: Unknown compatibility mode '$1'!\n");
}
$specified{$mode} = 1;
# Determine value
if (defined($2)) {
$value = $COMPAT_NAME_TO_VALUE{lc($2)};
if (!defined($value)) {
die("ERROR: Unknown compatibility mode ".
"value '$2'!\n");
}
} else {
$value = $COMPAT_VALUE_ON;
}
$compat_value{$mode} = $value;
}
# Perform auto-detection
foreach my $mode (sort(keys(%compat_value))) {
my $value = $compat_value{$mode};
my $is_autodetect = "";
my $name = compat_name($mode);
if ($value == $COMPAT_VALUE_AUTO) {
my $autodetect = $COMPAT_MODE_AUTO{$mode};
if (!defined($autodetect)) {
die("ERROR: No auto-detection for ".
"mode '$name' available!\n");
}
if (ref($autodetect) eq "CODE") {
$value = &$autodetect();
$compat_value{$mode} = $value;
$is_autodetect = " (auto-detected)";
}
}
if ($specified{$mode}) {
if ($value == $COMPAT_VALUE_ON) {
info("Enabling compatibility mode ".
"'$name'$is_autodetect\n");
} elsif ($value == $COMPAT_VALUE_OFF) {
info("Disabling compatibility mode ".
"'$name'$is_autodetect\n");
} else {
info("Using delayed auto-detection for ".
"compatibility mode ".
"'$name'\n");
}
}
}
}
sub compat_hammer_autodetect()
{
if ($gcov_version_string =~ /suse/i && $gcov_version == 0x30303 ||
$gcov_version_string =~ /mandrake/i && $gcov_version == 0x30302)
{
info("Auto-detected compatibility mode for GCC 3.3 (hammer)\n");
return $COMPAT_VALUE_ON;
}
return $COMPAT_VALUE_OFF;
}
#
# is_compat(mode)
#
# Return non-zero if compatibility mode MODE is enabled.
#
sub is_compat($)
{
my ($mode) = @_;
return 1 if ($compat_value{$mode} == $COMPAT_VALUE_ON);
return 0;
}
#
# is_compat_auto(mode)
#
# Return non-zero if compatibility mode MODE is set to auto-detect.
#
sub is_compat_auto($)
{
my ($mode) = @_;
return 1 if ($compat_value{$mode} == $COMPAT_VALUE_AUTO);
return 0;
}
#!/usr/bin/perl -w
#
# Copyright (c) International Business Machines Corp., 2002
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# genpng
#
# This script creates an overview PNG image of a source code file by
# representing each source code character by a single pixel.
#
# Note that the Perl module GD.pm is required for this script to work.
# It may be obtained from http://www.cpan.org
#
# History:
# 2002-08-26: created by Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
#
use strict;
use File::Basename;
use Getopt::Long;
use Cwd qw/abs_path/;
# Constants
our $tool_dir = abs_path(dirname($0));
our $lcov_version = 'LCOV version '.`$tool_dir/get_version.sh --full`;
our $lcov_url = "http://ltp.sourceforge.net/coverage/lcov.php";
our $tool_name = basename($0);
# Prototypes
sub gen_png($$$@);
sub check_and_load_module($);
sub genpng_print_usage(*);
sub genpng_process_file($$$$);
sub genpng_warn_handler($);
sub genpng_die_handler($);
#
# Code entry point
#
# Check whether required module GD.pm is installed
if (check_and_load_module("GD"))
{
# Note: cannot use die() to print this message because inserting this
# code into another script via do() would not fail as required!
print(STDERR <<END_OF_TEXT)
ERROR: required module GD.pm not found on this system (see www.cpan.org).
END_OF_TEXT
;
exit(2);
}
# Check whether we're called from the command line or from another script
if (!caller)
{
my $filename;
my $tab_size = 4;
my $width = 80;
my $out_filename;
my $help;
my $version;
$SIG{__WARN__} = \&genpng_warn_handler;
$SIG{__DIE__} = \&genpng_die_handler;
# Parse command line options
if (!GetOptions("tab-size=i" => \$tab_size,
"width=i" => \$width,
"output-filename=s" => \$out_filename,
"help" => \$help,
"version" => \$version))
{
print(STDERR "Use $tool_name --help to get usage ".
"information\n");
exit(1);
}
$filename = $ARGV[0];
# Check for help flag
if ($help)
{
genpng_print_usage(*STDOUT);
exit(0);
}
# Check for version flag
if ($version)
{
print("$tool_name: $lcov_version\n");
exit(0);
}
# Check options
if (!$filename)
{
die("No filename specified\n");
}
# Check for output filename
if (!$out_filename)
{
$out_filename = "$filename.png";
}
genpng_process_file($filename, $out_filename, $width, $tab_size);
exit(0);
}
#
# genpng_print_usage(handle)
#
# Write out command line usage information to given filehandle.
#
sub genpng_print_usage(*)
{
local *HANDLE = $_[0];
print(HANDLE <<END_OF_USAGE)
Usage: $tool_name [OPTIONS] SOURCEFILE
Create an overview image for a given source code file of either plain text
or .gcov file format.
-h, --help Print this help, then exit
-v, --version Print version number, then exit
-t, --tab-size TABSIZE Use TABSIZE spaces in place of tab
-w, --width WIDTH Set width of output image to WIDTH pixel
-o, --output-filename FILENAME Write image to FILENAME
For more information see: $lcov_url
END_OF_USAGE
;
}
#
# check_and_load_module(module_name)
#
# Check whether a module by the given name is installed on this system
# and make it known to the interpreter if available. Return undefined if it
# is installed, an error message otherwise.
#
sub check_and_load_module($)
{
eval("use $_[0];");
return $@;
}
#
# genpng_process_file(filename, out_filename, width, tab_size)
#
sub genpng_process_file($$$$)
{
my $filename = $_[0];
my $out_filename = $_[1];
my $width = $_[2];
my $tab_size = $_[3];
local *HANDLE;
my @source;
open(HANDLE, "<", $filename)
or die("ERROR: cannot open $filename!\n");
# Check for .gcov filename extension
if ($filename =~ /^(.*).gcov$/)
{
# Assume gcov text format
while (<HANDLE>)
{
if (/^\t\t(.*)$/)
{
# Uninstrumented line
push(@source, ":$1");
}
elsif (/^ ###### (.*)$/)
{
# Line with zero execution count
push(@source, "0:$1");
}
elsif (/^( *)(\d*) (.*)$/)
{
# Line with positive execution count
push(@source, "$2:$3");
}
}
}
else
{
# Plain text file
while (<HANDLE>) { push(@source, ":$_"); }
}
close(HANDLE);
gen_png($out_filename, $width, $tab_size, @source);
}
#
# gen_png(filename, width, tab_size, source)
#
# Write an overview PNG file to FILENAME. Source code is defined by SOURCE
# which is a list of lines <count>:<source code> per source code line.
# The output image will be made up of one pixel per character of source,
# coloring will be done according to execution counts. WIDTH defines the
# image width. TAB_SIZE specifies the number of spaces to use as replacement
# string for tabulator signs in source code text.
#
# Die on error.
#
sub gen_png($$$@)
{
my $filename = shift(@_); # Filename for PNG file
my $overview_width = shift(@_); # Imagewidth for image
my $tab_size = shift(@_); # Replacement string for tab signs
my @source = @_; # Source code as passed via argument 2
my $height; # Height as define by source size
my $overview; # Source code overview image data
my $col_plain_back; # Color for overview background
my $col_plain_text; # Color for uninstrumented text
my $col_cov_back; # Color for background of covered lines
my $col_cov_text; # Color for text of covered lines
my $col_nocov_back; # Color for background of lines which
# were not covered (count == 0)
my $col_nocov_text; # Color for test of lines which were not
# covered (count == 0)
my $col_hi_back; # Color for background of highlighted lines
my $col_hi_text; # Color for text of highlighted lines
my $line; # Current line during iteration
my $row = 0; # Current row number during iteration
my $column; # Current column number during iteration
my $color_text; # Current text color during iteration
my $color_back; # Current background color during iteration
my $last_count; # Count of last processed line
my $count; # Count of current line
my $source; # Source code of current line
my $replacement; # Replacement string for tabulator chars
local *PNG_HANDLE; # Handle for output PNG file
# Handle empty source files
if (!@source) {
@source = ( "" );
}
$height = scalar(@source);
# Create image
$overview = new GD::Image($overview_width, $height)
or die("ERROR: cannot allocate overview image!\n");
# Define colors
$col_plain_back = $overview->colorAllocate(0xff, 0xff, 0xff);
$col_plain_text = $overview->colorAllocate(0xaa, 0xaa, 0xaa);
$col_cov_back = $overview->colorAllocate(0xaa, 0xa7, 0xef);
$col_cov_text = $overview->colorAllocate(0x5d, 0x5d, 0xea);
$col_nocov_back = $overview->colorAllocate(0xff, 0x00, 0x00);
$col_nocov_text = $overview->colorAllocate(0xaa, 0x00, 0x00);
$col_hi_back = $overview->colorAllocate(0x00, 0xff, 0x00);
$col_hi_text = $overview->colorAllocate(0x00, 0xaa, 0x00);
# Visualize each line
foreach $line (@source)
{
# Replace tabs with spaces to keep consistent with source
# code view
while ($line =~ /^([^\t]*)(\t)/)
{
$replacement = " "x($tab_size - ((length($1) - 1) %
$tab_size));
$line =~ s/^([^\t]*)(\t)/$1$replacement/;
}
# Skip lines which do not follow the <count>:<line>
# specification, otherwise $1 = count, $2 = source code
if (!($line =~ /(\*?)(\d*):(.*)$/)) { next; }
$count = $2;
$source = $3;
# Decide which color pair to use
# If this line was not instrumented but the one before was,
# take the color of that line to widen color areas in
# resulting image
if (($count eq "") && defined($last_count) &&
($last_count ne ""))
{
$count = $last_count;
}
if ($count eq "")
{
# Line was not instrumented
$color_text = $col_plain_text;
$color_back = $col_plain_back;
}
elsif ($count == 0)
{
# Line was instrumented but not executed
$color_text = $col_nocov_text;
$color_back = $col_nocov_back;
}
elsif ($1 eq "*")
{
# Line was highlighted
$color_text = $col_hi_text;
$color_back = $col_hi_back;
}
else
{
# Line was instrumented and executed
$color_text = $col_cov_text;
$color_back = $col_cov_back;
}
# Write one pixel for each source character
$column = 0;
foreach (split("", $source))
{
# Check for width
if ($column >= $overview_width) { last; }
if ($_ eq " ")
{
# Space
$overview->setPixel($column++, $row,
$color_back);
}
else
{
# Text
$overview->setPixel($column++, $row,
$color_text);
}
}
# Fill rest of line
while ($column < $overview_width)
{
$overview->setPixel($column++, $row, $color_back);
}
$last_count = $2;
$row++;
}
# Write PNG file
open (PNG_HANDLE, ">", $filename)
or die("ERROR: cannot write png file $filename!\n");
binmode(*PNG_HANDLE);
print(PNG_HANDLE $overview->png());
close(PNG_HANDLE);
}
sub genpng_warn_handler($)
{
my ($msg) = @_;
warn("$tool_name: $msg");
}
sub genpng_die_handler($)
{
my ($msg) = @_;
die("$tool_name: $msg");
}
#!/bin/bash
#
# Usage: get_changes.sh
#
# Print lcov change log information as provided by Git
TOOLDIR=$(cd $(dirname $0) ; pwd)
cd $TOOLDIR
if ! git --no-pager log --no-merges --decorate=short --color=never 2>/dev/null ; then
cat "$TOOLDIR/../CHANGES" 2>/dev/null
fi
#!/bin/bash
#
# Usage: get_version.sh --version|--release|--full
#
# Print lcov version or release information as provided by Git, .version
# or a fallback.
TOOLDIR=$(cd $(dirname $0) ; pwd)
GITVER=$(cd $TOOLDIR ; git describe --tags 2>/dev/null)
if [ -z "$GITVER" ] ; then
# Get version information from file
if [ -e "$TOOLDIR/../.version" ] ; then
source "$TOOLDIR/../.version"
fi
else
# Get version information from git
FULL=${GITVER:1}
VERSION=${GITVER%%-*}
VERSION=${VERSION:1}
if [ "${GITVER#*-}" != "$GITVER" ] ; then
RELEASE=${GITVER#*-}
RELEASE=${RELEASE/-/.}
fi
fi
# Fallback
[ -z "$VERSION" ] && VERSION="1.0"
[ -z "$RELEASE" ] && RELEASE="1"
[ -z "$FULL" ] && FULL="$VERSION"
[ "$1" == "--version" ] && echo -n "$VERSION"
[ "$1" == "--release" ] && echo -n "$RELEASE"
[ "$1" == "--full" ] && echo -n "$FULL"
#!/bin/bash
#
# install.sh [--uninstall] sourcefile targetfile [install options]
#
# Check for uninstall option
if test "x$1" == "x--uninstall" ; then
UNINSTALL=true
SOURCE=$2
TARGET=$3
shift 3
else
UNINSTALL=false
SOURCE=$1
TARGET=$2
shift 2
fi
# Check usage
if test -z "$SOURCE" || test -z "$TARGET" ; then
echo Usage: install.sh [--uninstall] source target [install options] >&2
exit 1
fi
#
# do_install(SOURCE_FILE, TARGET_FILE)
#
do_install()
{
local SOURCE=$1
local TARGET=$2
local PARAMS=$3
install -d $(dirname $TARGET)
install -p $PARAMS $SOURCE $TARGET
}
#
# do_uninstall(SOURCE_FILE, TARGET_FILE)
#
do_uninstall()
{
local SOURCE=$1
local TARGET=$2
# Does target exist?
if test -r $TARGET ; then
# Is target of the same version as this package?
if diff -I '^our \$lcov_version' -I '^\.TH ' $SOURCE $TARGET >/dev/null; then
rm -f $TARGET
else
echo WARNING: Skipping uninstall for $TARGET - versions differ! >&2
fi
else
echo WARNING: Skipping uninstall for $TARGET - not installed! >&2
fi
}
# Call sub routine
if $UNINSTALL ; then
do_uninstall $SOURCE $TARGET
else
do_install $SOURCE $TARGET "$*"
fi
exit 0
This source diff could not be displayed because it is too large. You can view the blob instead.
#!/usr/bin/perl -w
use strict;
use File::Basename;
sub update_man_page($);
sub update_bin_tool($);
sub update_txt_file($);
sub update_spec_file($);
sub write_version_file($);
sub get_file_info($);
our $directory = $ARGV[0];
our $version = $ARGV[1];
our $release = $ARGV[2];
our $full = $ARGV[3];
our @man_pages = ("man/gendesc.1", "man/genhtml.1", "man/geninfo.1",
"man/genpng.1", "man/lcov.1", "man/lcovrc.5");
our @bin_tools = ("bin/gendesc", "bin/genhtml", "bin/geninfo",
"bin/genpng", "bin/lcov");
our @txt_files = ("README");
our @spec_files = ("rpm/lcov.spec");
if (!defined($directory) || !defined($version) || !defined($release)) {
die("Usage: $0 DIRECTORY|FILE VERSION RELEASE FULL_VERSION\n");
}
# Determine mode of operation
if (-f $directory) {
my $file = $directory;
my $base = basename($file);
if (grep(/^$base$/, map({ basename($_) } @man_pages))) {
print("Updating man page $file\n");
update_man_page($file);
} elsif (grep(/^$base$/, map({ basename($_) } @bin_tools))) {
print("Updating bin tool $file\n");
update_bin_tool($file);
} elsif (grep(/^$base$/, map({ basename($_) } @txt_files))) {
print("Updating text file $file\n");
update_txt_file($file);
} elsif (grep(/^$base$/, map({ basename($_) } @spec_files))) {
print("Updating spec file $file\n");
update_spec_file($file);
} elsif ($base eq ".version") {
print("Updating version file $file\n");
write_version_file($file);
} else {
print("WARNING: Skipping unknown file $file\n");
}
print("Done.\n");
exit(0);
}
foreach (@man_pages) {
print("Updating man page $_\n");
update_man_page($directory."/".$_);
}
foreach (@bin_tools) {
print("Updating bin tool $_\n");
update_bin_tool($directory."/".$_);
}
foreach (@txt_files) {
print("Updating text file $_\n");
update_txt_file($directory."/".$_);
}
foreach (@spec_files) {
print("Updating spec file $_\n");
update_spec_file($directory."/".$_);
}
print("Updating version file $directory/.version\n");
write_version_file("$directory/.version");
print("Done.\n");
sub get_file_info($)
{
my ($filename) = @_;
my ($sec, $min, $hour, $year, $month, $day);
my @stat;
my $gittime;
return (0, 0, 0) if (!-e $filename);
@stat = stat($filename);
($sec, $min, $hour, $day, $month, $year) = gmtime($stat[9]);
$year += 1900;
$month += 1;
return (sprintf("%04d-%02d-%02d", $year, $month, $day),
sprintf("%04d%02d%02d%02d%02d.%02d", $year, $month, $day,
$hour, $min, $sec),
sprintf("%o", $stat[2] & 07777));
}
sub update_man_page($)
{
my ($filename) = @_;
my @date = get_file_info($filename);
my $date_string = $date[0];
local *IN;
local *OUT;
$date_string =~ s/-/\\-/g;
open(IN, "<$filename") || die ("Error: cannot open $filename\n");
open(OUT, ">$filename.new") ||
die("Error: cannot create $filename.new\n");
while (<IN>) {
s/\"LCOV\s+\d+\.\d+\"/\"LCOV $version\"/g;
s/\d\d\d\d\\\-\d\d\\\-\d\d/$date_string/g;
print(OUT $_);
}
close(OUT);
close(IN);
chmod(oct($date[2]), "$filename.new");
system("mv", "-f", "$filename.new", "$filename");
system("touch", "$filename", "-t", $date[1]);
}
sub update_bin_tool($)
{
my ($filename) = @_;
my @date = get_file_info($filename);
local *IN;
local *OUT;
open(IN, "<$filename") || die ("Error: cannot open $filename\n");
open(OUT, ">$filename.new") ||
die("Error: cannot create $filename.new\n");
while (<IN>) {
s/^(our\s+\$lcov_version\s*=).*$/$1 "LCOV version $full";/g;
print(OUT $_);
}
close(OUT);
close(IN);
chmod(oct($date[2]), "$filename.new");
system("mv", "-f", "$filename.new", "$filename");
system("touch", "$filename", "-t", $date[1]);
}
sub update_txt_file($)
{
my ($filename) = @_;
my @date = get_file_info($filename);
local *IN;
local *OUT;
open(IN, "<$filename") || die ("Error: cannot open $filename\n");
open(OUT, ">$filename.new") ||
die("Error: cannot create $filename.new\n");
while (<IN>) {
s/(Last\s+changes:\s+)\d\d\d\d-\d\d-\d\d/$1$date[0]/g;
print(OUT $_);
}
close(OUT);
close(IN);
chmod(oct($date[2]), "$filename.new");
system("mv", "-f", "$filename.new", "$filename");
system("touch", "$filename", "-t", $date[1]);
}
sub update_spec_file($)
{
my ($filename) = @_;
my @date = get_file_info($filename);
local *IN;
local *OUT;
open(IN, "<$filename") || die ("Error: cannot open $filename\n");
open(OUT, ">$filename.new") ||
die("Error: cannot create $filename.new\n");
while (<IN>) {
s/^(Version:\s*)\d+\.\d+.*$/$1$version/;
s/^(Release:\s*).*$/$1$release/;
print(OUT $_);
}
close(OUT);
close(IN);
system("mv", "-f", "$filename.new", "$filename");
system("touch", "$filename", "-t", $date[1]);
}
sub write_version_file($)
{
my ($filename) = @_;
my $fd;
open($fd, ">", $filename) or die("Error: cannot write $filename: $!\n");
print($fd "VERSION=$version\n");
print($fd "RELEASE=$release\n");
print($fd "FULL=$full\n");
close($fd);
}
#
# Makefile for the LCOV example program.
#
# Make targets:
# - example: compile the example program
# - output: run test cases on example program and create HTML output
# - clean: clean up directory
#
CC := gcc
CFLAGS := -Wall -I. -fprofile-arcs -ftest-coverage
LCOV := ../bin/lcov
GENHTML := ../bin/genhtml
GENDESC := ../bin/gendesc
GENPNG := ../bin/genpng
# Depending on the presence of the GD.pm perl module, we can use the
# special option '--frames' for genhtml
USE_GENPNG := $(shell $(GENPNG) --help >/dev/null 2>/dev/null; echo $$?)
ifeq ($(USE_GENPNG),0)
FRAMES := --frames
else
FRAMES :=
endif
.PHONY: clean output test_noargs test_2_to_2000 test_overflow
all: output
example: example.o iterate.o gauss.o
$(CC) example.o iterate.o gauss.o -o example -lgcov
example.o: example.c iterate.h gauss.h
$(CC) $(CFLAGS) -c example.c -o example.o
iterate.o: methods/iterate.c iterate.h
$(CC) $(CFLAGS) -c methods/iterate.c -o iterate.o
gauss.o: methods/gauss.c gauss.h
$(CC) $(CFLAGS) -c methods/gauss.c -o gauss.o
output: example descriptions test_noargs test_2_to_2000 test_overflow
@echo
@echo '*'
@echo '* Generating HTML output'
@echo '*'
@echo
$(GENHTML) trace_noargs.info trace_args.info trace_overflow.info \
--output-directory output --title "Basic example" \
--show-details --description-file descriptions $(FRAMES) \
--legend
@echo
@echo '*'
@echo '* See '`pwd`/output/index.html
@echo '*'
@echo
descriptions: descriptions.txt
$(GENDESC) descriptions.txt -o descriptions
all_tests: example test_noargs test_2_to_2000 test_overflow
test_noargs:
@echo
@echo '*'
@echo '* Test case 1: running ./example without parameters'
@echo '*'
@echo
$(LCOV) --zerocounters --directory .
./example
$(LCOV) --capture --directory . --output-file trace_noargs.info --test-name test_noargs --no-external
test_2_to_2000:
@echo
@echo '*'
@echo '* Test case 2: running ./example 2 2000'
@echo '*'
@echo
$(LCOV) --zerocounters --directory .
./example 2 2000
$(LCOV) --capture --directory . --output-file trace_args.info --test-name test_2_to_2000 --no-external
test_overflow:
@echo
@echo '*'
@echo '* Test case 3: running ./example 0 100000 (causes an overflow)'
@echo '*'
@echo
$(LCOV) --zerocounters --directory .
./example 0 100000 || true
$(LCOV) --capture --directory . --output-file trace_overflow.info --test-name "test_overflow" --no-external
clean:
rm -rf *.o *.bb *.bbg *.da *.gcno *.gcda *.info output example \
descriptions
To get an example of how the LCOV generated HTML output looks like,
type 'make output' and point a web browser to the resulting file
output/index.html
test_noargs
Example program is called without arguments so that default range
[0..9] is used.
test_2_to_2000
Example program is called with "2" and "2000" as arguments.
test_overflow
Example program is called with "0" and "100000" as arguments. The
resulting sum is too large to be stored as an int variable.
/*
* example.c
*
* Calculate the sum of a given range of integer numbers. The range is
* specified by providing two integer numbers as command line argument.
* If no arguments are specified, assume the predefined range [0..9].
* Abort with an error message if the resulting number is too big to be
* stored as int variable.
*
* This program example is similar to the one found in the GCOV documentation.
* It is used to demonstrate the HTML output generated by LCOV.
*
* The program is split into 3 modules to better demonstrate the 'directory
* overview' function. There are also a lot of bloated comments inserted to
* artificially increase the source code size so that the 'source code
* overview' function makes at least a minimum of sense.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "iterate.h"
#include "gauss.h"
static int start = 0;
static int end = 9;
int main (int argc, char* argv[])
{
int total1, total2;
/* Accept a pair of numbers as command line arguments. */
if (argc == 3)
{
start = atoi(argv[1]);
end = atoi(argv[2]);
}
/* Use both methods to calculate the result. */
total1 = iterate_get_sum (start, end);
total2 = gauss_get_sum (start, end);
/* Make sure both results are the same. */
if (total1 != total2)
{
printf ("Failure (%d != %d)!\n", total1, total2);
}
else
{
printf ("Success, sum[%d..%d] = %d\n", start, end, total1);
}
return 0;
}
#ifndef GAUSS_H
#define GAUSS_H GAUSS_h
extern int gauss_get_sum (int min, int max);
#endif /* GAUSS_H */
#ifndef ITERATE_H
#define ITERATE_H ITERATE_H
extern int iterate_get_sum (int min, int max);
#endif /* ITERATE_H */
/*
* methods/gauss.c
*
* Calculate the sum of a given range of integer numbers.
*
* Somewhat of a more subtle way of calculation - and it even has a story
* behind it:
*
* Supposedly during math classes in elementary school, the teacher of
* young mathematician Gauss gave the class an assignment to calculate the
* sum of all natural numbers between 1 and 100, hoping that this task would
* keep the kids occupied for some time. The story goes that Gauss had the
* result ready after only a few minutes. What he had written on his black
* board was something like this:
*
* 1 + 100 = 101
* 2 + 99 = 101
* 3 + 98 = 101
* .
* .
* 100 + 1 = 101
*
* s = (1/2) * 100 * 101 = 5050
*
* A more general form of this formula would be
*
* s = (1/2) * (max + min) * (max - min + 1)
*
* which is used in the piece of code below to implement the requested
* function in constant time, i.e. without dependencies on the size of the
* input parameters.
*
*/
#include "gauss.h"
int gauss_get_sum (int min, int max)
{
/* This algorithm doesn't work well with invalid range specifications
so we're intercepting them here. */
if (max < min)
{
return 0;
}
return (int) ((max + min) * (double) (max - min + 1) / 2);
}
/*
* methods/iterate.c
*
* Calculate the sum of a given range of integer numbers.
*
* This particular method of implementation works by way of brute force,
* i.e. it iterates over the entire range while adding the numbers to finally
* get the total sum. As a positive side effect, we're able to easily detect
* overflows, i.e. situations in which the sum would exceed the capacity
* of an integer variable.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include "iterate.h"
int iterate_get_sum (int min, int max)
{
int i, total;
total = 0;
/* This is where we loop over each number in the range, including
both the minimum and the maximum number. */
for (i = min; i <= max; i++)
{
/* We can detect an overflow by checking whether the new
sum would become negative. */
if (total + i < total)
{
printf ("Error: sum too large!\n");
exit (1);
}
/* Everything seems to fit into an int, so continue adding. */
total += i;
}
return total;
}
#
# /etc/lcovrc - system-wide defaults for LCOV
#
# To change settings for a single user, place a customized copy of this file
# at location ~/.lcovrc
#
# Specify an external style sheet file (same as --css-file option of genhtml)
#genhtml_css_file = gcov.css
# Specify coverage rate limits (in %) for classifying file entries
# HI: hi_limit <= rate <= 100 graph color: green
# MED: med_limit <= rate < hi_limit graph color: orange
# LO: 0 <= rate < med_limit graph color: red
genhtml_hi_limit = 90
genhtml_med_limit = 75
# Width of line coverage field in source code view
genhtml_line_field_width = 12
# Width of branch coverage field in source code view
genhtml_branch_field_width = 16
# Width of overview image (used by --frames option of genhtml)
genhtml_overview_width = 80
# Resolution of overview navigation: this number specifies the maximum
# difference in lines between the position a user selected from the overview
# and the position the source code window is scrolled to (used by --frames
# option of genhtml)
genhtml_nav_resolution = 4
# Clicking a line in the overview image should show the source code view at
# a position a bit further up so that the requested line is not the first
# line in the window. This number specifies that offset in lines (used by
# --frames option of genhtml)
genhtml_nav_offset = 10
# Do not remove unused test descriptions if non-zero (same as
# --keep-descriptions option of genhtml)
genhtml_keep_descriptions = 0
# Do not remove prefix from directory names if non-zero (same as --no-prefix
# option of genhtml)
genhtml_no_prefix = 0
# Do not create source code view if non-zero (same as --no-source option of
# genhtml)
genhtml_no_source = 0
# Replace tabs with number of spaces in source view (same as --num-spaces
# option of genhtml)
genhtml_num_spaces = 8
# Highlight lines with converted-only data if non-zero (same as --highlight
# option of genhtml)
genhtml_highlight = 0
# Include color legend in HTML output if non-zero (same as --legend option of
# genhtml)
genhtml_legend = 0
# Use FILE as HTML prolog for generated pages (same as --html-prolog option of
# genhtml)
#genhtml_html_prolog = FILE
# Use FILE as HTML epilog for generated pages (same as --html-epilog option of
# genhtml)
#genhtml_html_epilog = FILE
# Use custom filename extension for pages (same as --html-extension option of
# genhtml)
#genhtml_html_extension = html
# Compress all generated html files with gzip.
#genhtml_html_gzip = 1
# Include sorted overview pages (can be disabled by the --no-sort option of
# genhtml)
genhtml_sort = 1
# Include function coverage data display (can be disabled by the
# --no-func-coverage option of genhtml)
#genhtml_function_coverage = 1
# Include branch coverage data display (can be disabled by the
# --no-branch-coverage option of genhtml)
#genhtml_branch_coverage = 1
# Specify the character set of all generated HTML pages
genhtml_charset=UTF-8
# Allow HTML markup in test case description text if non-zero
genhtml_desc_html=0
# Specify the precision for coverage rates
#genhtml_precision=1
# Demangle C++ symbols
#genhtml_demangle_cpp=1
# Location of the gcov tool (same as --gcov-info option of geninfo)
#geninfo_gcov_tool = gcov
# Adjust test names to include operating system information if non-zero
#geninfo_adjust_testname = 0
# Calculate checksum for each source code line if non-zero (same as --checksum
# option of geninfo if non-zero, same as --no-checksum if zero)
#geninfo_checksum = 1
# Specify whether to capture coverage data for external source files (can
# be overridden by the --external and --no-external options of geninfo/lcov)
#geninfo_external = 1
# Enable libtool compatibility mode if non-zero (same as --compat-libtool option
# of geninfo if non-zero, same as --no-compat-libtool if zero)
#geninfo_compat_libtool = 0
# Use gcov's --all-blocks option if non-zero
#geninfo_gcov_all_blocks = 1
# Specify compatiblity modes (same as --compat option of geninfo).
#geninfo_compat = libtool=on, hammer=auto, split_crc=auto
# Adjust path to source files by removing or changing path components that
# match the specified pattern (Perl regular expression format)
#geninfo_adjust_src_path = /tmp/build => /usr/src
# Specify if geninfo should try to automatically determine the base-directory
# when collecting coverage data.
geninfo_auto_base = 1
# Directory containing gcov kernel files
# lcov_gcov_dir = /proc/gcov
# Location of the insmod tool
lcov_insmod_tool = /sbin/insmod
# Location of the modprobe tool
lcov_modprobe_tool = /sbin/modprobe
# Location of the rmmod tool
lcov_rmmod_tool = /sbin/rmmod
# Location for temporary directories
lcov_tmp_dir = /tmp
# Show full paths during list operation if non-zero (same as --list-full-path
# option of lcov)
lcov_list_full_path = 0
# Specify the maximum width for list output. This value is ignored when
# lcov_list_full_path is non-zero.
lcov_list_width = 80
# Specify the maximum percentage of file names which may be truncated when
# choosing a directory prefix in list output. This value is ignored when
# lcov_list_full_path is non-zero.
lcov_list_truncate_max = 20
# Specify if function coverage data should be collected and processed.
lcov_function_coverage = 1
# Specify if branch coverage data should be collected and processed.
lcov_branch_coverage = 0
.TH gendesc 1 "LCOV 1.13" 2015\-10\-05 "User Manuals"
.SH NAME
gendesc \- Generate a test case description file
.SH SYNOPSIS
.B gendesc
.RB [ \-h | \-\-help ]
.RB [ \-v | \-\-version ]
.RS 8
.br
.RB [ \-o | \-\-output\-filename
.IR filename ]
.br
.I inputfile
.SH DESCRIPTION
Convert plain text test case descriptions into a format as understood by
.BR genhtml .
.I inputfile
needs to observe the following format:
For each test case:
.IP " \-"
one line containing the test case name beginning at the start of the line
.RE
.IP " \-"
one or more lines containing the test case description indented with at
least one whitespace character (tab or space)
.RE
.B Example input file:
test01
.RS
An example test case description.
.br
Description continued
.RE
test42
.RS
Supposedly the answer to most of your questions
.RE
Note: valid test names can consist of letters, decimal digits and the
underscore character ('_').
.SH OPTIONS
.B \-h
.br
.B \-\-help
.RS
Print a short help text, then exit.
.RE
.B \-v
.br
.B \-\-version
.RS
Print version number, then exit.
.RE
.BI "\-o " filename
.br
.BI "\-\-output\-filename " filename
.RS
Write description data to
.IR filename .
By default, output is written to STDOUT.
.RE
.SH AUTHOR
Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
.SH SEE ALSO
.BR lcov (1),
.BR genhtml (1),
.BR geninfo (1),
.BR genpng (1),
.BR gcov (1)
.TH genhtml 1 "LCOV 1.13" 2015\-10\-05 "User Manuals"
.SH NAME
genhtml \- Generate HTML view from LCOV coverage data files
.SH SYNOPSIS
.B genhtml
.RB [ \-h | \-\-help ]
.RB [ \-v | \-\-version ]
.RS 8
.br
.RB [ \-q | \-\-quiet ]
.RB [ \-s | \-\-show\-details ]
.RB [ \-f | \-\-frames ]
.br
.RB [ \-b | \-\-baseline\-file ]
.IR baseline\-file
.br
.RB [ \-o | \-\-output\-directory
.IR output\-directory ]
.br
.RB [ \-t | \-\-title
.IR title ]
.br
.RB [ \-d | \-\-description\-file
.IR description\-file ]
.br
.RB [ \-k | \-\-keep\-descriptions ]
.RB [ \-c | \-\-css\-file
.IR css\-file ]
.br
.RB [ \-p | \-\-prefix
.IR prefix ]
.RB [ \-\-no\-prefix ]
.br
.RB [ \-\-no\-source ]
.RB [ \-\-num\-spaces
.IR num ]
.RB [ \-\-highlight ]
.br
.RB [ \-\-legend ]
.RB [ \-\-html\-prolog
.IR prolog\-file ]
.br
.RB [ \-\-html\-epilog
.IR epilog\-file ]
.RB [ \-\-html\-extension
.IR extension ]
.br
.RB [ \-\-html\-gzip ]
.RB [ \-\-sort ]
.RB [ \-\-no\-sort ]
.br
.RB [ \-\-function\-coverage ]
.RB [ \-\-no\-function\-coverage ]
.br
.RB [ \-\-branch\-coverage ]
.RB [ \-\-no\-branch\-coverage ]
.br
.RB [ \-\-demangle\-cpp ]
.RB [ \-\-ignore\-errors
.IR errors ]
.br
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-rc
.IR keyword = value ]
.br
.RB [ \-\-precision
.IR num ]
.br
.IR tracefile(s)
.RE
.SH DESCRIPTION
Create an HTML view of coverage data found in
.IR tracefile .
Note that
.I tracefile
may also be a list of filenames.
HTML output files are created in the current working directory unless the
\-\-output\-directory option is used. If
.I tracefile
ends with ".gz", it is assumed to be GZIP\-compressed and the gunzip tool
will be used to decompress it transparently.
Note that all source code files have to be present and readable at the
exact file system location they were compiled.
Use option
.I \--css\-file
to modify layout and colors of the generated HTML output. Files are
marked in different colors depending on the associated coverage rate. By
default, the coverage limits for low, medium and high coverage are set to
0\-75%, 75\-90% and 90\-100% percent respectively. To change these
values, use configuration file options
.IR genhtml_hi_limit " and " genhtml_med_limit .
Also note that when displaying percentages, 0% and 100% are only printed when
the values are exactly 0% and 100% respectively. Other values which would
conventionally be rounded to 0% or 100% are instead printed as nearest
non-boundary value. This behavior is in accordance with that of the
.BR gcov (1)
tool.
.SH OPTIONS
.B \-h
.br
.B \-\-help
.RS
Print a short help text, then exit.
.RE
.B \-v
.br
.B \-\-version
.RS
Print version number, then exit.
.RE
.B \-q
.br
.B \-\-quiet
.RS
Do not print progress messages.
Suppresses all informational progress output. When this switch is enabled,
only error or warning messages are printed.
.RE
.B \-f
.br
.B \-\-frames
.RS
Use HTML frames for source code view.
If enabled, a frameset is created for each source code file, providing
an overview of the source code as a "clickable" image. Note that this
option will slow down output creation noticeably because each source
code character has to be inspected once. Note also that the GD.pm Perl
module has to be installed for this option to work (it may be obtained
from http://www.cpan.org).
.RE
.B \-s
.br
.B \-\-show\-details
.RS
Generate detailed directory view.
When this option is enabled,
.B genhtml
generates two versions of each
file view. One containing the standard information plus a link to a
"detailed" version. The latter additionally contains information about
which test case covered how many lines of each source file.
.RE
.BI "\-b " baseline\-file
.br
.BI "\-\-baseline\-file " baseline\-file
.RS
Use data in
.I baseline\-file
as coverage baseline.
The tracefile specified by
.I baseline\-file
is read and all counts found in the original
.I tracefile
are decremented by the corresponding counts in
.I baseline\-file
before creating any output.
Note that when a count for a particular line in
.I baseline\-file
is greater than the count in the
.IR tracefile ,
the result is zero.
.RE
.BI "\-o " output\-directory
.br
.BI "\-\-output\-directory " output\-directory
.RS
Create files in
.I output\-directory.
Use this option to tell
.B genhtml
to write the resulting files to a directory other than
the current one. If
.I output\-directory
does not exist, it will be created.
It is advisable to use this option since depending on the
project size, a lot of files and subdirectories may be created.
.RE
.BI "\-t " title
.br
.BI "\-\-title " title
.RS
Display
.I title
in header of all pages.
.I title
is written to the header portion of each generated HTML page to
identify the context in which a particular output
was created. By default this is the name of the tracefile.
.RE
.BI "\-d " description\-file
.br
.BI "\-\-description\-file " description\-file
.RS
Read test case descriptions from
.IR description\-file .
All test case descriptions found in
.I description\-file
and referenced in the input data file are read and written to an extra page
which is then incorporated into the HTML output.
The file format of
.IR "description\-file " is:
for each test case:
.RS
TN:<testname>
.br
TD:<test description>
.RE
Valid test case names can consist of letters, numbers and the underscore
character ('_').
.RE
.B \-k
.br
.B \-\-keep\-descriptions
.RS
Do not remove unused test descriptions.
Keep descriptions found in the description file even if the coverage data
indicates that the associated test case did not cover any lines of code.
This option can also be configured permanently using the configuration file
option
.IR genhtml_keep_descriptions .
.RE
.BI "\-c " css\-file
.br
.BI "\-\-css\-file " css\-file
.RS
Use external style sheet file
.IR css\-file .
Using this option, an extra .css file may be specified which will replace
the default one. This may be helpful if the default colors make your eyes want
to jump out of their sockets :)
This option can also be configured permanently using the configuration file
option
.IR genhtml_css_file .
.RE
.BI "\-p " prefix
.br
.BI "\-\-prefix " prefix
.RS
Remove
.I prefix
from all directory names.
Because lists containing long filenames are difficult to read, there is a
mechanism implemented that will automatically try to shorten all directory
names on the overview page beginning with a common prefix. By default,
this is done using an algorithm that tries to find the prefix which, when
applied, will minimize the resulting sum of characters of all directory
names.
Use this option to specify the prefix to be removed by yourself.
.RE
.B \-\-no\-prefix
.RS
Do not remove prefix from directory names.
This switch will completely disable the prefix mechanism described in the
previous section.
This option can also be configured permanently using the configuration file
option
.IR genhtml_no_prefix .
.RE
.B \-\-no\-source
.RS
Do not create source code view.
Use this switch if you don't want to get a source code view for each file.
This option can also be configured permanently using the configuration file
option
.IR genhtml_no_source .
.RE
.BI "\-\-num\-spaces " spaces
.RS
Replace tabs in source view with
.I num
spaces.
Default value is 8.
This option can also be configured permanently using the configuration file
option
.IR genhtml_num_spaces .
.RE
.B \-\-highlight
.RS
Highlight lines with converted\-only coverage data.
Use this option in conjunction with the \-\-diff option of
.B lcov
to highlight those lines which were only covered in data sets which were
converted from previous source code versions.
This option can also be configured permanently using the configuration file
option
.IR genhtml_highlight .
.RE
.B \-\-legend
.RS
Include color legend in HTML output.
Use this option to include a legend explaining the meaning of color coding
in the resulting HTML output.
This option can also be configured permanently using the configuration file
option
.IR genhtml_legend .
.RE
.BI "\-\-html\-prolog " prolog\-file
.RS
Read customized HTML prolog from
.IR prolog\-file .
Use this option to replace the default HTML prolog (the initial part of the
HTML source code leading up to and including the <body> tag) with the contents
of
.IR prolog\-file .
Within the prolog text, the following words will be replaced when a page is generated:
.B "@pagetitle@"
.br
The title of the page.
.B "@basedir@"
.br
A relative path leading to the base directory (e.g. for locating css\-files).
This option can also be configured permanently using the configuration file
option
.IR genhtml_html_prolog .
.RE
.BI "\-\-html\-epilog " epilog\-file
.RS
Read customized HTML epilog from
.IR epilog\-file .
Use this option to replace the default HTML epilog (the final part of the HTML
source including </body>) with the contents of
.IR epilog\-file .
Within the epilog text, the following words will be replaced when a page is generated:
.B "@basedir@"
.br
A relative path leading to the base directory (e.g. for locating css\-files).
This option can also be configured permanently using the configuration file
option
.IR genhtml_html_epilog .
.RE
.BI "\-\-html\-extension " extension
.RS
Use customized filename extension for generated HTML pages.
This option is useful in situations where different filename extensions
are required to render the resulting pages correctly (e.g. php). Note that
a '.' will be inserted between the filename and the extension specified by
this option.
This option can also be configured permanently using the configuration file
option
.IR genhtml_html_extension .
.RE
.B \-\-html\-gzip
.RS
Compress all generated html files with gzip and add a .htaccess file specifying
gzip\-encoding in the root output directory.
Use this option if you want to save space on your webserver. Requires a
webserver with .htaccess support and a browser with support for gzip
compressed html.
This option can also be configured permanently using the configuration file
option
.IR genhtml_html_gzip .
.RE
.B \-\-sort
.br
.B \-\-no\-sort
.RS
Specify whether to include sorted views of file and directory overviews.
Use \-\-sort to include sorted views or \-\-no\-sort to not include them.
Sorted views are
.B enabled
by default.
When sorted views are enabled, each overview page will contain links to
views of that page sorted by coverage rate.
This option can also be configured permanently using the configuration file
option
.IR genhtml_sort .
.RE
.B \-\-function\-coverage
.br
.B \-\-no\-function\-coverage
.RS
Specify whether to display function coverage summaries in HTML output.
Use \-\-function\-coverage to enable function coverage summaries or
\-\-no\-function\-coverage to disable it. Function coverage summaries are
.B enabled
by default
When function coverage summaries are enabled, each overview page will contain
the number of functions found and hit per file or directory, together with
the resulting coverage rate. In addition, each source code view will contain
a link to a page which lists all functions found in that file plus the
respective call count for those functions.
This option can also be configured permanently using the configuration file
option
.IR genhtml_function_coverage .
.RE
.B \-\-branch\-coverage
.br
.B \-\-no\-branch\-coverage
.RS
Specify whether to display branch coverage data in HTML output.
Use \-\-branch\-coverage to enable branch coverage display or
\-\-no\-branch\-coverage to disable it. Branch coverage data display is
.B enabled
by default
When branch coverage display is enabled, each overview page will contain
the number of branches found and hit per file or directory, together with
the resulting coverage rate. In addition, each source code view will contain
an extra column which lists all branches of a line with indications of
whether the branch was taken or not. Branches are shown in the following format:
' + ': Branch was taken at least once
.br
' - ': Branch was not taken
.br
' # ': The basic block containing the branch was never executed
.br
Note that it might not always be possible to relate branches to the
corresponding source code statements: during compilation, GCC might shuffle
branches around or eliminate some of them to generate better code.
This option can also be configured permanently using the configuration file
option
.IR genhtml_branch_coverage .
.RE
.B \-\-demangle\-cpp
.RS
Specify whether to demangle C++ function names.
Use this option if you want to convert C++ internal function names to
human readable format for display on the HTML function overview page.
This option requires that the c++filt tool is installed (see
.BR c++filt (1)).
.RE
.B \-\-ignore\-errors
.I errors
.br
.RS
Specify a list of errors after which to continue processing.
Use this option to specify a list of one or more classes of errors after which
geninfo should continue processing instead of aborting.
.I errors
can be a comma\-separated list of the following keywords:
.B source:
the source code file for a data set could not be found.
.RE
.B \-\-config\-file
.I config\-file
.br
.RS
Specify a configuration file to use.
When this option is specified, neither the system\-wide configuration file
/etc/lcovrc, nor the per\-user configuration file ~/.lcovrc is read.
This option may be useful when there is a need to run several
instances of
.B genhtml
with different configuration file options in parallel.
.RE
.B \-\-rc
.IR keyword = value
.br
.RS
Override a configuration directive.
Use this option to specify a
.IR keyword = value
statement which overrides the corresponding configuration statement in
the lcovrc configuration file. You can specify this option more than once
to override multiple configuration statements.
See
.BR lcovrc (5)
for a list of available keywords and their meaning.
.RE
.BI "\-\-precision " num
.RS
Show coverage rates with
.I num
number of digits after the decimal-point.
Default value is 1.
This option can also be configured permanently using the configuration file
option
.IR genhtml_precision .
.RE
.SH FILES
.I /etc/lcovrc
.RS
The system\-wide configuration file.
.RE
.I ~/.lcovrc
.RS
The per\-user configuration file.
.RE
.SH AUTHOR
Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
.SH SEE ALSO
.BR lcov (1),
.BR lcovrc (5),
.BR geninfo (1),
.BR genpng (1),
.BR gendesc (1),
.BR gcov (1)
.TH geninfo 1 "LCOV 1.13" 2015\-10\-05 "User Manuals"
.SH NAME
geninfo \- Generate tracefiles from .da files
.SH SYNOPSIS
.B geninfo
.RB [ \-h | \-\-help ]
.RB [ \-v | \-\-version ]
.RB [ \-q | \-\-quiet ]
.br
.RS 8
.RB [ \-i | \-\-initial ]
.RB [ \-t | \-\-test\-name
.IR test\-name ]
.br
.RB [ \-o | \-\-output\-filename
.IR filename ]
.RB [ \-f | \-\-follow ]
.br
.RB [ \-b | \-\-base\-directory
.IR directory ]
.br
.RB [ \-\-checksum ]
.RB [ \-\-no\-checksum ]
.br
.RB [ \-\-compat\-libtool ]
.RB [ \-\-no\-compat\-libtool ]
.br
.RB [ \-\-gcov\-tool
.IR tool ]
.RB [ \-\-ignore\-errors
.IR errors ]
.br
.RB [ \-\-no\-recursion ]
.I directory
.RB [ \-\-external ]
.RB [ \-\-no\-external ]
.br
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-no\-markers ]
.br
.RB [ \-\-derive\-func\-data ]
.RB [ \-\-compat
.IR mode =on|off|auto]
.br
.RB [ \-\-rc
.IR keyword = value ]
.br
.RB [ \-\-include
.IR pattern ]
.RB [ \-\-exclude
.IR pattern ]
.RE
.SH DESCRIPTION
.B geninfo
converts all GCOV coverage data files found in
.I directory
into tracefiles, which the
.B genhtml
tool can convert to HTML output.
Unless the \-\-output\-filename option is specified,
.B geninfo
writes its
output to one file per .da file, the name of which is generated by simply
appending ".info" to the respective .da file name.
Note that the current user needs write access to both
.I directory
as well as to the original source code location. This is necessary because
some temporary files have to be created there during the conversion process.
Note also that
.B geninfo
is called from within
.BR lcov ,
so that there is usually no need to call it directly.
.B Exclusion markers
To exclude specific lines of code from a tracefile, you can add exclusion
markers to the source code. Additionally you can exclude specific branches from
branch coverage without excluding the involved lines from line and function
coverage. Exclusion markers are keywords which can for example be added in the
form of a comment.
See
.BR lcovrc (5)
how to override some of them.
The following markers are recognized by geninfo:
LCOV_EXCL_LINE
.RS
Lines containing this marker will be excluded.
.br
.RE
LCOV_EXCL_START
.RS
Marks the beginning of an excluded section. The current line is part of this
section.
.br
.RE
LCOV_EXCL_STOP
.RS
Marks the end of an excluded section. The current line not part of this
section.
.RE
.br
LCOV_EXCL_BR_LINE
.RS
Lines containing this marker will be excluded from branch coverage.
.br
.RE
LCOV_EXCL_BR_START
.RS
Marks the beginning of a section which is excluded from branch coverage. The
current line is part of this section.
.br
.RE
LCOV_EXCL_BR_STOP
.RS
Marks the end of a section which is excluded from branch coverage. The current
line not part of this section.
.RE
.br
.SH OPTIONS
.B \-b
.I directory
.br
.B \-\-base\-directory
.I directory
.br
.RS
.RI "Use " directory
as base directory for relative paths.
Use this option to specify the base directory of a build\-environment
when geninfo produces error messages like:
.RS
ERROR: could not read source file /home/user/project/subdir1/subdir2/subdir1/subdir2/file.c
.RE
In this example, use /home/user/project as base directory.
This option is required when using geninfo on projects built with libtool or
similar build environments that work with a base directory, i.e. environments,
where the current working directory when invoking the compiler is not the same
directory in which the source code file is located.
Note that this option will not work in environments where multiple base
directories are used. In that case use configuration file setting
.B geninfo_auto_base=1
(see
.BR lcovrc (5)).
.RE
.B \-\-checksum
.br
.B \-\-no\-checksum
.br
.RS
Specify whether to generate checksum data when writing tracefiles.
Use \-\-checksum to enable checksum generation or \-\-no\-checksum to
disable it. Checksum generation is
.B disabled
by default.
When checksum generation is enabled, a checksum will be generated for each
source code line and stored along with the coverage data. This checksum will
be used to prevent attempts to combine coverage data from different source
code versions.
If you don't work with different source code versions, disable this option
to speed up coverage data processing and to reduce the size of tracefiles.
.RE
.B \-\-compat
.IR mode = value [, mode = value ,...]
.br
.RS
Set compatibility mode.
Use \-\-compat to specify that geninfo should enable one or more compatibility
modes when capturing coverage data. You can provide a comma-separated list
of mode=value pairs to specify the values for multiple modes.
Valid
.I values
are:
.B on
.RS
Enable compatibility mode.
.RE
.B off
.RS
Disable compatibility mode.
.RE
.B auto
.RS
Apply auto-detection to determine if compatibility mode is required. Note that
auto-detection is not available for all compatibility modes.
.RE
If no value is specified, 'on' is assumed as default value.
Valid
.I modes
are:
.B libtool
.RS
Enable this mode if you are capturing coverage data for a project that
was built using the libtool mechanism. See also
\-\-compat\-libtool.
The default value for this setting is 'on'.
.RE
.B hammer
.RS
Enable this mode if you are capturing coverage data for a project that
was built using a version of GCC 3.3 that contains a modification
(hammer patch) of later GCC versions. You can identify a modified GCC 3.3
by checking the build directory of your project for files ending in the
extension '.bbg'. Unmodified versions of GCC 3.3 name these files '.bb'.
The default value for this setting is 'auto'.
.RE
.B split_crc
.RS
Enable this mode if you are capturing coverage data for a project that
was built using a version of GCC 4.6 that contains a modification
(split function checksums) of later GCC versions. Typical error messages
when running geninfo on coverage data produced by such GCC versions are
\'out of memory' and 'reached unexpected end of file'.
The default value for this setting is 'auto'
.RE
.RE
.B \-\-compat\-libtool
.br
.B \-\-no\-compat\-libtool
.br
.RS
Specify whether to enable libtool compatibility mode.
Use \-\-compat\-libtool to enable libtool compatibility mode or \-\-no\-compat\-libtool
to disable it. The libtool compatibility mode is
.B enabled
by default.
When libtool compatibility mode is enabled, geninfo will assume that the source
code relating to a .da file located in a directory named ".libs" can be
found in its parent directory.
If you have directories named ".libs" in your build environment but don't use
libtool, disable this option to prevent problems when capturing coverage data.
.RE
.B \-\-config\-file
.I config\-file
.br
.RS
Specify a configuration file to use.
When this option is specified, neither the system\-wide configuration file
/etc/lcovrc, nor the per\-user configuration file ~/.lcovrc is read.
This option may be useful when there is a need to run several
instances of
.B geninfo
with different configuration file options in parallel.
.RE
.B \-\-derive\-func\-data
.br
.RS
Calculate function coverage data from line coverage data.
Use this option to collect function coverage data, even if the version of the
gcov tool installed on the test system does not provide this data. lcov will
instead derive function coverage data from line coverage data and
information about which lines belong to a function.
.RE
.B \-\-exclude
.I pattern
.br
.RS
Exclude source files matching
.IR pattern .
Use this switch if you want to exclude coverage data for a particular set
of source files matching any of the given patterns. Multiple patterns can be
specified by using multiple
.B --exclude
command line switches. The
.I patterns
will be interpreted as shell wildcard patterns (note that they may need to be
escaped accordingly to prevent the shell from expanding them first).
Can be combined with the
.B --include
command line switch. If a given file matches both the include pattern and the
exclude pattern, the exclude pattern will take precedence.
.RE
.B \-\-external
.br
.B \-\-no\-external
.br
.RS
Specify whether to capture coverage data for external source files.
External source files are files which are not located in one of the directories
specified by \-\-directory or \-\-base\-directory. Use \-\-external to include
external source files while capturing coverage data or \-\-no\-external to
ignore this data.
Data for external source files is
.B included
by default.
.RE
.B \-f
.br
.B \-\-follow
.RS
Follow links when searching .da files.
.RE
.B \-\-gcov\-tool
.I tool
.br
.RS
Specify the location of the gcov tool.
.RE
.B \-h
.br
.B \-\-help
.RS
Print a short help text, then exit.
.RE
.B \-\-include
.I pattern
.br
.RS
Include source files matching
.IR pattern .
Use this switch if you want to include coverage data for only a particular set
of source files matching any of the given patterns. Multiple patterns can be
specified by using multiple
.B --include
command line switches. The
.I patterns
will be interpreted as shell wildcard patterns (note that they may need to be
escaped accordingly to prevent the shell from expanding them first).
.RE
.B \-\-ignore\-errors
.I errors
.br
.RS
Specify a list of errors after which to continue processing.
Use this option to specify a list of one or more classes of errors after which
geninfo should continue processing instead of aborting.
.I errors
can be a comma\-separated list of the following keywords:
.B gcov:
the gcov tool returned with a non\-zero return code.
.B source:
the source code file for a data set could not be found.
.RE
.B \-i
.br
.B \-\-initial
.RS
Capture initial zero coverage data.
Run geninfo with this option on the directories containing .bb, .bbg or .gcno
files before running any test case. The result is a "baseline" coverage data
file that contains zero coverage for every instrumented line and function.
Combine this data file (using lcov \-a) with coverage data files captured
after a test run to ensure that the percentage of total lines covered is
correct even when not all object code files were loaded during the test.
Note: currently, the \-\-initial option does not generate branch coverage
information.
.RE
.B \-\-no\-markers
.br
.RS
Use this option if you want to get coverage data without regard to exclusion
markers in the source code file.
.RE
.B \-\-no\-recursion
.br
.RS
Use this option if you want to get coverage data for the specified directory
only without processing subdirectories.
.RE
.BI "\-o " output\-filename
.br
.BI "\-\-output\-filename " output\-filename
.RS
Write all data to
.IR output\-filename .
If you want to have all data written to a single file (for easier
handling), use this option to specify the respective filename. By default,
one tracefile will be created for each processed .da file.
.RE
.B \-q
.br
.B \-\-quiet
.RS
Do not print progress messages.
Suppresses all informational progress output. When this switch is enabled,
only error or warning messages are printed.
.RE
.B \-\-rc
.IR keyword = value
.br
.RS
Override a configuration directive.
Use this option to specify a
.IR keyword = value
statement which overrides the corresponding configuration statement in
the lcovrc configuration file. You can specify this option more than once
to override multiple configuration statements.
See
.BR lcovrc (5)
for a list of available keywords and their meaning.
.RE
.BI "\-t " testname
.br
.BI "\-\-test\-name " testname
.RS
Use test case name
.I testname
for resulting data. Valid test case names can consist of letters, decimal
digits and the underscore character ('_').
This proves useful when data from several test cases is merged (i.e. by
simply concatenating the respective tracefiles) in which case a test
name can be used to differentiate between data from each test case.
.RE
.B \-v
.br
.B \-\-version
.RS
Print version number, then exit.
.RE
.SH FILES
.I /etc/lcovrc
.RS
The system\-wide configuration file.
.RE
.I ~/.lcovrc
.RS
The per\-user configuration file.
.RE
Following is a quick description of the tracefile format as used by
.BR genhtml ", " geninfo " and " lcov .
A tracefile is made up of several human\-readable lines of text,
divided into sections. If available, a tracefile begins with the
.I testname
which is stored in the following format:
TN:<test name>
For each source file referenced in the .da file, there is a section containing
filename and coverage data:
SF:<absolute path to the source file>
Following is a list of line numbers for each function name found in the
source file:
FN:<line number of function start>,<function name>
Next, there is a list of execution counts for each instrumented function:
FNDA:<execution count>,<function name>
This list is followed by two lines containing the number of functions found
and hit:
FNF:<number of functions found>
FNH:<number of function hit>
Branch coverage information is stored which one line per branch:
BRDA:<line number>,<block number>,<branch number>,<taken>
Block number and branch number are gcc internal IDs for the branch. Taken is
either '-' if the basic block containing the branch was never executed or
a number indicating how often that branch was taken.
Branch coverage summaries are stored in two lines:
BRF:<number of branches found>
BRH:<number of branches hit>
Then there is a list of execution counts for each instrumented line
(i.e. a line which resulted in executable code):
DA:<line number>,<execution count>[,<checksum>]
Note that there may be an optional checksum present for each instrumented
line. The current
.B geninfo
implementation uses an MD5 hash as checksumming algorithm.
At the end of a section, there is a summary about how many lines
were found and how many were actually instrumented:
LH:<number of lines with a non\-zero execution count>
LF:<number of instrumented lines>
Each sections ends with:
end_of_record
In addition to the main source code file there are sections for all
#included files which also contain executable code.
Note that the absolute path of a source file is generated by interpreting
the contents of the respective .bb file (see
.BR "gcov " (1)
for more information on this file type). Relative filenames are prefixed
with the directory in which the .bb file is found.
Note also that symbolic links to the .bb file will be resolved so that the
actual file path is used instead of the path to a link. This approach is
necessary for the mechanism to work with the /proc/gcov files.
.SH AUTHOR
Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
.SH SEE ALSO
.BR lcov (1),
.BR lcovrc (5),
.BR genhtml (1),
.BR genpng (1),
.BR gendesc (1),
.BR gcov (1)
.TH genpng 1 "LCOV 1.13" 2015\-10\-05 "User Manuals"
.SH NAME
genpng \- Generate an overview image from a source file
.SH SYNOPSIS
.B genpng
.RB [ \-h | \-\-help ]
.RB [ \-v | \-\-version ]
.RS 7
.br
.RB [ \-t | \-\-tab\-size
.IR tabsize ]
.RB [ \-w | \-\-width
.IR width ]
.br
.RB [ \-o | \-\-output\-filename
.IR output\-filename ]
.br
.IR source\-file
.SH DESCRIPTION
.B genpng
creates an overview image for a given source code file of either
plain text or .gcov file format.
Note that the
.I GD.pm
Perl module has to be installed for this script to work
(it may be obtained from
.IR http://www.cpan.org ).
Note also that
.B genpng
is called from within
.B genhtml
so that there is usually no need to call it directly.
.SH OPTIONS
.B \-h
.br
.B \-\-help
.RS
Print a short help text, then exit.
.RE
.B \-v
.br
.B \-\-version
.RS
Print version number, then exit.
.RE
.BI "\-t " tab\-size
.br
.BI "\-\-tab\-size " tab\-size
.RS
Use
.I tab\-size
spaces in place of tab.
All occurrences of tabulator signs in the source code file will be replaced
by the number of spaces defined by
.I tab\-size
(default is 4).
.RE
.BI "\-w " width
.br
.BI "\-\-width " width
.RS
Set width of output image to
.I width
pixel.
The resulting image will be exactly
.I width
pixel wide (default is 80).
Note that source code lines which are longer than
.I width
will be truncated.
.RE
.BI "\-o " filename
.br
.BI "\-\-output\-filename " filename
.RS
Write image to
.IR filename .
Specify a name for the resulting image file (default is
.IR source\-file .png).
.RE
.SH AUTHOR
Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
.SH SEE ALSO
.BR lcov (1),
.BR genhtml (1),
.BR geninfo (1),
.BR gendesc (1),
.BR gcov (1)
.TH lcov 1 "LCOV 1.13" 2015\-10\-05 "User Manuals"
.SH NAME
lcov \- a graphical GCOV front\-end
.SH SYNOPSIS
.B lcov
.BR \-c | \-\-capture
.RS 5
.br
.RB [ \-d | \-\-directory
.IR directory ]
.RB [ \-k | \-\-kernel\-directory
.IR directory ]
.br
.RB [ \-o | \-\-output\-file
.IR tracefile ]
.RB [ \-t | \-\-test\-name
.IR testname ]
.br
.RB [ \-b | \-\-base\-directory
.IR directory ]
.RB [ \-i | \-\-initial ]
.RB [ \-\-gcov\-tool
.IR tool ]
.br
.RB [ \-\-checksum ]
.RB [ \-\-no\-checksum ]
.RB [ \-\-no\-recursion ]
.RB [ \-f | \-\-follow ]
.br
.RB [ \-\-compat\-libtool ]
.RB [ \-\-no\-compat\-libtool ]
.RB [ \-\-ignore\-errors
.IR errors ]
.br
.RB [ \-\-to\-package
.IR package ]
.RB [ \-\-from\-package
.IR package ]
.RB [ \-q | \-\-quiet ]
.br
.RB [ \-\-no\-markers ]
.RB [ \-\-external ]
.RB [ \-\-no\-external ]
.br
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-rc
.IR keyword = value ]
.br
.RB [ \-\-compat
.IR mode =on|off|auto]
.br
.RB [ \-\-include
.IR pattern ]
.RB [ \-\-exclude
.IR pattern ]
.br
.RE
.B lcov
.BR \-z | \-\-zerocounters
.RS 5
.br
.RB [ \-d | \-\-directory
.IR directory ]
.RB [ \-\-no\-recursion ]
.RB [ \-f | \-\-follow ]
.br
.RB [ \-q | \-\-quiet ]
.br
.RE
.B lcov
.BR \-l | \-\-list
.I tracefile
.RS 5
.br
.RB [ \-q | \-\-quiet ]
.RB [ \-\-list\-full\-path ]
.RB [ \-\-no\-list\-full\-path ]
.br
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-rc
.IR keyword = value ]
.br
.RE
.B lcov
.BR \-a | \-\-add\-tracefile
.I tracefile
.RS 5
.br
.RB [ \-o | \-\-output\-file
.IR tracefile ]
.RB [ \-\-checksum ]
.RB [ \-\-no\-checksum ]
.br
.RB [ \-q | \-\-quiet ]
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-rc
.IR keyword = value ]
.br
.RE
.B lcov
.BR \-e | \-\-extract
.I tracefile pattern
.RS 5
.br
.RB [ \-o | \-\-output\-file
.IR tracefile ]
.RB [ \-\-checksum ]
.RB [ \-\-no\-checksum ]
.br
.RB [ \-q | \-\-quiet ]
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-rc
.IR keyword = value ]
.br
.RE
.B lcov
.BR \-r | \-\-remove
.I tracefile pattern
.RS 5
.br
.RB [ \-o | \-\-output\-file
.IR tracefile ]
.RB [ \-\-checksum ]
.RB [ \-\-no\-checksum ]
.br
.RB [ \-q | \-\-quiet ]
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-rc
.IR keyword = value ]
.br
.RE
.B lcov
.BR \-\-diff
.IR "tracefile diff"
.RS 5
.br
.RB [ \-o | \-\-output\-file
.IR tracefile ]
.RB [ \-\-checksum ]
.RB [ \-\-no\-checksum ]
.br
.RB [ \-\-convert\-filenames ]
.RB [ \-\-strip
.IR depth ]
.RB [ \-\-path
.IR path ]
.RB [ \-q | \-\-quiet ]
.br
.RB [ \-\-config\-file
.IR config\-file ]
.RB [ \-\-rc
.IR keyword = value ]
.br
.RE
.B lcov
.BR \-\-summary
.I tracefile
.RS 5
.br
.RB [ \-q | \-\-quiet ]
.br
.RE
.B lcov
.RB [ \-h | \-\-help ]
.RB [ \-v | \-\-version ]
.RS 5
.br
.RE
.SH DESCRIPTION
.B lcov
is a graphical front\-end for GCC's coverage testing tool gcov. It collects
line, function and branch coverage data for multiple source files and creates
HTML pages containing the source code annotated with coverage information.
It also adds overview pages for easy navigation within the file structure.
Use
.B lcov
to collect coverage data and
.B genhtml
to create HTML pages. Coverage data can either be collected from the
currently running Linux kernel or from a user space application. To do this,
you have to complete the following preparation steps:
For Linux kernel coverage:
.RS
Follow the setup instructions for the gcov\-kernel infrastructure:
.I http://ltp.sourceforge.net/coverage/gcov.php
.br
.RE
For user space application coverage:
.RS
Compile the application with GCC using the options
"\-fprofile\-arcs" and "\-ftest\-coverage".
.RE
Please note that this man page refers to the output format of
.B lcov
as ".info file" or "tracefile" and that the output of GCOV
is called ".da file".
Also note that when printing percentages, 0% and 100% are only printed when
the values are exactly 0% and 100% respectively. Other values which would
conventionally be rounded to 0% or 100% are instead printed as nearest
non-boundary value. This behavior is in accordance with that of the
.BR gcov (1)
tool.
.SH OPTIONS
.B \-a
.I tracefile
.br
.B \-\-add\-tracefile
.I tracefile
.br
.RS
Add contents of
.IR tracefile .
Specify several tracefiles using the \-a switch to combine the coverage data
contained in these files by adding up execution counts for matching test and
filename combinations.
The result of the add operation will be written to stdout or the tracefile
specified with \-o.
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.B \-b
.I directory
.br
.B \-\-base\-directory
.I directory
.br
.RS
.RI "Use " directory
as base directory for relative paths.
Use this option to specify the base directory of a build\-environment
when lcov produces error messages like:
.RS
ERROR: could not read source file /home/user/project/subdir1/subdir2/subdir1/subdir2/file.c
.RE
In this example, use /home/user/project as base directory.
This option is required when using lcov on projects built with libtool or
similar build environments that work with a base directory, i.e. environments,
where the current working directory when invoking the compiler is not the same
directory in which the source code file is located.
Note that this option will not work in environments where multiple base
directories are used. In that case use configuration file setting
.B geninfo_auto_base=1
(see
.BR lcovrc (5)).
.RE
.B \-c
.br
.B \-\-capture
.br
.RS
Capture coverage data.
By default captures the current kernel execution counts and writes the
resulting coverage data to the standard output. Use the \-\-directory
option to capture counts for a user space program.
The result of the capture operation will be written to stdout or the tracefile
specified with \-o.
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.B \-\-checksum
.br
.B \-\-no\-checksum
.br
.RS
Specify whether to generate checksum data when writing tracefiles.
Use \-\-checksum to enable checksum generation or \-\-no\-checksum to
disable it. Checksum generation is
.B disabled
by default.
When checksum generation is enabled, a checksum will be generated for each
source code line and stored along with the coverage data. This checksum will
be used to prevent attempts to combine coverage data from different source
code versions.
If you don't work with different source code versions, disable this option
to speed up coverage data processing and to reduce the size of tracefiles.
.RE
.B \-\-compat
.IR mode = value [, mode = value ,...]
.br
.RS
Set compatibility mode.
Use \-\-compat to specify that lcov should enable one or more compatibility
modes when capturing coverage data. You can provide a comma-separated list
of mode=value pairs to specify the values for multiple modes.
Valid
.I values
are:
.B on
.RS
Enable compatibility mode.
.RE
.B off
.RS
Disable compatibility mode.
.RE
.B auto
.RS
Apply auto-detection to determine if compatibility mode is required. Note that
auto-detection is not available for all compatibility modes.
.RE
If no value is specified, 'on' is assumed as default value.
Valid
.I modes
are:
.B libtool
.RS
Enable this mode if you are capturing coverage data for a project that
was built using the libtool mechanism. See also
\-\-compat\-libtool.
The default value for this setting is 'on'.
.RE
.B hammer
.RS
Enable this mode if you are capturing coverage data for a project that
was built using a version of GCC 3.3 that contains a modification
(hammer patch) of later GCC versions. You can identify a modified GCC 3.3
by checking the build directory of your project for files ending in the
extension '.bbg'. Unmodified versions of GCC 3.3 name these files '.bb'.
The default value for this setting is 'auto'.
.RE
.B split_crc
.RS
Enable this mode if you are capturing coverage data for a project that
was built using a version of GCC 4.6 that contains a modification
(split function checksums) of later GCC versions. Typical error messages
when running lcov on coverage data produced by such GCC versions are
\'out of memory' and 'reached unexpected end of file'.
The default value for this setting is 'auto'
.RE
.RE
.B \-\-compat\-libtool
.br
.B \-\-no\-compat\-libtool
.br
.RS
Specify whether to enable libtool compatibility mode.
Use \-\-compat\-libtool to enable libtool compatibility mode or \-\-no\-compat\-libtool
to disable it. The libtool compatibility mode is
.B enabled
by default.
When libtool compatibility mode is enabled, lcov will assume that the source
code relating to a .da file located in a directory named ".libs" can be
found in its parent directory.
If you have directories named ".libs" in your build environment but don't use
libtool, disable this option to prevent problems when capturing coverage data.
.RE
.B \-\-config\-file
.I config\-file
.br
.RS
Specify a configuration file to use.
When this option is specified, neither the system\-wide configuration file
/etc/lcovrc, nor the per\-user configuration file ~/.lcovrc is read.
This option may be useful when there is a need to run several
instances of
.B lcov
with different configuration file options in parallel.
.RE
.B \-\-convert\-filenames
.br
.RS
Convert filenames when applying diff.
Use this option together with \-\-diff to rename the file names of processed
data sets according to the data provided by the diff.
.RE
.B \-\-diff
.I tracefile
.I difffile
.br
.RS
Convert coverage data in
.I tracefile
using source code diff file
.IR difffile .
Use this option if you want to merge coverage data from different source code
levels of a program, e.g. when you have data taken from an older version
and want to combine it with data from a more current version.
.B lcov
will try to map source code lines between those versions and adjust the coverage
data respectively.
.I difffile
needs to be in unified format, i.e. it has to be created using the "\-u" option
of the
.B diff
tool.
Note that lines which are not present in the old version will not be counted
as instrumented, therefore tracefiles resulting from this operation should
not be interpreted individually but together with other tracefiles taken
from the newer version. Also keep in mind that converted coverage data should
only be used for overview purposes as the process itself introduces a loss
of accuracy.
The result of the diff operation will be written to stdout or the tracefile
specified with \-o.
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.B \-d
.I directory
.br
.B \-\-directory
.I directory
.br
.RS
Use .da files in
.I directory
instead of kernel.
If you want to work on coverage data for a user space program, use this
option to specify the location where the program was compiled (that's
where the counter files ending with .da will be stored).
Note that you may specify this option more than once.
.RE
.B \-\-exclude
.I pattern
.br
.RS
Exclude source files matching
.IR pattern .
Use this switch if you want to exclude coverage data for a particular set
of source files matching any of the given patterns. Multiple patterns can be
specified by using multiple
.B --exclude
command line switches. The
.I patterns
will be interpreted as shell wildcard patterns (note that they may need to be
escaped accordingly to prevent the shell from expanding them first).
Can be combined with the
.B --include
command line switch. If a given file matches both the include pattern and the
exclude pattern, the exclude pattern will take precedence.
.RE
.B \-\-external
.br
.B \-\-no\-external
.br
.RS
Specify whether to capture coverage data for external source files.
External source files are files which are not located in one of the directories
specified by \-\-directory or \-\-base\-directory. Use \-\-external to include
external source files while capturing coverage data or \-\-no\-external to
ignore this data.
Data for external source files is
.B included
by default.
.RE
.B \-e
.I tracefile
.I pattern
.br
.B \-\-extract
.I tracefile
.I pattern
.br
.RS
Extract data from
.IR tracefile .
Use this switch if you want to extract coverage data for only a particular
set of files from a tracefile. Additional command line parameters will be
interpreted as shell wildcard patterns (note that they may need to be
escaped accordingly to prevent the shell from expanding them first).
Every file entry in
.I tracefile
which matches at least one of those patterns will be extracted.
The result of the extract operation will be written to stdout or the tracefile
specified with \-o.
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.B \-f
.br
.B \-\-follow
.br
.RS
Follow links when searching for .da files.
.RE
.B \-\-from\-package
.I package
.br
.RS
Use .da files in
.I package
instead of kernel or directory.
Use this option if you have separate machines for build and test and
want to perform the .info file creation on the build machine. See
\-\-to\-package for more information.
.RE
.B \-\-gcov\-tool
.I tool
.br
.RS
Specify the location of the gcov tool.
.RE
.B \-h
.br
.B \-\-help
.br
.RS
Print a short help text, then exit.
.RE
.B \-\-include
.I pattern
.br
.RS
Include source files matching
.IR pattern .
Use this switch if you want to include coverage data for only a particular set
of source files matching any of the given patterns. Multiple patterns can be
specified by using multiple
.B --include
command line switches. The
.I patterns
will be interpreted as shell wildcard patterns (note that they may need to be
escaped accordingly to prevent the shell from expanding them first).
.RE
.B \-\-ignore\-errors
.I errors
.br
.RS
Specify a list of errors after which to continue processing.
Use this option to specify a list of one or more classes of errors after which
lcov should continue processing instead of aborting.
.I errors
can be a comma\-separated list of the following keywords:
.B gcov:
the gcov tool returned with a non\-zero return code.
.B source:
the source code file for a data set could not be found.
.B graph:
the graph file could not be found or is corrupted.
.RE
.B \-i
.br
.B \-\-initial
.RS
Capture initial zero coverage data.
Run lcov with \-c and this option on the directories containing .bb, .bbg
or .gcno files before running any test case. The result is a "baseline"
coverage data file that contains zero coverage for every instrumented line.
Combine this data file (using lcov \-a) with coverage data files captured
after a test run to ensure that the percentage of total lines covered is
correct even when not all source code files were loaded during the test.
Recommended procedure when capturing data for a test case:
1. create baseline coverage data file
.RS
# lcov \-c \-i \-d appdir \-o app_base.info
.br
.RE
2. perform test
.RS
# appdir/test
.br
.RE
3. create test coverage data file
.RS
# lcov \-c \-d appdir \-o app_test.info
.br
.RE
4. combine baseline and test coverage data
.RS
# lcov \-a app_base.info \-a app_test.info \-o app_total.info
.br
.RE
.RE
.B \-k
.I subdirectory
.br
.B \-\-kernel\-directory
.I subdirectory
.br
.RS
Capture kernel coverage data only from
.IR subdirectory .
Use this option if you don't want to get coverage data for all of the
kernel, but only for specific subdirectories. This option may be specified
more than once.
Note that you may need to specify the full path to the kernel subdirectory
depending on the version of the kernel gcov support.
.RE
.B \-l
.I tracefile
.br
.B \-\-list
.I tracefile
.br
.RS
List the contents of the
.IR tracefile .
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.B \-\-list\-full\-path
.br
.B \-\-no\-list\-full\-path
.br
.RS
Specify whether to show full paths during list operation.
Use \-\-list\-full\-path to show full paths during list operation
or \-\-no\-list\-full\-path to show shortened paths. Paths are
.B shortened
by default.
.RE
.B \-\-no\-markers
.br
.RS
Use this option if you want to get coverage data without regard to exclusion
markers in the source code file. See
.BR "geninfo " (1)
for details on exclusion markers.
.RE
.B \-\-no\-recursion
.br
.RS
Use this option if you want to get coverage data for the specified directory
only without processing subdirectories.
.RE
.B \-o
.I tracefile
.br
.B \-\-output\-file
.I tracefile
.br
.RS
Write data to
.I tracefile
instead of stdout.
Specify "\-" as a filename to use the standard output.
By convention, lcov\-generated coverage data files are called "tracefiles" and
should have the filename extension ".info".
.RE
.B \-\-path
.I path
.br
.RS
Strip path from filenames when applying diff.
Use this option together with \-\-diff to tell lcov to disregard the specified
initial path component when matching between tracefile and diff filenames.
.RE
.B \-q
.br
.B \-\-quiet
.br
.RS
Do not print progress messages.
This option is implied when no output filename is specified to prevent
progress messages to mess with coverage data which is also printed to
the standard output.
.RE
.B \-\-rc
.IR keyword = value
.br
.RS
Override a configuration directive.
Use this option to specify a
.IR keyword = value
statement which overrides the corresponding configuration statement in
the lcovrc configuration file. You can specify this option more than once
to override multiple configuration statements.
See
.BR lcovrc (5)
for a list of available keywords and their meaning.
.RE
.B \-r
.I tracefile
.I pattern
.br
.B \-\-remove
.I tracefile
.I pattern
.br
.RS
Remove data from
.IR tracefile .
Use this switch if you want to remove coverage data for a particular
set of files from a tracefile. Additional command line parameters will be
interpreted as shell wildcard patterns (note that they may need to be
escaped accordingly to prevent the shell from expanding them first).
Every file entry in
.I tracefile
which matches at least one of those patterns will be removed.
The result of the remove operation will be written to stdout or the tracefile
specified with \-o.
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.B \-\-strip
.I depth
.br
.RS
Strip path components when applying diff.
Use this option together with \-\-diff to tell lcov to disregard the specified
number of initial directories when matching tracefile and diff filenames.
.RE
.B \-\-summary
.I tracefile
.br
.RS
Show summary coverage information for the specified tracefile.
Note that you may specify this option more than once.
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.B \-t
.I testname
.br
.B \-\-test\-name
.I testname
.br
.RS
Specify test name to be stored in the tracefile.
This name identifies a coverage data set when more than one data set is merged
into a combined tracefile (see option \-a).
Valid test names can consist of letters, decimal digits and the underscore
character ("_").
.RE
.B \-\-to\-package
.I package
.br
.RS
Store .da files for later processing.
Use this option if you have separate machines for build and test and
want to perform the .info file creation on the build machine. To do this,
follow these steps:
On the test machine:
.RS
.br
\- run the test
.br
\- run lcov \-c [\-d directory] \-\-to-package
.I file
.br
\- copy
.I file
to the build machine
.RE
.br
On the build machine:
.RS
.br
\- run lcov \-c \-\-from-package
.I file
[\-o and other options]
.RE
.br
This works for both kernel and user space coverage data. Note that you might
have to specify the path to the build directory using \-b with
either \-\-to\-package or \-\-from-package. Note also that the package data
must be converted to a .info file before recompiling the program or it will
become invalid.
.RE
.B \-v
.br
.B \-\-version
.br
.RS
Print version number, then exit.
.RE
.B \-z
.br
.B \-\-zerocounters
.br
.RS
Reset all execution counts to zero.
By default tries to reset kernel execution counts. Use the \-\-directory
option to reset all counters of a user space program.
Only one of \-z, \-c, \-a, \-e, \-r, \-l, \-\-diff or \-\-summary may be
specified at a time.
.RE
.SH FILES
.I /etc/lcovrc
.RS
The system\-wide configuration file.
.RE
.I ~/.lcovrc
.RS
The per\-user configuration file.
.RE
.SH AUTHOR
Peter Oberparleiter <Peter.Oberparleiter@de.ibm.com>
.SH SEE ALSO
.BR lcovrc (5),
.BR genhtml (1),
.BR geninfo (1),
.BR genpng (1),
.BR gendesc (1),
.BR gcov (1)
.TH lcovrc 5 "LCOV 1.13" 2015\-10\-05 "User Manuals"
.SH NAME
lcovrc \- lcov configuration file
.SH DESCRIPTION
The
.I lcovrc
file contains configuration information for the
.B lcov
code coverage tool (see
.BR lcov (1)).
.br
The system\-wide configuration file is located at
.IR /etc/lcovrc .
To change settings for a single user, place a customized copy of this file at
location
.IR ~/.lcovrc .
Where available, command\-line options override configuration file settings.
Lines in a configuration file can either be:
.IP " *"
empty lines or lines consisting only of white space characters. These lines are
ignored.
.IP " *"
comment lines which start with a hash sign ('#'). These are treated like empty
lines and will be ignored.
.IP " *"
statements in the form
.RI ' key " = " value '.
A list of valid statements and their description can be found in
section 'OPTIONS' below.
.PP
.B Example configuration:
.IP
#
.br
# Example LCOV configuration file
.br
#
.br
# External style sheet file
.br
#genhtml_css_file = gcov.css
.br
# Coverage rate limits
.br
genhtml_hi_limit = 90
.br
genhtml_med_limit = 75
.br
# Width of line coverage field in source code view
.br
genhtml_line_field_width = 12
.br
# Width of branch coverage field in source code view
.br
genhtml_branch_field_width = 16
.br
# Width of overview image
.br
genhtml_overview_width = 80
.br
# Resolution of overview navigation
.br
genhtml_nav_resolution = 4
.br
# Offset for source code navigation
.br
genhtml_nav_offset = 10
.br
# Do not remove unused test descriptions if non\-zero
.br
genhtml_keep_descriptions = 0
.br
# Do not remove prefix from directory names if non\-zero
.br
genhtml_no_prefix = 0
.br
# Do not create source code view if non\-zero
.br
genhtml_no_source = 0
.br
# Specify size of tabs
.br
genhtml_num_spaces = 8
.br
# Highlight lines with converted\-only data if non\-zero
.br
genhtml_highlight = 0
.br
# Include color legend in HTML output if non\-zero
.br
genhtml_legend = 0
.br
# Include HTML file at start of HTML output
.br
#genhtml_html_prolog = prolog.html
.br
# Include HTML file at end of HTML output
.br
#genhtml_html_epilog = epilog.html
.br
# Use custom HTML file extension
.br
#genhtml_html_extension = html
.br
# Compress all generated html files with gzip.
.br
#genhtml_html_gzip = 1
.br
# Include sorted overview pages
.br
genhtml_sort = 1
.br
# Include function coverage data display
.br
#genhtml_function_coverage = 1
.br
# Include branch coverage data display
.br
#genhtml_branch_coverage = 1
.br
# Specify the character set of all generated HTML pages
.br
genhtml_charset=UTF\-8
.br
# Allow HTML markup in test case description text if non\-zero
.br
genhtml_desc_html=0
.br
# Specify the precision for coverage rates
.br
#genhtml_precision=1
.br
# Demangle C++ symbols
.br
#genhtml_demangle_cpp=1
.br
# Location of the gcov tool
.br
#geninfo_gcov_tool = gcov
.br
# Adjust test names if non\-zero
.br
#geninfo_adjust_testname = 0
.br
# Calculate a checksum for each line if non\-zero
.br
geninfo_checksum = 0
.br
# Enable libtool compatibility mode if non\-zero
.br
geninfo_compat_libtool = 0
.br
# Specify whether to capture coverage data for external source
.br
# files
.br
#geninfo_external = 1
.br
# Use gcov's --all-blocks option if non-zero
.br
#geninfo_gcov_all_blocks = 1
.br
# Specify compatiblity modes (same as \-\-compat option
.br
# of geninfo)
.br
#geninfo_compat = libtool=on, hammer=auto, split_crc=auto
.br
# Adjust path to source files by removing or changing path
.br
# components that match the specified pattern (Perl regular
.br
# expression format)
.br
#geninfo_adjust_src_path = /tmp/build => /usr/src
# Specify if geninfo should try to automatically determine
.br
# the base-directory when collecting coverage data.
.br
geninfo_auto_base = 1
.br
# Directory containing gcov kernel files
.br
lcov_gcov_dir = /proc/gcov
.br
# Location for temporary directories
.br
lcov_tmp_dir = /tmp
.br
# Show full paths during list operation if non\-zero
.br
lcov_list_full_path = 0
.br
# Specify the maximum width for list output. This value is
.br
# ignored when lcov_list_full_path is non\-zero.
.br
lcov_list_width = 80
.br
# Specify the maximum percentage of file names which may be
.br
# truncated when choosing a directory prefix in list output.
.br
# This value is ignored when lcov_list_full_path is non\-zero.
.br
lcov_list_truncate_max = 20
# Specify if function coverage data should be collected and
.br
# processed.
.br
lcov_function_coverage = 1
.br
# Specify if branch coverage data should be collected and
.br
# processed.
.br
lcov_branch_coverage = 0
.br
.PP
.SH OPTIONS
.BR genhtml_css_file " ="
.I filename
.IP
Specify an external style sheet file. Use this option to modify the appearance of the HTML output as generated by
.BR genhtml .
During output generation, a copy of this file will be placed in the output
directory.
.br
This option corresponds to the \-\-css\-file command line option of
.BR genhtml .
.br
By default, a standard CSS file is generated.
.PP
.BR genhtml_hi_limit " ="
.I hi_limit
.br
.BR genhtml_med_limit " ="
.I med_limit
.br
.IP
Specify coverage rate limits for classifying file entries. Use this option to
modify the coverage rates (in percent) for line, function and branch coverage at
which a result is classified as high, medium or low coverage. This
classification affects the color of the corresponding entries on the overview
pages of the HTML output:
.br
High: hi_limit <= rate <= 100 default color: green
.br
Medium: med_limit <= rate < hi_limit default color: orange
.br
Low: 0 <= rate < med_limit default color: red
.br
Defaults are 90 and 75 percent.
.PP
.BR genhtml_line_field_width " ="
.I number_of_characters
.IP
Specify the width (in characters) of the source code view column containing
line coverage information.
.br
Default is 12.
.PP
.BR genhtml_branch_field_width " ="
.I number_of_characters
.IP
Specify the width (in characters) of the source code view column containing
branch coverage information.
.br
Default is 16.
.PP
.BR genhtml_overview_width " ="
.I pixel_size
.IP
Specify the width (in pixel) of the overview image created when generating HTML
output using the \-\-frames option of
.BR genhtml .
.br
Default is 80.
.PP
.BR genhtml_nav_resolution " ="
.I lines
.IP
Specify the resolution of overview navigation when generating HTML output using
the \-\-frames option of
.BR genhtml .
This number specifies the maximum difference in lines between the position a
user selected from the overview and the position the source code window is
scrolled to.
.br
Default is 4.
.PP
.BR genhtml_nav_offset " ="
.I lines
.IP
Specify the overview navigation line offset as applied when generating HTML
output using the \-\-frames option of
.BR genhtml.
.br
Clicking a line in the overview image should show the source code view at
a position a bit further up, so that the requested line is not the first
line in the window. This number specifies that offset.
.br
Default is 10.
.PP
.BR genhtml_keep_descriptions " ="
.IR 0 | 1
.IP
If non\-zero, keep unused test descriptions when generating HTML output using
.BR genhtml .
.br
This option corresponds to the \-\-keep\-descriptions option of
.BR genhtml .
.br
Default is 0.
.PP
.BR genhtml_no_prefix " ="
.IR 0 | 1
.IP
If non\-zero, do not try to find and remove a common prefix from directory names.
.br
This option corresponds to the \-\-no\-prefix option of
.BR genhtml .
.br
Default is 0.
.PP
.BR genhtml_no_source " ="
.IR 0 | 1
.IP
If non\-zero, do not create a source code view when generating HTML output using
.BR genhtml .
.br
This option corresponds to the \-\-no\-source option of
.BR genhtml .
.br
Default is 0.
.PP
.BR genhtml_num_spaces " ="
.I num
.IP
Specify the number of spaces to use as replacement for tab characters in the
HTML source code view as generated by
.BR genhtml .
.br
This option corresponds to the \-\-num\-spaces option of
.BR genthml .
.br
Default is 8.
.PP
.BR genhtml_highlight " ="
.IR 0 | 1
.IP
If non\-zero, highlight lines with converted\-only data in
HTML output as generated by
.BR genhtml .
.br
This option corresponds to the \-\-highlight option of
.BR genhtml .
.br
Default is 0.
.PP
.BR genhtml_legend " ="
.IR 0 | 1
.IP
If non\-zero, include a legend explaining the meaning of color coding in the HTML
output as generated by
.BR genhtml .
.br
This option corresponds to the \-\-legend option of
.BR genhtml .
.br
Default is 0.
.PP
.BR genhtml_html_prolog " ="
.I filename
.IP
If set, include the contents of the specified file at the beginning of HTML
output.
This option corresponds to the \-\-html\-prolog option of
.BR genhtml .
.br
Default is to use no extra prolog.
.PP
.BR genhtml_html_epilog " ="
.I filename
.IP
If set, include the contents of the specified file at the end of HTML output.
This option corresponds to the \-\-html\-epilog option of
.BR genhtml .
.br
Default is to use no extra epilog.
.PP
.BR genhtml_html_extension " ="
.I extension
.IP
If set, use the specified string as filename extension for generated HTML files.
This option corresponds to the \-\-html\-extension option of
.BR genhtml .
.br
Default extension is "html".
.PP
.BR genhtml_html_gzip " ="
.IR 0 | 1
.IP
If set, compress all html files using gzip.
This option corresponds to the \-\-html\-gzip option of
.BR genhtml .
.br
Default extension is 0.
.PP
.BR genhtml_sort " ="
.IR 0 | 1
.IP
If non\-zero, create overview pages sorted by coverage rates when generating
HTML output using
.BR genhtml .
.br
This option can be set to 0 by using the \-\-no\-sort option of
.BR genhtml .
.br
Default is 1.
.PP
.BR genhtml_function_coverage " ="
.IR 0 | 1
.IP
If non\-zero, include function coverage data when generating HTML output using
.BR genhtml .
.br
This option can be set to 0 by using the \-\-no\-function\-coverage option of
.BR genhtml .
.br
Default is 1.
.PP
.BR genhtml_branch_coverage " ="
.IR 0 | 1
.IP
If non\-zero, include branch coverage data when generating HTML output using
.BR genhtml .
.br
This option can be set to 0 by using the \-\-no\-branch\-coverage option of
.BR genhtml .
.br
Default is 1.
.PP
.BR genhtml_charset " ="
.I charset
.IP
Specify the character set of all generated HTML pages.
.br
Use this option if the source code contains characters which are not
part of the default character set. Note that this option is ignored
when a custom HTML prolog is specified (see also
.BR genhtml_html_prolog ).
.br
Default is UTF-8.
.PP
.BR genhtml_demangle_cpp " ="
.IR 0 | 1
.IP
If non-zero, demangle C++ function names in function overviews.
Set this option to one if you want to convert C++ internal function
names to human readable format for display on the HTML function overview
page. This option requires that the c++filt tool is installed (see
.BR c++filt(1)
).
.br
This option corresponds to the \-\-demangle\-cpp command line option of
.BR genhtml .
.br
Default is 0.
.PP
.BR genhtml_desc_html " ="
.IR 0 | 1
.IP
If non-zero, test case descriptions may contain HTML markup.
Set this option to one if you want to embed HTML markup (for example to
include links) in test case descriptions. When set to zero, HTML markup
characters will be escaped to show up as plain text on the test case
description page.
.br
Default is 0.
.PP
.BR genhtml_precision " ="
.IR 1 | 2 | 3 | 4
.IP
Specify how many digits after the decimal-point should be used for
displaying coverage rates.
.br
Default is 1.
.PP
.
.BR geninfo_gcov_tool " ="
.I path_to_gcov
.IP
Specify the location of the gcov tool (see
.BR gcov (1))
which is used to generate coverage information from data files.
.br
Default is 'gcov'.
.PP
.BR geninfo_adjust_testname " ="
.IR 0 | 1
.IP
If non\-zero, adjust test names to include operating system information
when capturing coverage data.
.br
Default is 0.
.PP
.BR geninfo_checksum " ="
.IR 0 | 1
.IP
If non\-zero, generate source code checksums when capturing coverage data.
Checksums are useful to prevent merging coverage data from incompatible
source code versions but checksum generation increases the size of coverage
files and the time used to generate those files.
.br
This option corresponds to the \-\-checksum and \-\-no\-checksum command line
option of
.BR geninfo .
.br
Default is 0.
.PP
.BR geninfo_compat_libtool " ="
.IR 0 | 1
.IP
If non\-zero, enable libtool compatibility mode. When libtool compatibility
mode is enabled, lcov will assume that the source code relating to a .da file
located in a directory named ".libs" can be found in its parent directory.
.br
This option corresponds to the \-\-compat\-libtool and \-\-no\-compat\-libtool
command line option of
.BR geninfo .
.br
Default is 1.
.PP
.BR geninfo_external " ="
.IR 0 | 1
.IP
If non\-zero, capture coverage data for external source files.
External source files are files which are not located in one of the directories
(including sub-directories)
specified by the \-\-directory or \-\-base\-directory options of
.BR lcov / geninfo .
Default is 1.
.PP
.BR geninfo_gcov_all_blocks " ="
.IR 0 | 1
.IP
If non\-zero, call the gcov tool with option --all-blocks.
Using --all-blocks will produce more detailed branch coverage information for
each line. Set this option to zero if you do not need detailed branch coverage
information to speed up the process of capturing code coverage or to work
around a bug in some versions of gcov which will cause it to endlessly loop
when analysing some files.
Default is 1.
.PP
.BR geninfo_compat " ="
.IR mode = value [, mode = value ,...]
.IP
Specify that geninfo should enable one or more compatibility modes
when capturing coverage data.
This option corresponds to the \-\-compat command line option of
.BR geninfo .
Default is 'libtool=on, hammer=auto, split_crc=auto'.
.PP
.BR geninfo_adjust_src_path " ="
.IR pattern " => " replacement
.br
.BR geninfo_adjust_src_path " ="
.I pattern
.IP
Adjust source paths when capturing coverage data.
Use this option in situations where geninfo cannot find the correct
path to source code files of a project. By providing a
.I pattern
in Perl regular expression format (see
.BR perlre (1))
and an optional replacement string, you can instruct geninfo to
remove or change parts of the incorrect source path.
.B Example:
.br
1. When geninfo reports that it cannot find source file
.br
/path/to/src/.libs/file.c
.br
while the file is actually located in
.br
/path/to/src/file.c
.br
use the following parameter:
.br
geninfo_adjust_src_path = /.libs
This will remove all "/.libs" strings from the path.
2. When geninfo reports that it cannot find source file
.br
/tmp/build/file.c
.br
while the file is actually located in
.br
/usr/src/file.c
.br
use the following parameter:
.br
geninfo_adjust_src_path = /tmp/build => /usr/src
.br
This will change all "/tmp/build" strings in the path to "/usr/src".
.PP
.BR geninfo_auto_base " ="
.IR 0 | 1
.IP
If non\-zero, apply a heuristic to determine the base directory when
collecting coverage data.
.br
Use this option when using geninfo on projects built with libtool or
similar build environments that work with multiple base directories,
i.e. environments, where the current working directory when invoking the
compiler ist not the same directory in which the source code file is
located, and in addition, is different between files of the same project.
.br
Default is 1.
.PP
.BR lcov_gcov_dir " ="
.I path_to_kernel_coverage_data
.IP
Specify the path to the directory where kernel coverage data can be found
or leave undefined for auto-detection.
.br
Default is auto-detection.
.PP
.BR lcov_tmp_dir " ="
.I temp
.IP
Specify the location of a directory used for temporary files.
.br
Default is '/tmp'.
.PP
.BR lcov_list_full_path " ="
.IR 0 | 1
.IP
If non-zero, print the full path to source code files during a list operation.
.br
This option corresponds to the \-\-list\-full\-path option of
.BR lcov .
.br
Default is 0.
.PP
.BR lcov_list_max_width " ="
.IR width
.IP
Specify the maximum width for list output. This value is ignored when
lcov_list_full_path is non\-zero.
.br
Default is 80.
.PP
.BR lcov_list_truncate_max
.B " ="
.IR percentage
.IP
Specify the maximum percentage of file names which may be truncated when
choosing a directory prefix in list output. This value is ignored when
lcov_list_full_path is non\-zero.
.br
Default is 20.
.PP
.BR lcov_function_coverage " ="
.IR 0 | 1
.IP
Specify whether lcov should handle function coverage data.
.br
Setting this option to 0 can reduce memory and CPU time consumption
when lcov is collecting and processing coverage data, as well as
reduce the size of the resulting data files. Note that setting
.B genhtml_function_coverage
will override this option for HTML generation.
.br
Default is 1.
.PP
.BR lcov_branch_coverage " ="
.IR 0 | 1
.IP
Specify whether lcov should handle branch coverage data.
.br
Setting this option to 0 can reduce memory and CPU time consumption
when lcov is collecting and processing coverage data, as well as
reduce the size of the resulting data files. Note that setting
.B genhtml_branch_coverage
will override this option for HTML generation.
.br
Default is 0.
.PP
.BR lcov_excl_line " ="
.I expression
.IP
Specify the regular expression of lines to exclude.
.br
Default is 'LCOV_EXCL_LINE'.
.PP
.BR lcov_excl_br_line " ="
.I expression
.IP
Specify the regular expression of lines to exclude from branch coverage.
.br
Default is 'LCOV_EXCL_BR_LINE'.
.PP
.SH FILES
.TP
.I /etc/lcovrc
The system\-wide
.B lcov
configuration file.
.TP
.I ~/.lcovrc
The individual per\-user configuration file.
.PP
.SH SEE ALSO
.BR lcov (1),
.BR genhtml (1),
.BR geninfo (1),
.BR gcov (1)
Summary: A graphical GCOV front-end
Name: lcov
Version: 1.13
Release: 1
License: GPLv2+
Group: Development/Tools
URL: http://ltp.sourceforge.net/coverage/lcov.php
Source0: http://downloads.sourceforge.net/ltp/%{name}-%{version}.tar.gz
BuildRoot: %{_tmppath}/%{name}-%{version}-root
BuildArch: noarch
Requires: perl >= 5.8.8
%description
LCOV is a graphical front-end for GCC's coverage testing tool gcov. It collects
gcov data for multiple source files and creates HTML pages containing the
source code annotated with coverage information. It also adds overview pages
for easy navigation within the file structure.
%prep
%setup -q -n %{name}-%{version}
%build
exit 0
%install
rm -rf $RPM_BUILD_ROOT
make install DESTDIR=$RPM_BUILD_ROOT PREFIX=/usr CFG_DIR=/etc
%clean
rm -rf $RPM_BUILD_ROOT
%files
%defattr(-,root,root)
/usr/bin/*
/usr/share/man/man*/*
%config /etc/*
%changelog
* Mon Aug 22 2016 Peter Oberparleiter (Peter.Oberparleiter@de.ibm.com)
- updated "make install" call to work with PREFIX Makefile changes
* Mon May 07 2012 Peter Oberparleiter (Peter.Oberparleiter@de.ibm.com)
- added dependency on perl 5.8.8 for >>& open mode support
* Wed Aug 13 2008 Peter Oberparleiter (Peter.Oberparleiter@de.ibm.com)
- changed description + summary text
* Mon Aug 20 2007 Peter Oberparleiter (Peter.Oberparleiter@de.ibm.com)
- fixed "Copyright" tag
* Mon Jul 14 2003 Peter Oberparleiter (Peter.Oberparleiter@de.ibm.com)
- removed variables for version/release to support source rpm building
- added initial rm command in install section
* Mon Apr 7 2003 Peter Oberparleiter (Peter.Oberparleiter@de.ibm.com)
- implemented variables for version/release
* Fri Oct 18 2002 Peter Oberparleiter (Peter.Oberparleiter@de.ibm.com)
- created initial spec file
include common.mak
TESTDIRS := $(sort $(patsubst %/,%,$(dir $(wildcard */Makefile))))
help: info
info:
echo "Available make targets:"
echo " test : perform self-tests"
echo " clean : remove all temporary files"
echo ""
echo "Available make variables:"
echo " SIZE : specify size of test data (small, medium, large)"
echo " V : specify level of verbosity (0, 1, 2)"
test:
for TEST in $(TESTDIRS) ; do \
make -C $$TEST test ; \
done
clean:
rm -rf *.info *.counts test.log src/
for TEST in $(TESTDIRS) ; do \
make -C $$TEST clean ; \
done
.PHONY: help info test clean
function elapsed_to_ms()
{
local ELAPSED=$1
local IFS=:.
local MS
set -- $ELAPSED
if [ $# -eq 3 ] ; then
let MS=${3#0}*10+${2#0}*1000+$1*60000
else
let MS=${4#0}*10+${3#0}*1000+${2#0}*60000+$1*3600000
fi
echo $MS
}
function t_timestamp()
{
date +"%Y-%m-%d %H:%M:%S %z"
}
function t_marker()
{
echo
echo "======================================================================"
}
function t_detail()
{
local KEY=$1
local VALUE=$2
local DOTS=" ............"
printf "%-.12s: %s\n" "$KEY$DOTS" "$VALUE"
}
function t_announce()
{
local TESTNAME="$1"
printf "$BOLD%-.30s$RESET " "$TESTNAME .............................."
t_marker >> "$LOGFILE"
t_detail "DATE" "$(t_timestamp)" >> "$LOGFILE"
t_detail "TESTNAME" "$TESTNAME" >> "$LOGFILE"
}
function t_result()
{
local COLOR="$1"
local TEXT="$2"
printf "[$COLOR$TEXT$RESET]"
}
function t_pass()
{
local TESTNAME="$1"
t_result "$GREEN" "pass"
echo "pass $TESTNAME" >> "$COUNTFILE"
}
function t_fail()
{
local TESTNAME="$1"
t_result "$RED" "fail"
echo "fail $TESTNAME" >> "$COUNTFILE"
}
function t_kill()
{
local TESTNAME="$1"
t_result "$RED" "kill"
echo "fail $TESTNAME" >> "$COUNTFILE"
}
function t_skip()
{
local TESTNAME="$1"
t_result "$BLUE" "skip"
echo "skip $TESTNAME" >> "$COUNTFILE"
}
function t_indent()
{
sed -e 's/^/ /'
}
LOGFILE="$TOPDIR/test.log"
COUNTFILE="$TOPDIR/test.counts"
TIMEFILE="$TOPDIR/test.time"
if [ -t 1 ] ; then
RED="\e[31m"
GREEN="\e[32m"
BLUE="\e[34m"
BOLD="\e[1m"
DEFAULT="\e[39m"
RESET="\e[0m"
fi
#!/usr/bin/perl
#
# Copyright IBM Corp. 2017
#
# Usage: mkinfo <config_file> [-o <output_dir>] [--seed <seed>]
# [<key>=<value>...]
#
# Create a fake lcov code coverage data file and optionally the corresponding
# source tree. DATA_FILE contains all specifications for creating the data
# file. Directives can be overridden using KEY=VALUE specifications with KEY
# being in the form SECTION.KEY. SEED specifies the number used to initialize
# the pseudo random number generator.
#
# Example:
# mkinfo profiles/small -o src files.numfiles=12
#
use strict;
use warnings;
use Getopt::Long;
use Cwd qw(abs_path getcwd);
use File::Path qw(make_path);
use File::Basename;
use Data::Dumper;
my $MAX_TAKEN = 1000;
my $use_colors = -t STDIN;
my $BOLD = $use_colors ? "\033[1m" : "";
my $RESET = $use_colors ? "\033[0m" : "";
sub usage()
{
print(<<EOF)
Usage: $0 <config_file> [-o <output_dir>] [--seed <seed>] [<key>=<value>...]
Create a fake lcov code coverage data file and optionally the corresponding
source tree. DATA_FILE contains all specifications for creating the data
file. Directives can be overridden using KEY=VALUE specifications with KEY
being in the form SECTION.KEY. SEED specifies the number used to initialize
the pseudo random number generator.
Example:
$0 profiles/small -o src files.numfiles=12
EOF
}
sub read_config($)
{
my ($filename) = @_;
my $fd;
my %config;
my $section;
open($fd, "<", $filename) or die("Could not open $filename: $!\n");
while (my $line = <$fd>) {
my ($key, $value);
$line =~ s/(^\s*|\s*$)//g;
next if ($line eq "" || $line =~ /^#/);
if ($line =~ /^\[\s*(\S+)\s*]$/) {
$section = $1;
next;
}
if ($line !~ /^(\S+)\s*=\s*(.*)$/) {
die("$filename:$.: Unknown line format: $line\n");
}
($key, $value) = ($1, $2);
if (!defined($section)) {
die("$filename:$.: Directive outside of section\n");
}
$config{$section}->{$1} = $2;
}
close($fd);
return \%config;
}
sub apply_config($$)
{
my ($config, $directive) = @_;
for my $dir (@$directive) {
if ($dir !~ /^([^\.]+)\.([^=]+)=(.*)$/) {
die("Unknown directive format: $dir\n");
}
$config->{$1}->{$2} = $3;
}
}
sub get_value($$;$)
{
my ($config, $dir, $default) = @_;
my ($section, $key, $value);
if ($dir !~ /^([^\.]+)\.([^=]+)$/) {
die("$0: Internal error: Unknown key format: $key\n");
}
($section, $key) = ($1, $2);
$value = $config->{$section}->{$key};
if (!defined($value)) {
if (!defined($default)) {
die("$0: Missing config value for $dir\n");
}
$value = $default;
}
return $value;
}
sub get_int($$;$$$)
{
my ($config, $dir, $default, $min, $max) = @_;
my $value = get_value($config, $dir, $default);
if ($value !~ /^\d+$/) {
die("$0: Config value $dir must be an integer: $value\n");
}
$value = int($value);
if (defined($min) && $value < $min) {
die("$0: Config value $dir is too low (min $min): $value\n");
}
if (defined($max) && $value > $max) {
die("$0: Config value $dir is too high (max $max): $value\n");
}
return int($value);
}
sub get_list($$;$)
{
my ($config, $dir, $default) = @_;
my $value = get_value($config, $dir, $default);
my @list = split(/\s+/, $value);
return \@list;
}
sub randlist($)
{
my ($list) = @_;
return "" if (!@$list);
return $list->[int(rand(scalar(@$list)))];
}
sub randbool()
{
return int(rand(2));
}
# Reduce LIST to PERCENTAGE of its former size.
sub reduce_list_per($$)
{
my ($list, $percentage) = @_;
my $remove;
$remove = int((100 - $percentage) * scalar(@$list) / 100);
for (my $i = 0; $i < $remove; $i++) {
splice(@$list, int(rand(scalar(@$list))), 1);
}
}
# Reduce LIST to NUM items.
sub reduce_list_num($$)
{
my ($list, $num) = @_;
my $remove;
$remove = scalar(@$list) - $num;
for (my $i = 0; $i < $remove; $i++) {
splice(@$list, int(rand(scalar(@$list))), 1);
}
}
sub _gen_filename($$)
{
my ($c, $root) = @_;
my $ltop = get_list($c, "files.top", "");
my $lsub = get_list($c, "files.sub", "");
my $lsubsub = get_list($c, "files.subsub", "");
my $lprefix = get_list($c, "files.prefix");
my $lsuffix = get_list($c, "files.suffix", "");
my $lext = get_list($c, "files.ext");
my ($top, $sub, $subsub, $prefix, $suffix, $ext) =
("", "", "", "", "", "");
my $filename = "";
$top = randlist($ltop) if (randbool());
$sub = randlist($lsub) if (randbool());
$subsub = randlist($lsubsub) if (randbool());
$prefix = randlist($lprefix);
$suffix = randlist($lsuffix) if (randbool());
$ext = randlist($lext);
$filename = $root;
$filename .= "/".$top if ($top ne "");
$filename .= "/".$sub if ($sub ne "");
$filename .= "/".$subsub if ($subsub ne "");
$filename .= "/".$prefix;
$filename .= "_".$suffix if ($suffix ne "");
$filename .= $ext;
$filename =~ s#^//#/#;
return $filename;
}
sub gen_filename($$$)
{
my ($c, $root, $filenames) = @_;
my $filename;
do {
$filename = _gen_filename($c, $root);
} while ($filenames->{$filename});
$filenames->{$filename} = 1;
return $filename;
}
sub gen_lines($$)
{
my ($c, $length) = @_;
my @lines = 1 .. $length;
my $percent = get_int($c, "lines.instrumented", undef, 0, 100);
reduce_list_per(\@lines, $percent);
return \@lines;
}
sub gen_fnname($$)
{
my ($c, $hash) = @_;
my $lverb = get_list($c, "functions.verb");
my $ladj = get_list($c, "functions.adj", "");
my $lnoun = get_list($c, "functions.noun", "");
my ($verb, $adj, $noun) = ("", "", "");
my $fnname;
$verb = randlist($lverb);
$adj = randlist($ladj) if (randbool());
$noun = randlist($lnoun) if (randbool());
$fnname = $verb;
$fnname .= "_".$adj if ($adj ne "");
$fnname .= "_".$noun if ($noun ne "");
if (exists($hash->{$fnname})) {
my $i = 2;
while (exists($hash->{$fnname.$i})) {
$i++;
}
$fnname .= $i;
}
$hash->{$fnname} = 1;
return $fnname;
}
sub gen_functions($$)
{
my ($c, $lines) = @_;
my @fnlines;
my @functions;
my %names;
my $percent = get_int($c, "functions.perinstrumented", undef, 0, 100);
@fnlines = @$lines;
reduce_list_per(\@fnlines, $percent);
foreach my $fnline (@fnlines) {
push(@functions, [ $fnline, gen_fnname($c, \%names) ]);
}
return \@functions;
}
# Returns a value distribution object. This object can be used to randomly
# choose one element from a list of elements with a given relative distribution.
#
# dist: [ sumprob, probs]
# sumprob: Sum of all probabilities
# probs: [ prob1, prob2, ... ]
# prob: [ num, x ]
# num: Value
sub get_dist($$;$)
{
my ($c, $dir, $default) = @_;
my $list = get_list($c, $dir, $default);
my $sumprob = 0;
my @probs;
foreach my $spec (@$list) {
my ($n, $p);
if ($spec =~ /^(\d+):(\d+)$/) {
($n, $p) = ($1, $2);
} elsif ($spec =~ /^(\d+)$/) {
$n = $1;
$p = 1;
} else {
die("$0: Config value $dir must be a distribution ".
"list (a:p1 b:p2 ...)\n");
}
$sumprob += $p;
push(@probs, [ $n, $sumprob ]);
}
return [ $sumprob, \@probs ];
}
sub rand_dist($)
{
my ($dist) = @_;
my ($sumprob, $probs) = @$dist;
my $r = int(rand($sumprob));
foreach my $prob (@$probs) {
my ($num, $x) = @$prob;
return $num if ($r < $x);
}
die("Internal error: Incomplete distribution list\n");
}
sub gen_branches($$)
{
my ($c, $lines) = @_;
my $percent = get_int($c, "branches.perinstrumented", undef, 0, 100);
my @allblocks = @{get_list($c, "branches.blocks", "0")};
my $branchdist = get_dist($c, "branches.branchdist", "2");
my @brlines;
my @branches;
@brlines = @$lines;
reduce_list_per(\@brlines, $percent);
foreach my $brline (@brlines) {
my @blocks = @allblocks;
my $numblocks = int(rand(scalar(@blocks))) + 1;
reduce_list_num(\@blocks, $numblocks);
foreach my $block (@blocks) {
my $numbranch = rand_dist($branchdist);
for (my $branch = 0; $branch < $numbranch; $branch++) {
push(@branches, [ $brline, $block, $branch]);
}
}
}
return \@branches;
}
sub gen_filesrc($)
{
my ($c) = @_;
my ($length, $lines, $functions, $branches);
my $do_ln = get_int($c, "lines.enabled");
my $do_fn = get_int($c, "functions.enabled");
my $do_br = get_int($c, "branches.enabled");
$length = 1 + int(rand(get_int($c, "lines.maxlines")));
$lines = gen_lines($c, $length);
$functions = gen_functions($c, $lines) if ($do_fn);
$branches = gen_branches($c, $lines) if ($do_br);
return [ $length, $lines, $functions, $branches ];
}
# Generate fake source tree.
#
# returns: [ files, numlns, numfns, numbrs ]
# files: filename -> filesrc
# filesrc: [ length, lines, functions, branches ]
# length: Total number of lines in file
#
# lines: [ line1, line2, ... ]
#
# functions: [ fn1, fn2, ... ]
# fn: [ fnline, fnname ]
# fnline: Starting line of function
# fnname: Function name
#
# branches: [ brdata1, brdata2, ...]
# brdata: [ brline, block, branch ]
# brline: Line number containing branches
# block: Block ID
# branch: Branch ID
#
sub gen_src($$)
{
my ($c, $root) = @_;
my %files;
my $numfiles = get_int($c, "files.numfiles");
my %filenames;
my ($numlns, $numfns, $numbrs) = (0, 0, 0);
for (my $i = 0; $i < $numfiles; $i++) {
my $filename = gen_filename($c, $root, \%filenames);
my $filesrc = gen_filesrc($c);
$files{$filename} = $filesrc;
$numlns += scalar(@{$filesrc->[1]}) if (defined($filesrc->[1]));
$numfns += scalar(@{$filesrc->[2]}) if (defined($filesrc->[2]));
$numbrs += scalar(@{$filesrc->[3]}) if (defined($filesrc->[3]));
}
return [ \%files, $numlns, $numfns, $numbrs ];
}
sub write_src($)
{
my ($src) = @_;
my ($files, $numlns, $numfns, $numbrs) = @$src;
foreach my $filename (sort(keys(%{$files}))) {
my $filesrc = $files->{$filename};
my $length = $filesrc->[0];
my $dir = dirname($filename);
my $fd;
if (!-d $dir) {
make_path($dir) or
die("Could not create directory $dir\n");
}
open($fd, ">", $filename) or
die("Could not create file $filename: $!\n");
for (my $i = 0; $i < $length; $i++) {
print($fd "\n");
}
close($fd);
}
}
sub write_branches($$$$)
{
my ($fd, $branches, $brhits, $iref) = @_;
my ($found, $hit) = (0, 0);
# Line coverage data
foreach my $brdata (@$branches) {
my $brhit = $brhits->[$$iref++];
my ($brline, $block, $branch) = @$brdata;
$found++;
$hit++ if ($brhit ne "-" && $brhit > 0);
print($fd "BRDA:$brline,$block,$branch,$brhit\n");
}
if ($found > 0) {
print($fd "BRF:$found\n");
print($fd "BRH:$hit\n");
}
}
sub write_lines($$$$)
{
my ($fd, $lines, $lnhist, $iref) = @_;
my ($found, $hit) = (0, 0);
# Line coverage data
foreach my $line (@$lines) {
my $lnhit = $lnhist->[$$iref++];
$found++;
$hit++ if ($lnhit > 0);
print($fd "DA:$line,$lnhit\n");
}
print($fd "LF:$found\n");
print($fd "LH:$hit\n");
}
sub write_functions($$$$)
{
my ($fd, $functions, $fnhits, $iref) = @_;
my ($found, $hit) = (0, 0);
# Function coverage data
foreach my $fn (@$functions) {
my ($fnline, $fnname) = @$fn;
print($fd "FN:$fnline,$fnname\n");
}
foreach my $fn (@$functions) {
my ($fnline, $fnname) = @$fn;
my $fnhit = $fnhits->[$$iref++];
$found++;
$hit++ if ($fnhit > 0);
print($fd "FNDA:$fnhit,$fnname\n");
}
print($fd "FNF:$found\n");
print($fd "FNH:$hit\n");
}
sub write_filesrc($$$$$)
{
my ($c, $fd, $filesrc, $hits, $iter) = @_;
my ($length, $lines, $functions, $branches) = @$filesrc;
my $do_ln = get_int($c, "lines.enabled");
my $do_fn = get_int($c, "functions.enabled");
my $do_br = get_int($c, "branches.enabled");
write_functions($fd, $functions, $hits->[1], \$iter->[1]) if ($do_fn);
write_branches($fd, $branches, $hits->[2], \$iter->[2]) if ($do_br);
write_lines($fd, $lines, $hits->[0], \$iter->[0]) if ($do_ln);
}
sub write_info($$$$)
{
my ($c, $filename, $src, $hits) = @_;
my $files = $src->[0];
my $fd;
my %iters;
foreach my $testname (keys(%{$hits})) {
$iters{$testname} = [ 0, 0, 0 ];
}
open($fd, ">", $filename) or die("Could not create $filename: $!\n");
foreach my $filename (sort(keys(%{$files}))) {
my $filesrc = $files->{$filename};
foreach my $testname (sort(keys(%{$hits}))) {
my $testhits = $hits->{$testname};
my $iter = $iters{$testname};
print($fd "TN:$testname\n");
print($fd "SF:$filename\n");
write_filesrc($c, $fd, $filesrc, $testhits, $iter);
print($fd "end_of_record\n");
}
}
close($fd);
}
sub get_hit_found($)
{
my ($list) = @_;
my ($hit, $found) = (0, 0);
foreach my $e (@$list) {
$hit++ if ($e ne "-" && $e > 0);
$found++;
}
return ($hit, $found);
}
sub write_counts($$)
{
my ($filename, $hits) = @_;
my $fd;
my (@tlnhits, @tfnhits, @tbrhits);
foreach my $testname (keys(%{$hits})) {
my $testhits = $hits->{$testname};
my ($lnhits, $fnhits, $brhits) = @$testhits;
for (my $i = 0; $i < scalar(@$lnhits); $i++) {
$tlnhits[$i] += $lnhits->[$i];
}
for (my $i = 0; $i < scalar(@$fnhits); $i++) {
$tfnhits[$i] += $fnhits->[$i];
}
for (my $i = 0; $i < scalar(@$brhits); $i++) {
my $h = $brhits->[$i];
$h = 0 if ($h eq "-");
$tbrhits[$i] += $h;
}
}
open($fd, ">", $filename) or die("Could not create $filename: $!\n");
print($fd join(" ", get_hit_found(\@tlnhits), get_hit_found(\@tfnhits),
get_hit_found(\@tbrhits))."\n");
close($fd);
}
# A branch hit value for a block that was not hit must be "-". A branch hit
# value for a block that was hit cannot be "-", but must be "0" if not hit.
sub sanitize_brhits($)
{
my ($brhits) = @_;
my $block_hit = 0;
foreach my $brhit_ref (@$brhits) {
if ($$brhit_ref ne "-" && $$brhit_ref > 0) {
$block_hit = 1;
last;
}
}
foreach my $brhit_ref (@$brhits) {
if (!$block_hit) {
$$brhit_ref = "-";
} elsif ($$brhit_ref eq "-") {
$$brhit_ref = 0;
}
}
}
# Ensure coverage rate interdependencies are met
sub sanitize_hits($$)
{
my ($src, $hits) = @_;
my $files = $src->[0];
foreach my $hits (values(%{$hits})) {
my $brhits = $hits->[2];
my $i = 0;
foreach my $filename (sort(keys(%{$files}))) {
my $filesrc = $files->{$filename};
my $branches = $filesrc->[3];
my $lastblock;
my $lastline;
my @blist;
foreach my $brdata (@$branches) {
my ($brline, $block, $branch) = @$brdata;
if (!defined($lastblock) ||
$block != $lastblock ||
$brline != $lastline) {
sanitize_brhits(\@blist);
@blist = ();
$lastblock = $block;
$lastline = $brline;
}
push(@blist, \$brhits->[$i++]);
}
sanitize_brhits(\@blist);
}
}
}
# Generate random coverage data
#
# returns: testname -> testhits
# testhits: [ lnhits, fnhits, brhits ]
# lnhits: [ ln1hit, ln2hit, ... ]
# lnhit: Number of times a line was hit by a specific test
# fnhits: [ fn1hit, fn2hit, ... ]
# fnhit: Number of times a function was hit by a specific test
# brhits: [ br1hit, br2hit, ... ]
# brhit: Number of times a branch was hit by a specific test
sub gen_hits($$)
{
my ($c, $src) = @_;
my (@lnhits, @fnhits, @brhits);
my ($files, $numlns, $numfns, $numbrs) = @$src;
my $testnames = get_list($c, "tests.names", "");
my %hits;
$testnames = [ "" ] if (!@$testnames);
foreach my $testname (@$testnames) {
my (@lnhits, @fnhits, @brhits);
for (my $i = 0; $i < $numlns; $i++) {
push(@lnhits, 1 + int(rand($MAX_TAKEN)));
}
for (my $i = 0; $i < $numfns; $i++) {
push(@fnhits, 1 + int(rand($MAX_TAKEN)));
}
for (my $i = 0; $i < $numbrs; $i++) {
push(@brhits, 1 + int(rand($MAX_TAKEN)));
}
$hits{$testname} = [ \@lnhits, \@fnhits, \@brhits ];
}
sanitize_hits($src, \%hits);
return \%hits;
}
# Return a hash containing RATE percent of indices [0..NUM-1].
sub gen_filter($$)
{
my ($num, $rate) = @_;
my @list = (0 .. ($num - 1));
my %hash;
reduce_list_per(\@list, $rate);
foreach my $i (@list) {
$hash{$i} = 1;
}
return \%hash;
}
# Zero all entries in LIST identified by the indices in FILTER.
sub zero_by_filter($$)
{
my ($list, $filter) = @_;
foreach my $i (keys(%{$filter})) {
$list->[$i] = 0;
}
}
# Add a random number of indices between [0..NUM-1] to FILTER.
sub widen_filter($$)
{
my ($filter, $num) = @_;
my @list;
for (my $i = 0; $i < $num; $i++) {
push(@list, $i) if (!exists($filter->{$i}));
}
reduce_list_per(\@list, int(rand(101)));
foreach my $i (@list) {
$filter->{$i} = 1;
}
}
# Zero coverage data in HITS until the combined coverage rates reach the
# specified RATEs.
sub reduce_hits($$$$$)
{
my ($src, $hits, $lnrate, $fnrate, $brrate) = @_;
my ($files, $numlns, $numfns, $numbrs) = @$src;
my ($lnfilter, $fnfilter, $brfilter);
$lnfilter = gen_filter($numlns, 100 - $lnrate);
$fnfilter = gen_filter($numfns, 100 - $fnrate);
$brfilter = gen_filter($numbrs, 100 - $brrate);
foreach my $testhits (values(%{$hits})) {
my ($lnhits, $fnhits, $brhits) = @$testhits;
zero_by_filter($lnhits, $lnfilter);
zero_by_filter($fnhits, $fnfilter);
zero_by_filter($brhits, $brfilter);
# Provide some variation between tests
widen_filter($lnfilter, $numlns);
widen_filter($fnfilter, $numfns);
widen_filter($brfilter, $numbrs);
}
sanitize_hits($src, $hits);
}
sub zero_list($)
{
my ($list) = @_;
foreach my $i (@$list) {
$i = 0;
}
}
# Zero all coverage in HITS.
sub zero_hits($$)
{
my ($src, $hits) = @_;
foreach my $testhits (values(%{$hits})) {
my ($lnhits, $fnhits, $brhits) = @$testhits;
zero_list($lnhits);
zero_list($fnhits);
zero_list($brhits);
}
sanitize_hits($src, $hits);
}
# Distribute items from LIST to A and B depending on whether the index for
# an item is found in FILTER.
sub split_by_filter($$$$)
{
my ($list, $filter, $a, $b) = @_;
for (my $i = 0; $i < scalar(@$list); $i++) {
if (exists($filter->{$i})) {
push(@$a, $list->[$i]);
push(@$b, 0);
} else {
push(@$a, 0);
push(@$b, $list->[$i]);
}
}
}
sub split_hits($$$)
{
my ($c, $src, $hits) = @_;
my ($files, $numlns, $numfns, $numbrs) = @$src;
my ($lnsplit, $fnsplit, $brsplit);
my (%a, %b);
$lnsplit = gen_filter($numlns, int(rand(101)));
$fnsplit = gen_filter($numfns, int(rand(101)));
$brsplit = gen_filter($numbrs, int(rand(101)));
foreach my $testname (keys(%{$hits})) {
my $testhits = $hits->{$testname};
my ($lnhits, $fnhits, $brhits) = @$testhits;
my (@lnhitsa, @fnhitsa, @brhitsa);
my (@lnhitsb, @fnhitsb, @brhitsb);
split_by_filter($lnhits, $lnsplit, \@lnhitsa, \@lnhitsb);
split_by_filter($fnhits, $fnsplit, \@fnhitsa, \@fnhitsb);
split_by_filter($brhits, $brsplit, \@brhitsa, \@brhitsb);
$a{$testname} = [ \@lnhitsa, \@fnhitsa, \@brhitsa ];
$b{$testname} = [ \@lnhitsb, \@fnhitsb, \@brhitsb ];
}
sanitize_hits($src, \%a);
sanitize_hits($src, \%b);
return (\%a, \%b);
}
sub plural($$$)
{
my ($num, $sing, $plur) = @_;
return $num <= 1 ? $sing : $plur;
}
sub print_intro($)
{
my ($c) = @_;
my $numtests = scalar(@{get_list($c, "tests.names")});
my $numfiles = get_int($c, "files.numfiles");
$numtests = 1 if ($numtests < 1);
print($BOLD."Creating coverage files ($numtests ".
plural($numtests, "test", "tests").", $numfiles ".
plural($numfiles, "source file", "source files").")\n".$RESET);
}
sub main()
{
my $opt_help;
my $opt_output;
my $opt_configfile;
my $opt_seed = 0;
my $c;
my $src;
my $hits;
my $root;
my $enum;
my ($a, $b);
# Parse options
if (!GetOptions("output|o=s" => \$opt_output,
"seed=s" => \$opt_seed,
"help|h" => \$opt_help,
)) {
print(STDERR "Use $0 --help to get usage information\n");
exit(2);
}
if ($opt_help) {
usage();
exit(0);
}
$opt_configfile = shift(@ARGV);
if (!defined($opt_configfile)) {
print(STDERR "Please specify a config file\n");
exit(2);
}
if (defined($opt_output)) {
if (! -d $opt_output) {
mkdir($opt_output) or
die("$0: Could not create directory ".
"$opt_output: $!\n");
}
$root = abs_path($opt_output)
} else {
$root = "/";
}
srand($opt_seed);
# Get config
$c = read_config($opt_configfile);
apply_config($c, \@ARGV) if (@ARGV);
print_intro($c);
# Show lines on STDOUT without newline
$| = 1;
# Create source tree
print(" Source tree ......... ");
$src = gen_src($c, $root);
# Write out source code if requested
write_src($src) if (defined($opt_output));
print("done (");
print($src->[1]." lines, ");
print($src->[2]." functions, ");
print($src->[3]." branches)\n");
# Write out full-coverage data files
print(" Full coverage ....... ");
$hits = gen_hits($c, $src);
write_info($c, "full.info", $src, $hits);
write_counts("full.counts", $hits);
print("done\n");
# Write out data files with target coverage rates
print(" Target coverage ..... ");
reduce_hits($src, $hits, get_int($c, "lines.covered"),
get_int($c, "functions.covered"),
get_int($c, "branches.covered"));
write_info($c, "target.info", $src, $hits);
write_counts("target.counts", $hits);
print("done\n");
# Write out partial data files
print(" Partial coverage .... ");
($a, $b) = split_hits($c, $src, $hits);
write_info($c, "part1.info", $src, $a);
write_counts("part1.counts", $a);
write_info($c, "part2.info", $src, $b);
write_counts("part2.counts", $b);
print("done\n");
# Write out zero-coverage data files
print(" Zero coverage ....... ");
zero_hits($src, $hits);
write_info($c, "zero.info", $src, $hits);
write_counts("zero.counts", $hits);
print("done\n");
}
main();
exit(0);
#!/usr/bin/perl
#
# Copyright IBM Corp. 2017
#
# Usage: norminfo <coverage-data-file> [<multiplier>]
#
# Normalize coverage data file (ensure stable order), perform some sanity
# checks, and apply optional multiplier to execution counts.
#
use strict;
use warnings;
sub ferr($$$)
{
my ($pos, $filename, $msg) = @_;
if (defined($pos)) {
$pos .= ":";
} else {
$pos = "";
}
die("$0:$filename:$pos $msg");
}
sub print_sorted($$$)
{
my ($fd, $info, $multi) = @_;
my (%fn, %fns, %fnda, %brda, %da);
my ($fnf, $fnh, $brf, $brh, $lf, $lh);
while (my $line = <$fd>) {
$line =~ s/(^\s*|\s*$)//g;
if ($line =~ /^end_of_record$/) {
last;
} elsif ($line =~ /^FN:(\d+),(.*)$/) {
my ($lineno, $fnname) = ($1, $2);
if (exists($fn{$lineno})) {
ferr($., $info, "Duplicate FN: entry\n");
}
$fn{$lineno} = $fnname;
if (exists($fns{$fnname})) {
ferr($., $info, "Duplicate function name\n");
}
$fns{$fnname} = $lineno;
} elsif ($line =~ /^FNDA:(\d+),(.*)$/) {
my ($count, $fnname) = ($1, $2);
if (exists($fnda{$fnname})) {
ferr($., $info, "Duplicate FNDA: entry\n");
}
$fnda{$fnname} = int($count * $multi);
} elsif ($line =~ /^FNF:(\d+)$/) {
if (defined($fnf)) {
ferr($., $info, "Duplicate FNF: entry\n");
}
$fnf = $1;
} elsif ($line =~ /^FNH:(\d+)$/) {
if (defined($fnh)) {
ferr($., $info, "Duplicate FNH: entry\n");
}
$fnh = $1;
} elsif ($line =~ /^BRDA:(\d+),(\d+),(\d+),(\d+|-)$/) {
my ($lineno, $block, $branch, $count) = ($1, $2, $3, $4);
if (exists($brda{$lineno}->{$block}->{$branch})) {
ferr($., $info, "Duplicate BRDA: entry\n");
}
$count = int($count * $multi) if ($count ne "-");
$brda{$lineno}->{$block}->{$branch} = $count;
} elsif ($line =~ /^BRF:(\d+)$/) {
if (defined($brf)) {
ferr($., $info, "Duplicate BRF: entry\n");
}
$brf = $1;
} elsif ($line =~ /^BRH:(\d+)$/) {
if (defined($brh)) {
ferr($., $info, "Duplicate BRH: entry\n");
}
$brh = $1;
} elsif ($line =~ /^DA:(\d+),(\d+)$/) {
my ($lineno, $count) = ($1, $2);
if (exists($da{$lineno})) {
ferr($., $info, "Duplicate FNDA: entry\n");
}
$da{$lineno} = int($count * $multi);
} elsif ($line =~ /^LF:(\d+)$/) {
if (defined($lf)) {
ferr($., $info, "Duplicate LF: entry\n");
}
$lf = $1;
} elsif ($line =~ /^LH:(\d+)$/) {
if (defined($lh)) {
ferr($., $info, "Duplicate LH: entry\n");
}
$lh = $1;
} else {
ferr($., $info, "Unknown line: $line\n");
}
}
# FN:<line>,<fnname>
foreach my $lineno (sort({ $a <=> $b } keys(%fn))) {
my $fnname = $fn{$lineno};
print("FN:$lineno,$fnname\n");
}
# FNDA:<counts>,<fnname>
foreach my $fnname (keys(%fnda)) {
if (!exists($fns{$fnname})) {
ferr(undef, $info, "FNDA entry without FN: $fnname\n");
}
}
foreach my $fnname (sort({ $fns{$a} <=> $fns{$b} } keys(%fnda))) {
my $count = $fnda{$fnname};
print("FNDA:$count,$fnname\n");
}
# FNF:<counts>
print("FNF:$fnf\n") if (defined($fnf));
# FNH:<counts>
if (defined($fnh)) {
$fnh = 0 if ($multi == 0);
print("FNH:$fnh\n");
}
# BRDA:<line>,<block>,<branch>,<count>
foreach my $lineno (sort({ $a <=> $b } keys(%brda))) {
my $blocks = $brda{$lineno};
foreach my $block (sort({ $a <=> $b } keys(%{$blocks}))) {
my $branches = $blocks->{$block};
foreach my $branch (sort({ $a <=> $b }
keys(%{$branches}))) {
my $count = $branches->{$branch};
$count = "-" if ($multi == 0);
print("BRDA:$lineno,$block,$branch,$count\n");
}
}
}
# BRF:<counts>
print("BRF:$brf\n") if (defined($brf));
# BRH:<counts>
if (defined($brh)) {
$brh = 0 if ($multi == 0);
print("BRH:$brh\n");
}
# DA:<line>,<counts>
foreach my $lineno (sort({ $a <=> $b } keys(%da))) {
my $count = $da{$lineno};
print("DA:$lineno,$count\n");
}
# LF:<counts>
print("LF:$lf\n") if (defined($lf));
# LH:<count>
if (defined($lh)) {
$lh = 0 if ($multi == 0);
print("LH:$lh\n");
}
}
sub main()
{
my $infofile = $ARGV[0];
my $multi = $ARGV[1];
# info: testname -> files
# files: infofile -> data
# data: [ starting offset, starting line ]
my %info;
my $fd;
my $tn = "";
my %allfiles;
$multi = 1 if (!defined($multi));
if (!defined($infofile)) {
$infofile = "standard input";
warn("$0: Reading data from standard input\n");
open($fd, "<&STDIN") or
die("$0: Could not duplicated stdin: $!\n");
} else {
open($fd, "<", $infofile) or
die("$0: Could not open $infofile: $!\n");
}
# Register starting positions of data sets
while (my $line = <$fd>) {
if ($line =~ /^TN:(.*)$/) {
$tn = $1;
} elsif ($line =~ /^SF:(.*)$/) {
my $sf = $1;
my $pos = tell($fd);
die("$0: Could not get file position: $!\n")
if ($pos == -1);
if (exists($info{$tn}->{$sf})) {
ferr($., $infofile,
"Duplicate entry for $tn:$sf\n");
}
$info{$tn}->{$sf} = [ $pos, $. ];
$allfiles{$sf} = 1;
}
}
# Print data sets in normalized order
foreach my $filename (sort(keys(%allfiles))) {
foreach my $testname (sort(keys(%info))) {
my $pos = $info{$testname}->{$filename};
my ($cpos, $lpos) = @$pos;
next if (!defined($pos));
if (seek($fd, $cpos, 0) != 1) {
die("$0: Could not seek in $infofile: $!\n");
}
printf("TN:$testname\n");
printf("SF:$filename\n");
$. = $lpos;
print_sorted($fd, $infofile, $multi);
printf("end_of_record\n");
}
}
foreach my $testname (sort(keys(%info))) {
my $files = $info{$testname};
foreach my $filename (sort(keys(%{$files}))) {
}
}
close($fd);
}
main();
exit(0);
#!/bin/bash
#
# Copyright IBM Corp. 2017
#
# Usage: test_run <testname> <cmdline>
#
# Announce a test case, run it, and record the resulting output in the
# test log file. Must be run after testsuite_init.
#
TOPDIR=$(realpath $(dirname $0)/..) && source "$TOPDIR/bin/common"
EXCERPTLEN=10
TESTNAME="$1"
shift
TIME=$(which time 2>/dev/null)
if [ ! -z "$TIME" ] ; then
TIME="$TIME -v -o $TIMEFILE"
if ! $TIME true 2>/dev/null ; then
TIME=""
fi
fi
t_announce "$TESTNAME"
let POS=$(stat -c %s "$LOGFILE")+1
t_detail "COMMAND" "\"$*\"" >>"$LOGFILE"
t_detail "OUTPUT" "" >>"$LOGFILE"
# Run command
$TIME bash -c "$*" 2>&1 | t_indent >>"$LOGFILE"
RC=$?
# Evaluate output of time command
ELAPSED=
RESIDENT=
SIGNAL=
if [ ! -z "$TIME" ] ; then
while read LINE ; do
case "$LINE" in
"Command terminated by signal"*) SIGNAL=${LINE##* } ;;
"Elapsed"*) ELAPSED=$(elapsed_to_ms ${LINE##* }) ;;
"Maximum resident"*) RESIDENT=${LINE##* } ;;
"Exit status"*) RC=${LINE##* } ;;
esac
done < "$TIMEFILE"
rm -f "$TIMEFILE"
fi
t_detail "EXITCODE" "$RC" >>"$LOGFILE"
# Show result
if [ $RC -eq 0 -a -z "$SIGNAL" ] ; then
RESULT="pass"
t_pass "$TESTNAME"
else
if [ -z "$SIGNAL" ] ; then
RESULT="fail"
t_fail "$TESTNAME"
else
RESULT="kill"
t_kill "$TESTNAME"
fi
fi
if [ ! -z "$SIGNAL" ] ; then
t_detail "SIGNAL" "$SIGNAL" >>"$LOGFILE"
fi
if [ ! -z "$ELAPSED" ] ; then
echo -n " (time $(($ELAPSED/1000)).$(($ELAPSED%1000/100))s, "
echo "elapsed $TESTNAME $ELAPSED" >> "$COUNTFILE"
fi
if [ ! -z "$RESIDENT" ] ; then
echo -n "mem $(($RESIDENT/1024)).$((($RESIDENT%1024)/100))MB)"
echo "resident $TESTNAME $RESIDENT" >> "$COUNTFILE"
fi
echo
# Show log excerpt on failure or if requested
if [ $RC -ne 0 -o "$V" == "1" ] ; then
LEN=$(tail -c "+$POS" "$LOGFILE" | wc -l)
if [ "$LEN" -gt "$EXCERPTLEN" -a "$V" != "1" ] ; then
tail -c "+$POS" "$LOGFILE" | head -n $EXCERPTLEN | t_indent
let LEN=$LEN-$EXCERPTLEN
echo " ..."
echo " Skipping $LEN more lines (see $LOGFILE)"
else
tail -c "+$POS" "$LOGFILE" | t_indent
fi
fi
# Log more details
[ ! -z "$ELAPSED" ] && t_detail "TIME" "${ELAPSED}ms" >>"$LOGFILE"
[ ! -z "$RESIDENT" ] && t_detail "MEM" "${RESIDENT}kB" >>"$LOGFILE"
t_detail "RESULT" "$RESULT" >> "$LOGFILE"
#!/bin/bash
#
# Copyright IBM Corp. 2017
#
# Usage: test_skip <testname> <reason>
#
# Announce and record that a single test case was skipped, including an
# optional reason text. Must be run after testsuite_init.
#
TOPDIR=$(realpath $(dirname $0)/..) && source "$TOPDIR/bin/common"
TESTNAME="$1"
REASON="${*:2}" ; [ -z "$REASON" ] && REASON="<no reason given>"
t_announce "$TESTNAME"
t_skip "$TESTNAME"
echo
t_detail "REASON" "$REASON" >>"$LOGFILE"
t_detail "REASON" "$REASON" | t_indent
#!/bin/bash
#
# Copyright IBM Corp. 2017
#
# Usage: testsuite_exit
#
# Announce end of test suite and show aggregate results.
#
TOPDIR=$(realpath $(dirname $0)/..) && source "$TOPDIR/bin/common"
echo "end_time $(date +%s.%N)" >>"$COUNTFILE"
SUCCESS=0
FAILED=0
SKIPPED=0
TOTAL_TIME=0
TOTAL_MEM=0
HAVE_EXT=0
# Get results
while read LINE ; do
set -- $LINE
case "$1" in
start_time) START_TIME=$2 ;;
end_time) END_TIME=$2 ;;
pass) let SUCCESS=$SUCCESS+1 ;;
fail) let FAILED=$FAILED+1 ;;
skip) let SKIPPED=$SKIPPED+1 ;;
elapsed) let TOTAL_TIME=$TOTAL_TIME+$3 ; HAVE_EXT=1 ;;
resident) let TOTAL_MEM=$TOTAL_MEM+$3 ; HAVE_EXT=1 ;;
esac
done < "$COUNTFILE"
exec 3>&1
exec >>"$LOGFILE" 2>&1
t_marker
t_detail "DATE" "$(t_timestamp)"
let TOTAL=$SUCCESS+$SKIPPED+$FAILED
t_detail "EXECUTED" "$TOTAL"
t_detail "PASSED" "$SUCCESS"
t_detail "FAILED" "$FAILED"
t_detail "SKIPPED" "$SKIPPED"
[ $HAVE_EXT -eq 1 ] && t_detail "TIME" "${TOTAL_TIME}ms"
[ $HAVE_EXT -eq 1 ] && t_detail "MEM" "${TOTAL_MEM}kB"
TOTAL_TIME=$(($TOTAL_TIME/1000)).$(($TOTAL_TIME%1000/100))
TOTAL_MEM=$(($TOTAL_MEM/1024)).$((($TOTAL_MEM%1024)/100))
TOTAL="$BOLD$TOTAL tests executed$RESET"
PASS="$SUCCESS passed"
FAIL="$FAILED failed"
SKIP="$SKIPPED skipped"
TIME="time ${TOTAL_TIME}s"
MEM="mem ${TOTAL_MEM}MB"
[ "$SUCCESS" -gt 0 ] && PASS="$GREEN$PASS$DEFAULT"
[ "$FAILED" -gt 0 ] && FAIL="$RED$FAIL$DEFAULT"
[ "$SKIPPED" -gt 0 ] && SKIP="$BLUE$SKIP$DEFAULT"
echo -en "$TOTAL, $PASS, $FAIL, $SKIP$RESET" >&3
[ $HAVE_EXT -eq 1 ] && echo -n " ($TIME, $MEM)" >&3
echo >&3
echo "Result log stored in $LOGFILE" >&3
if [ "$FAILED" -gt 0 ] ; then
exit 1
fi
exit 0
#!/bin/bash
#
# Copyright IBM Corp. 2017
#
# Usage: testsuite_init
#
# Announce start of test suite and prepare log files.
#
TOPDIR=$(realpath $(dirname $0)/..) && source "$TOPDIR/bin/common"
echo -e $BOLD"Starting tests"$RESET
echo "start_time $(date +%s.%N)" >"$COUNTFILE"
exec >"$LOGFILE" 2>&1
t_detail "DATE" "$(t_timestamp)"
t_detail "LCOV" ""
lcov --version 2>&1 | t_indent
t_detail "GCOV" ""
gcov --version 2>&1 | t_indent
t_detail "CPUINFO" ""
t_indent < /proc/cpuinfo
t_detail "MEMINFO" ""
t_indent < /proc/meminfo
TOPDIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
TESTDIR := $(dir $(realpath $(firstword $(MAKEFILE_LIST))))
PARENTDIR := $(dir $(patsubst %/,%,$(TOPDIR)))
RELDIR := $(TESTDIR:$(PARENTDIR)%=%)
ZEROINFO := $(TOPDIR)zero.info
ZEROCOUNTS := $(TOPDIR)zero.counts
FULLINFO := $(TOPDIR)full.info
FULLCOUNTS := $(TOPDIR)full.counts
TARGETINFO := $(TOPDIR)target.info
TARGETCOUNTS := $(TOPDIR)target.counts
PART1INFO := $(TOPDIR)part1.info
PART1COUNTS := $(TOPDIR)part1.counts
PART2INFO := $(TOPDIR)part2.info
PART2COUNTS := $(TOPDIR)part2.counts
INFOFILES := $(ZEROINFO) $(FULLINFO) $(TARGETINFO) $(PART1INFO) $(PART2INFO)
COUNTFILES := $(ZEROCOUNTS) $(FULLCOUNTS) $(TARGETCOUNTS) $(PART1COUNTS) \
$(PART2COUNTS)
LCOVRC := $(TOPDIR)lcovrc
LCOVFLAGS := --config-file $(LCOVRC)
SIZE := small
CC := gcc
export LCOV := lcov $(LCOVFLAGS)
export GENHTML := genhtml $(LCOVFLAGS)
export PATH := $(TOPDIR)/../bin:$(TOPDIR)/bin:$(PATH)
export LANG := C
all: prepare init test exit
init:
testsuite_init
exit:
testsuite_exit
prepare: $(INFOFILES) $(COUNTFILES)
clean: clean_common
clean_common:
echo " CLEAN $(patsubst %/,%,$(RELDIR))"
$(INFOFILES) $(COUNTFILES):
cd $(TOPDIR) && mkinfo profiles/$(SIZE) -o src/
ifneq ($(V),2)
.SILENT:
endif
.PHONY: all init exit prepare clean clean_common
include ../common.mak
GENHTML_TEST := ./genhtml_test
TESTS := genhtml_output_zero genhtml_output_full genhtml_output_target \
genhtml_output_part1 genhtml_output_part2 genhtml_output_combined
test: $(TESTS)
genhtml_output_zero:
@test_run genhtml_output_zero $(GENHTML) $(ZEROINFO) -o out_zero/
genhtml_output_full:
@test_run genhtml_output_full $(GENHTML) $(FULLINFO) -o out_full/
genhtml_output_target:
@test_run genhtml_output_target $(GENHTML) $(TARGETINFO) -o out_target/
genhtml_output_part1:
@test_run genhtml_output_part1 $(GENHTML) $(PART1INFO) -o out_part1/
genhtml_output_part2:
@test_run genhtml_output_part2 $(GENHTML) $(PART2INFO) -o out_part2/
genhtml_output_combined: genhtml_output_target
@test_run genhtml_output_combined $(GENHTML_TEST) $(TARGETINFO) $(PART1INFO) $(PART2INFO)
clean:
rm -rf out_*/
.PHONY: test $(TESTS) clean
#!/bin/bash
#
# Copyright IBM Corp. 2017
#
# Usage: genhtml_test <ref-file> <file1> [<file2>...]
#
# Compare genhtml output of a reference coverage data file with that of
# a combination of multiple files.
#
function die()
{
echo "Error: $@" >&2
exit 1
}
GENHTMLFLAGS="-t title"
REFFILE=$1
shift
if [ -z "$REFFILE" -o -z "$*" ] ; then
echo "Usage: $0 <ref-file> <file1> [<file2>...]" >&2
exit 2
fi
OUTREF="out_$(basename $REFFILE .info)"
OUTCOMBINED="out_combined"
$GENHTML $GENHTMLFLAGS "$REFFILE" -o "$OUTREF" || \
die "Could not generate HTML for reference file"
$GENHTML $GENHTMLFLAGS "$@" -o "$OUTCOMBINED" || \
die "Could not generate HTML for combined files"
diff -ur "$OUTREF" "$OUTCOMBINED" -I "headerValue" || \
die "Mismatch in generated output"
include ../common.mak
ADDTEST := ./add_test
TESTS := lcov_add_zero lcov_add_zero2 lcov_add_full lcov_add_full2 \
lcov_add_part lcov_add_part2 lcov_add_concatenated4
test: $(TESTS)
lcov_add_zero:
# Add single zero coverage file - output should be same as input
test_run lcov_add_zero $(ADDTEST) 1 "$(ZEROINFO)" "$(ZEROINFO)"
lcov_add_zero2:
# Add two zero coverage files - output should be same as input
test_run lcov_add_zero2 $(ADDTEST) 1 "$(ZEROINFO)" "$(ZEROINFO)" "$(ZEROINFO)"
lcov_add_full:
# Add single 100% coverage file - output should be same as input
test_run lcov_add_full $(ADDTEST) 1 "$(FULLINFO)" "$(FULLINFO)"
lcov_add_full2:
# Add two 100% coverage file and reduce counts to 1/2 - output should
# be same as input
test_run lcov_add_full2 $(ADDTEST) 0.5 "$(FULLINFO)" "$(FULLINFO)" "$(FULLINFO)"
lcov_add_part:
# Add single coverage file with random coverage rate - output should
# be same as input
test_run lcov_add_part $(ADDTEST) 1 "$(PART1INFO)" "$(PART1INFO)"
lcov_add_part2:
# Add two coverage files that were split from target file - output
# should be same as target file
test_run lcov_add_part2 $(ADDTEST) 1 "$(TARGETINFO)" "$(PART1INFO)" "$(PART2INFO)"
lcov_add_concatenated4:
# Add coverage file that consists of 4 concatenation of target files
# and reduce counts to 1/4 - output should be the same as input
cat $(TARGETINFO) $(TARGETINFO) $(TARGETINFO) $(TARGETINFO) >concatenated.info
test_run lcov_add_concatenated4 $(ADDTEST) 0.25 $(TARGETINFO) concatenated.info
clean:
rm -f *.info
.PHONY: test $(TESTS) clean
#!/bin/bash
#
# Copyright IBM Corp. 2017
#
# Usage: add_test <multiplier> <reference_file> <add_file> [<add_file>...]
#
# Add multiple coverage data files, normalize the output and multiply counts
# with multiplier. Compare against reference file. Report deviations.
#
MULTI=$1
REFFILE=$2
shift 2
ADD=
for INFO in $* ; do
ADD="$ADD -a $INFO"
done
if [ -z "$MULTI" -o -z "$REFFILE" -o -z "$ADD" ] ; then
echo "Usage: $0 <multiplier> <reference_file> <add_file> [<add_file>...]" >&2
exit 1
fi
OUTFILE="add_"$(basename "$REFFILE")
SORTFILE="norm_$OUTFILE"
set -x
echo "Adding files..."
if ! $LCOV $ADD -o "$OUTFILE" ; then
echo "Error: lcov returned with non-zero exit code $?" >&2
exit 1
fi
echo "Normalizing result..."
if ! norminfo "$OUTFILE" "$MULTI" > "$SORTFILE" ; then
echo "Error: Normalization of lcov result file failed" >&2
exit 1
fi
echo "Comparing with reference..."
if ! diff -u "$REFFILE" "$SORTFILE" ; then
echo "Error: Result of combination differs from reference file" >&2
exit 1
fi
include ../common.mak
test:
test_run lcov_diff_apply ./diff_test
clean:
make -C old clean
make -C new clean
rm -f *.info diff
#!/bin/bash
#
# Copyright IBM Corp. 2017
#
# Usage: diff_test
#
# Check lcov's diff function:
# - Compile two slightly different test programs
# - Run the programs and collect coverage data
# - Generate a patch containing the difference between the source code
# - Apply the patch to the coverage data
# - Compare the resulting patched coverage data file with the data from the
# patched source file
#
function die()
{
echo "Error: $@" >&2
exit 1
}
make -C old || die "Failed to compile old source"
make -C new || die "Failed to compile new source"
diff -u $PWD/old/prog.c $PWD/new/prog.c > diff
$LCOV --diff old/prog.info diff --convert-filenames -o patched.info -t bla || \
die "Failed to apply patch to coverage data file"
norminfo new/prog.info > new_normalized.info
norminfo patched.info > patched_normalized.info
sed -i -e 's/^TN:.*$/TN:/' patched_normalized.info
diff -u patched_normalized.info new_normalized.info || \
die "Mismatch in patched coverage data file"
echo "Patched coverage data file matches expected file"
prog.info:
include ../../common.mak
prog.info: prog.gcda
$(LCOV) -c -d . -o prog.info
prog.gcda: prog
./prog || true
prog: prog.c
$(CC) prog.c -o prog --coverage
clean:
rm -f prog prog.gcda prog.gcno prog.info
.PHONY: all clean
int fn(int x)
{
switch (x) {
case -1: return 0;
case 0: return 2;
case 2: return 3;
case 12: return 7;
default: return 255;
}
}
int fn2()
{
return 7;
}
int main(int argc, char *argv[])
{
if (argc > 1)
return fn(argc);
return fn2();
}
prog.info:
include ../../common.mak
prog.info: prog.gcda
$(LCOV) -c -d . -o prog.info
prog.gcda: prog
./prog || true
prog: prog.c
$(CC) prog.c -o prog --coverage
clean:
rm -f prog prog.gcda prog.gcno prog.info
.PHONY: all clean
int fn(int x)
{
switch (x) {
case -1: return 0;
case 0: return 2;
case 2: return 3;
case 12: return 7;
default: return 255;
}
}
int fn2()
{
return 7;
}
int main(int argc, char *argv[])
{
if (argc > 1)
return fn(argc);
return fn2();
}
include ../common.mak
test:
@test_run lcov_version lcov --version
@test_run lcov_help lcov --help
include ../common.mak
CHECK := ./check_counts
TESTS := lcov_summary_zero lcov_summary_full lcov_summary_target \
lcov_summary_part1 lcov_summary_part2 lcov_summary_concatenated \
lcov_summary_concatenated2
test: $(TESTS)
lcov_summary_zero:
# Compare output of lcov --summary with generated counts
test_run lcov_summary_zero $(CHECK) $(ZEROCOUNTS) $(ZEROINFO)
lcov_summary_full:
# Compare output of lcov --summary with generated counts
test_run lcov_summary_full $(CHECK) $(FULLCOUNTS) $(FULLINFO)
lcov_summary_target:
# Compare output of lcov --summary with generated counts
test_run lcov_summary_target $(CHECK) $(TARGETCOUNTS) $(TARGETINFO)
lcov_summary_part1:
# Compare output of lcov --summary with generated counts
test_run lcov_summary_part1 $(CHECK) $(PART1COUNTS) $(PART1INFO)
lcov_summary_part2:
# Compare output of lcov --summary with generated counts
test_run lcov_summary_part2 $(CHECK) $(PART2COUNTS) $(PART2INFO)
lcov_summary_concatenated:
# Compare output of lcov --summary with generated counts for a
# concatenated coverage data file
cat $(TARGETINFO) $(TARGETINFO) > concatenated.info
test_run lcov_summary_concatenated $(CHECK) $(TARGETCOUNTS) concatenated.info
lcov_summary_concatenated2:
# Compare output of lcov --summary with generated counts for a
# concatenated coverage data file (part1+part2=target)
cat $(PART1INFO) $(PART2INFO) > concatenated2.info
test_run lcov_summary_concatenated2 $(CHECK) $(TARGETCOUNTS) concatenated2.info
clean:
rm -f *.info
.PHONY: test $(TESTS) clean
#!/usr/bin/perl
#
# Copyright IBM Corp. 2017
#
# Usage: check_counts <counts_file> <coverage_data_file>
#
# Compare the output of "lcov --summary" for <coverage_data_file> with the
# coverage data counts specified in <counts_file>. This file has the following
# format (all in a single line):
#
# lnhit lnfound fnhit fnfound brhit brfound2
#
use strict;
use warnings;
sub do_cmp($$$)
{
my ($title, $a, $b) = @_;
if ($a == $b) {
print("$title: $a == $b\n");
return 0;
} else {
print("$title: $a != $b => mismatch!\n");
return 1;
}
}
my $lcov = $ENV{"LCOV"};
my ($counts, $info) = @ARGV;
my $fd;
my $cmdline;
my ($lnhit, $lnfound, $fnhit, $fnfound, $brhit, $brfound) = (0, 0, 0, 0, 0, 0);
my ($lnhit2, $lnfound2, $fnhit2, $fnfound2, $brhit2, $brfound2);
my $rc = 0;
die("$0: LCOV environment variable not defined\n") if (!defined($lcov));
if (!defined($counts) || !defined($info)) {
die("Usage: $0 <counts_file> <coverage_data_file>\n");
}
$cmdline = "$lcov --summary $info";
open($fd, "-|", $cmdline) or die("$0: Could not run $cmdline: $!\n");
while (<$fd>) {
($lnhit, $lnfound) = ($1, $2) if (/(\d+) of (\d+) lines/);
($fnhit, $fnfound) = ($1, $2) if (/(\d+) of (\d+) functions/);
($brhit, $brfound) = ($1, $2) if (/(\d+) of (\d+) branches/);
}
close($fd);
die("$0: Non-zero result code ($?) of command: $cmdline\n") if ($? != 0);
open($fd, "<", $counts) or die("$0: Could not open $counts: $!\n");
if (<$fd> !~ /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/) {
die("$0: Invalid count file: $counts\n");
}
($lnhit2, $lnfound2, $fnhit2, $fnfound2, $brhit2, $brfound2) =
($1, $2, $3, $4, $5, $6);
close($fd);
print("Comparing --summary output for $info and $counts:\n");
$rc |= do_cmp("line hit", $lnhit, $lnhit2);
$rc |= do_cmp("line found", $lnfound, $lnfound2);
$rc |= do_cmp("functions hit", $fnhit, $fnhit2);
$rc |= do_cmp("functions found", $fnfound, $fnfound2);
$rc |= do_cmp("branches hit", $brhit, $brhit2);
$rc |= do_cmp("branches found", $brfound, $brfound2);
exit($rc);
# lcovrc file used during tests
lcov_function_coverage = 1
lcov_branch_coverage = 1
# Profile of a large source code project. Use with mkinfo to generate fake test
# source code and coverage data.
[tests]
# List of test names
names = test1 test2
[files]
# Create this many files
numfiles = 500
# Generate paths from these components (top/sub/subsub/prefix_suffix.ext)
top = lib tools test bin img scripts
sub = build debug release include target sys config
subsub = work www utils gui info log basic
prefix = main misc report tune mem list
suffix = a b c top work proto final fast
ext = .c .h
[lines]
# Generate line coverage data
enabled = 1
# Line coverage rate
covered = 80
# Percentage of lines covered
instrumented = 80
# Maximum number of lines per file
maxlines = 2000
[functions]
# Generate function coverage data
enabled = 1
# Function coverage rate
covered = 60
# Percent of instrumented lines containing function definitions
perinstrumented = 10
# Generate function names from these components (verb_adj_noun)
verb = get set find read write stat add sub combine
adj = first last best min max avg
noun = bit byte file str num obj data
[branches]
# Generate branch coverage data
enabled = 1
# Branch coverage rate
covered = 20
# Percent of instrumented lines containing branches
perinstrumented = 5
# List of blocks to use
blocks = 0 4294967295
# Distribution of number of branches per block (num:probability)
branchdist = 2:50 3:25 5:20 100:5
# Profile of a medium-sized source code project. Use with mkinfo to generate
# fake test source code and coverage data.
[tests]
# List of test names
names = test1 test2 test3
[files]
# Create this many files
numfiles = 50
# Generate paths from these components (top/sub/subsub/prefix_suffix.ext)
top = lib tools test bin img scripts
sub = build debug release include target sys config
subsub = work www utils gui info log basic
prefix = main misc report tune mem list
suffix = a b c top work proto final fast
ext = .c .h
[lines]
# Generate line coverage data
enabled = 1
# Line coverage rate
covered = 80
# Percentage of lines covered
instrumented = 50
# Maximum number of lines per file
maxlines = 1000
[functions]
# Generate function coverage data
enabled = 1
# Function coverage rate
covered = 60
# Percent of instrumented lines containing function definitions
perinstrumented = 5
# Generate function names from these components (verb_adj_noun)
verb = get set find read write stat add sub combine
adj = first last best min max avg
noun = bit byte file str num obj data
[branches]
# Generate branch coverage data
enabled = 1
# Branch coverage rate
covered = 20
# Percent of instrumented lines containing branches
perinstrumented = 50
# List of blocks to use
blocks = 0 4294967295
# Distribution of number of branches per block (num:probability)
branchdist = 2:50 3:50
# Profile of a small source code project. Use with mkinfo to generate fake test
# source code and coverage data.
[tests]
# List of test names
names = test1 test2
[files]
# Create this many files
numfiles = 5
# Generate paths from these components (top/sub/subsub/prefix_suffix.ext)
top = lib tools test bin img scripts
sub = build debug release include target sys config
subsub = work www utils gui info log basic
prefix = main misc report tune mem list
suffix = a b c top work proto final fast
ext = .c .h
[lines]
# Generate line coverage data
enabled = 1
# Line coverage rate
covered = 80
# Percentage of lines covered
instrumented = 50
# Maximum number of lines per file
maxlines = 500
[functions]
# Generate function coverage data
enabled = 1
# Function coverage rate
covered = 60
# Percent of instrumented lines containing function definitions
perinstrumented = 5
# Generate function names from these components (verb_adj_noun)
verb = get set find read write stat add sub combine
adj = first last best min max avg
noun = bit byte file str num obj data
[branches]
# Generate branch coverage data
enabled = 1
# Branch coverage rate
covered = 20
# Percent of instrumented lines containing branches
perinstrumented = 50
# List of blocks to use
blocks = 0 4294967295
# Distribution of number of branches per block (num:probability)
branchdist = 2:50 3:45 50:5
......@@ -276,11 +276,10 @@
'xcode_settings':
{
'OTHER_CPLUSPLUSFLAGS': [
'-fprofile-instr-generate',
'-fcoverage-mapping'
'--coverage'
],
'OTHER_LDFLAGS': [
'-fprofile-instr-generate'
'--coverage'
]
}
}
......
#!/usr/bin/env bash
current_dir=${PWD##*/}
LCOV="./deps/lcov/bin/lcov"
GENHTML="./deps/lcov/bin/genhtml"
OBJECTS_DIR="./out/Release/obj.target/mediasoup-worker-test/"
HTML_REPORT_DIR="/tmp/mediasoup-worker-lcov-report"
COVERAGE_INFO="/tmp/mediasoup-worker-lcov-report.info"
if [ "${current_dir}" != "worker" ] ; then
echo ">>> [ERROR] $(basename $0) must be called from mediasoup/worker/ directory" >&2
exit 1
fi
echo ">>> [INFO] Clearing *.gcda files ..."
find ${OBJECTS_DIR} -name *.gcda -exec rm -rf {} \;
echo ">>> [INFO] running tests ..."
gulp test:worker
echo ">>> [INFO] generating coverage info file ..."
$LCOV --no-external --capture --directory ./ --output-file ${COVERAGE_INFO}
echo ">>> [INFO] removing tests from coverage info file ..."
$LCOV -r ${COVERAGE_INFO} "`pwd`/test/*" -o ${COVERAGE_INFO}
echo ">>> [INFO] removing deps from coverage info file ..."
$LCOV -r ${COVERAGE_INFO} "`pwd`/deps/*" -o ${COVERAGE_INFO}
echo ">>> [INFO] Clearing previous report data ..."
if [[ -d ${HTML_REPORT_DIR} ]] ; then
rm -rf ${HTML_REPORT_DIR}
else
mkdir ${HTML_REPORT_DIR}
fi
echo ">>> [INFO] Generating HTML report ..."
$GENHTML -o ${HTML_REPORT_DIR} ${COVERAGE_INFO}
echo ">>> [INFO] Clearing coverage info file ..."
rm ${COVERAGE_INFO}
if type "open" &> /dev/null; then
echo ">>> [INFO] opening HTML report ..."
open ${HTML_REPORT_DIR}/index.html
fi
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论