pax_global_header 0000666 0000000 0000000 00000000064 15057302234 0014513 g ustar 00root root 0000000 0000000 52 comment=65472541f74da213583535c8bb4fea831e875109
perfparser-65472541f74da213583535c8bb4fea831e875109/ 0000775 0000000 0000000 00000000000 15057302234 0020316 5 ustar 00root root 0000000 0000000 perfparser-65472541f74da213583535c8bb4fea831e875109/.gitignore 0000664 0000000 0000000 00000001067 15057302234 0022312 0 ustar 00root root 0000000 0000000 tests/auto/**/*.actual.txt
tests/auto/perfdata/fork_static_gcc/fork
tests/auto/perfdata/fork_static_gcc/perf.data.zstd
tests/auto/perfdata/vector_static_clang/perf.data
tests/auto/perfdata/vector_static_clang/vector_static_clang_v8.0.1
tests/auto/perfdata/vector_static_gcc/perf.data
tests/auto/perfdata/vector_static_gcc/perf.data.zstd
tests/auto/perfdata/vector_static_gcc/perf.lbr.data
tests/auto/perfdata/vector_static_gcc/vector_static_gcc_v9.1.0
tests/auto/perfdata/parallel_static_gcc/parallel_static_gcc
tests/auto/perfdata/parallel_static_gcc/perf.data.zstd
perfparser-65472541f74da213583535c8bb4fea831e875109/.gitreview 0000664 0000000 0000000 00000000122 15057302234 0022317 0 ustar 00root root 0000000 0000000 [gerrit]
host=codereview.qt-project.org
port=29418
project=qt-creator/perfparser
perfparser-65472541f74da213583535c8bb4fea831e875109/CMakeLists.txt 0000664 0000000 0000000 00000002535 15057302234 0023063 0 ustar 00root root 0000000 0000000 find_package(elfutils)
if (NOT elfutils_FOUND)
message(STATUS "PerfParser is disabled. Set ELFUTILS_INSTALL_DIR to enable it.")
return()
endif()
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
find_package(Zstd)
find_package(LibRustcDemangle)
set_package_properties(LibRustcDemangle PROPERTIES
DESCRIPTION "Demangling for Rust symbols, written in Rust."
PURPOSE "Demangling of Rust symbols"
URL "https://github.com/alexcrichton/rustc-demangle"
TYPE RUNTIME)
find_package(LibDDemangle)
set_package_properties(LibDDemangle PROPERTIES
DESCRIPTION "Demangling for D symbols, written in D."
PURPOSE "Demangling of D symbols"
URL "https://github.com/lievenhey/d_demangler"
TYPE RUNTIME)
add_definitions(-DQT_NO_CAST_FROM_ASCII
-DQT_NO_CAST_TO_ASCII
-DQT_USE_QSTRINGBUILDER
-DQT_NO_FOREACH)
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wcast-align -Wchar-subscripts -Wformat-security -Wno-long-long -Wpointer-arith -Wnon-virtual-dtor -Woverloaded-virtual")
# Make some warnings errors
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=return-type -Werror=init-self -Werror=undef")
endif()
add_subdirectory(app)
add_subdirectory(tests)
perfparser-65472541f74da213583535c8bb4fea831e875109/LICENSE.GPLv3 0000664 0000000 0000000 00000104513 15057302234 0022221 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
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
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
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 3 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, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program 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, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU 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. But first, please read
.
perfparser-65472541f74da213583535c8bb4fea831e875109/app/ 0000775 0000000 0000000 00000000000 15057302234 0021076 5 ustar 00root root 0000000 0000000 perfparser-65472541f74da213583535c8bb4fea831e875109/app/CMakeLists.txt 0000664 0000000 0000000 00000002302 15057302234 0023633 0 ustar 00root root 0000000 0000000 add_qtc_library(perfparser_lib STATIC
ALLOW_ASCII_CASTS
PUBLIC_DEPENDS
Qt::Core
Qt::Network
elfutils::dw
elfutils::elf
PUBLIC_INCLUDES ./
SOURCES
perfaddresscache.cpp
perfattributes.cpp perfattributes.h
perfheader.cpp perfheader.h
perffilesection.cpp perffilesection.h
perffeatures.cpp perffeatures.h
perfdata.cpp perfdata.h
perfunwind.cpp perfunwind.h
perfregisterinfo.cpp perfregisterinfo.h
perfstdin.cpp perfstdin.h
perfsymboltable.cpp perfsymboltable.h
perfelfmap.cpp perfelfmap.h
perfkallsyms.cpp perfkallsyms.h
perftracingdata.cpp perftracingdata.h
perfdwarfdiecache.cpp perfdwarfdiecache.h
perfeucompat.h
demangler.cpp demangler.h
)
if (Zstd_FOUND)
target_include_directories(perfparser_lib PUBLIC ${Zstd_INCLUDE_DIR})
target_link_libraries(perfparser_lib PUBLIC ${Zstd_LIBRARY})
set(HAVE_ZSTD 1)
endif()
if (HAVE_DWFL_GET_DEBUGINFOD_CLIENT)
target_link_libraries(perfparser_lib PRIVATE elfutils::debuginfod)
set(HAVE_DWFL_GET_DEBUGINFOD_CLIENT 1)
endif()
configure_file(config-perfparser.h.in config-perfparser.h)
add_qtc_executable(perfparser
DEPENDS
perfparser_lib
SOURCES
main.cpp
)
perfparser-65472541f74da213583535c8bb4fea831e875109/app/app.pro 0000664 0000000 0000000 00000002123 15057302234 0022376 0 ustar 00root root 0000000 0000000 #-------------------------------------------------
#
# Project created by QtCreator 2014-08-14T10:44:20
#
#-------------------------------------------------
QT = core network
CONFIG += c++11 console
CONFIG -= app_bundle
include(../paths.pri)
include(../elfutils.pri)
DESTDIR = $$PERFPARSER_APP_DESTDIR
target.path = $$PERFPARSER_APP_INSTALLDIR
INSTALLS += target
TARGET = perfparser
SOURCES += main.cpp \
perfaddresscache.cpp \
perfattributes.cpp \
perfheader.cpp \
perffilesection.cpp \
perffeatures.cpp \
perfdata.cpp \
perfunwind.cpp \
perfregisterinfo.cpp \
perfstdin.cpp \
perfsymboltable.cpp \
perfelfmap.cpp \
perfkallsyms.cpp \
perftracingdata.cpp \
perfdwarfdiecache.cpp
HEADERS += \
perfaddresscache.h \
perfattributes.h \
perfheader.h \
perffilesection.h \
perffeatures.h \
perfdata.h \
perfunwind.h \
perfregisterinfo.h \
perfstdin.h \
perfsymboltable.h \
perfelfmap.h \
perfkallsyms.h \
perftracingdata.h \
perfdwarfdiecache.h \
perfeucompat.h
OTHER_FILES += app.qbs
perfparser-65472541f74da213583535c8bb4fea831e875109/app/app.qbs 0000664 0000000 0000000 00000002331 15057302234 0022364 0 ustar 00root root 0000000 0000000 import qbs
import qbs.FileInfo
QtcTool {
name: "perfparser"
Depends { name: "qtc" }
Depends { name: "Qt.network" }
cpp.defines: base.filter(function(def) { return def != "QT_RESTRICTED_CAST_FROM_ASCII"; })
cpp.includePaths: project.includePaths
cpp.libraryPaths: project.libPaths
cpp.dynamicLibraries: ["dw", "elf"]
files: [
"main.cpp",
"demangler.cpp",
"demangler.h",
"perfaddresscache.cpp",
"perfaddresscache.h",
"perfattributes.cpp",
"perfattributes.h",
"perfheader.cpp",
"perfheader.h",
"perffilesection.cpp",
"perffilesection.h",
"perffeatures.cpp",
"perffeatures.h",
"perfdata.cpp",
"perfdata.h",
"perfunwind.cpp",
"perfunwind.h",
"perfregisterinfo.cpp",
"perfregisterinfo.h",
"perfstdin.cpp",
"perfstdin.h",
"perfsymboltable.cpp",
"perfsymboltable.h",
"perfelfmap.cpp",
"perfelfmap.h",
"perfkallsyms.cpp",
"perfkallsyms.h",
"perftracingdata.cpp",
"perftracingdata.h",
"perfdwarfdiecache.cpp",
"perfdwarfdiecache.h",
"perfeucompat.h"
]
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/config-perfparser.h.in 0000664 0000000 0000000 00000001747 15057302234 0025301 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2021 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author David Faure
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#cmakedefine01 HAVE_ZSTD
#cmakedefine01 HAVE_DWFL_GET_DEBUGINFOD_CLIENT
perfparser-65472541f74da213583535c8bb4fea831e875109/app/demangler.cpp 0000664 0000000 0000000 00000005453 15057302234 0023547 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2021 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Lieven Hey
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "demangler.h"
#include
#include
/* Demangler specification
* int demangler(const char* mangledSymbol, char* demangledBuffer, size_t bufferSize)
*
* size_t is platform dependent (4 bytes on 32 bit, 8 bytes on 64 bit)
* */
namespace {
bool startsWith(const char* string, const QByteArray& prefix) {
return strcmp(string, prefix.constData()) == 0;
}
}
Demangler::Demangler()
{
loadDemangleLib(QStringLiteral("rustc_demangle"), "rustc_demangle", QByteArrayLiteral("_R"));
loadDemangleLib(QStringLiteral("d_demangle"), "demangle_symbol", QByteArrayLiteral("_D"));
}
bool Demangler::demangle(const char *mangledSymbol, char *demangleBuffer, size_t demangleBufferLength)
{
// fast path, some languages (like rust since 1.37 or d) share a common prefix
// try these first
for (const auto& demangler : std::as_const(m_demanglers)) {
if (startsWith(mangledSymbol, demangler.prefix)) {
if (demangler.demangler(mangledSymbol, demangleBuffer, demangleBufferLength)) {
return true;
}
}
}
return std::any_of(m_demanglers.constBegin(), m_demanglers.constEnd(), [&](const auto& demangler) {
return demangler.demangler(mangledSymbol, demangleBuffer, demangleBufferLength);
});
}
void Demangler::loadDemangleLib(const QString &name, const char* function, const QByteArray& prefix)
{
QLibrary lib(name);
if (!lib.load()) {
qDebug("failed to load library %ls: %ls", qUtf16Printable(name), qUtf16Printable(lib.errorString()));
return;
}
const auto rawSymbol = lib.resolve(function);
if (!rawSymbol) {
qDebug("failed to resolve %s function in library %ls: %ls", function, qUtf16Printable(lib.fileName()),
qUtf16Printable(lib.errorString()));
return;
}
m_demanglers.push_back({prefix, reinterpret_cast(rawSymbol)});
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/demangler.h 0000664 0000000 0000000 00000002656 15057302234 0023216 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2021 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Lieven Hey
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#ifndef DEMANGLER_H
#define DEMANGLER_H
#include
class Demangler
{
public:
Demangler();
bool demangle(const char* mangledSymbol, char* demangleBuffer, size_t demangleBufferLength);
private:
void loadDemangleLib(const QString& name, const char* function, const QByteArray& prefix);
using demangler_t = int (*) (const char*, char *, size_t);
struct DemangleInfo {
QByteArray prefix;
demangler_t demangler;
};
QVector m_demanglers;
};
#endif // DEMANGLER_H
perfparser-65472541f74da213583535c8bb4fea831e875109/app/main.cpp 0000664 0000000 0000000 00000045607 15057302234 0022542 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfattributes.h"
#include "perfdata.h"
#include "perffeatures.h"
#include "perfheader.h"
#include "perfregisterinfo.h"
#include "perfstdin.h"
#include "perfunwind.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#ifdef Q_OS_LINUX
#include
#endif
#ifdef Q_OS_WIN
#include
#include
#endif
#include
enum ErrorCodes {
NoError,
TcpSocketError,
CannotOpen,
BadMagic,
HeaderError,
DataError,
MissingData,
InvalidOption,
BufferingError
};
class PerfTcpSocket : public QTcpSocket {
Q_OBJECT
public:
PerfTcpSocket(QString host, quint16 port);
void tryConnect();
public slots:
void processError(QAbstractSocket::SocketError error);
private:
QString host;
quint16 port = 0;
quint16 tries = 0;
};
void PerfTcpSocket::processError(QAbstractSocket::SocketError error)
{
if (error == QAbstractSocket::RemoteHostClosedError)
return;
qWarning() << "socket error" << error << errorString();
if (state() == QAbstractSocket::ConnectedState || tries > 10)
QCoreApplication::exit(TcpSocketError);
else
QTimer::singleShot(1 << tries, this, &PerfTcpSocket::tryConnect);
}
PerfTcpSocket::PerfTcpSocket(QString host, quint16 port)
: host(std::move(host))
, port(port)
{
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(this, &QAbstractSocket::errorOccurred, this, &PerfTcpSocket::processError);
#else
connect(this, QOverload::of(&QTcpSocket::error),
this, &PerfTcpSocket::processError);
#endif
connect(this, &QAbstractSocket::disconnected, this, &QIODevice::close);
}
void PerfTcpSocket::tryConnect()
{
++tries;
connectToHost(host, port, QIODevice::ReadOnly);
}
std::unique_ptr initOutfile(const QCommandLineParser& parser, const QCommandLineOption& output)
{
std::unique_ptr outfile;
if (parser.isSet(output)) {
outfile = std::make_unique(parser.value(output));
if (!outfile->open(QIODevice::WriteOnly))
QCoreApplication::exit(CannotOpen);
} else {
#ifdef Q_OS_WIN
_setmode(fileno(stdout), O_BINARY);
#endif
outfile = std::make_unique();
if (!outfile->open(stdout, QIODevice::WriteOnly))
QCoreApplication::exit(CannotOpen);
}
return outfile;
}
std::unique_ptr initInfile(const QCommandLineParser& parser, const QCommandLineOption& host,
const QCommandLineOption& port, const QCommandLineOption& input)
{
if (parser.isSet(host))
return std::make_unique(parser.value(host), parser.value(port).toUShort());
else if (parser.isSet(input))
return std::make_unique(parser.value(input));
#ifdef Q_OS_WIN
_setmode(fileno(stdin), O_BINARY);
#endif
return std::make_unique();
}
int main(int argc, char *argv[])
{
QCoreApplication::setApplicationName(QStringLiteral("perfparser"));
QCoreApplication::setApplicationVersion(QStringLiteral("10.0"));
QCoreApplication app(argc, argv);
if (qEnvironmentVariableIsSet("PERFPARSER_DEBUG_WAIT")) {
#ifdef Q_OS_LINUX
const auto pid = QCoreApplication::applicationPid();
qWarning("PERFPARSER_DEBUG_WAIT is set, halting perfparser.");
qWarning("Continue with \"kill -SIGCONT %lld\" or by attaching a debugger.", pid);
kill(static_cast<__pid_t>(pid), SIGSTOP);
#else
qWarning("PERFPARSER_DEBUG_WAIT is set, but this only works on linux. Ignoring.");
#endif
}
QCommandLineParser parser;
auto elfutilsVersion = QString::fromUtf8(dwfl_version(nullptr));
parser.setApplicationDescription(QStringLiteral("Perf data parser and unwinder.\nUsing elfutils version: %1").arg(elfutilsVersion));
parser.addHelpOption();
parser.addVersionOption();
QCommandLineOption input(QStringLiteral("input"),
QCoreApplication::translate("main", "Read perf data from instead of stdin."),
QStringLiteral("file"));
parser.addOption(input);
QCommandLineOption host(QStringLiteral("host"),
QCoreApplication::translate("main", "Read perf data from remote instead of stdin."),
QStringLiteral("host"));
parser.addOption(host);
QCommandLineOption port(QStringLiteral("port"),
QCoreApplication::translate("main",
"When reading from remote host, connect to (default: "
"9327)."),
QStringLiteral("port"), QStringLiteral("9327"));
parser.addOption(port);
QCommandLineOption output(QStringLiteral("output"),
QCoreApplication::translate("main", "Write b2qt data to instead of stdout."),
QStringLiteral("file"));
parser.addOption(output);
QCommandLineOption sysroot(
QStringLiteral("sysroot"),
QCoreApplication::translate("main", "Look for system libraries in (default: %1).").arg(QDir::rootPath()),
QStringLiteral("path"), QDir::rootPath());
parser.addOption(sysroot);
const auto defaultDebug = PerfUnwind::defaultDebugInfoPath();
QCommandLineOption debug(QStringLiteral("debug"),
QCoreApplication::translate("main",
"Look for debug information in . "
"You can specify multiple paths separated by ':'. "
"Relative paths are relative to the original file's path. "
"The default is: %1 .")
.arg(defaultDebug),
QStringLiteral("path"), defaultDebug);
parser.addOption(debug);
QCommandLineOption extra(
QStringLiteral("extra"),
QCoreApplication::translate("main", "Look for additional libraries in (default: .)."),
QStringLiteral("path"));
parser.addOption(extra);
QCommandLineOption appPath(
QStringLiteral("app"),
QCoreApplication::translate("main", "Look for application binary in (default: .)."),
QStringLiteral("path"));
parser.addOption(appPath);
const auto defaultArch = PerfRegisterInfo::defaultArchitecture();
QCommandLineOption arch(
QStringLiteral("arch"),
QCoreApplication::translate("main",
"Set the fallback architecture, in case the architecture is not "
"given in the data itself, to . "
"The default is: %1")
.arg(defaultArch),
QStringLiteral("arch"), defaultArch);
parser.addOption(arch);
const auto defaultKallsyms = PerfUnwind::defaultKallsymsPath();
QCommandLineOption kallsymsPath(QStringLiteral("kallsyms"),
QCoreApplication::translate("main",
"Path to kallsyms mapping to resolve kernel "
"symbols. The default is: %1 .")
.arg(defaultKallsyms),
QStringLiteral("path"), defaultKallsyms);
parser.addOption(kallsymsPath);
QCommandLineOption printStats(
QStringLiteral("print-stats"),
QCoreApplication::translate("main", "Print statistics instead of converting the data."));
parser.addOption(printStats);
QCommandLineOption bufferSize(
QStringLiteral("buffer-size"),
QCoreApplication::translate("main",
"Initial size of event buffer in kilobytes. This"
" influences how many events get buffered before they get"
" sorted by time and then analyzed. Increase this value when"
" your perf.data file was recorded with a large buffer value"
" (perf record -m). Pass 0 to buffer events until a"
" FINISHED_ROUND event is encountered. perfparser will switch to"
" automatic buffering by FINISHED_ROUND events if either the"
" data indicates that the tace was recorded with a version of"
" perf >= 3.17, or a FINISHED_ROUND event is encountered and no"
" time order violations have occurred before. When encountering"
" a time order violation, perfparser will switch back to dynamic"
" buffering using buffer-size and max-buffer-size."
" The default value is 32MB."),
QStringLiteral("buffer-size"), QString::number(1 << 15));
parser.addOption(bufferSize);
QCommandLineOption maxBufferSize(
QStringLiteral("max-buffer-size"),
QCoreApplication::translate("main",
"Maximum size of event buffer in kilobytes. perfparser"
" increases the size of the event buffer when time order"
" violations are detected. It will never increase it beyond this"
" value, though. The default value is 1GB"),
QStringLiteral("max-buffer-size"), QString::number(1 << 20));
parser.addOption(maxBufferSize);
QCommandLineOption maxFrames(
QStringLiteral("max-frames"),
QCoreApplication::translate("main",
"Maximum number of frames that will be unwound."
" Set the value to -1 to unwind as many frames as possible."
" Beware that this can then potentially lead to infinite loops "
" when the stack got corrupted. Default value is 64."),
QStringLiteral("max-frames"), QStringLiteral("64"));
parser.addOption(maxFrames);
QCommandLineOption customPerfMapPath(
QStringLiteral("perf-map-path"),
QCoreApplication::translate("main",
"Specify a custom path where perfparser should look for a perf-$pid.map file"),
QStringLiteral("perf-map-path"));
parser.addOption(customPerfMapPath);
parser.process(app);
auto outfile = initOutfile(parser, output);
auto infile = initInfile(parser, host, port, input);
bool ok = false;
uint targetEventBufferSize = parser.value(bufferSize).toUInt(&ok) * 1024;
if (!ok) {
qWarning() << "Failed to parse buffer-size argument. Expected unsigned integer, got:"
<< parser.value(bufferSize);
return InvalidOption;
}
uint maxEventBufferSize = parser.value(maxBufferSize).toUInt(&ok) * 1024;
if (!ok) {
qWarning() << "Failed to parse buffer-size argument. Expected unsigned integer, got:"
<< parser.value(maxBufferSize);
return InvalidOption;
}
int maxFramesValue = parser.value(maxFrames).toInt(&ok);
if (!ok) {
qWarning() << "Failed to parse max-frames argument. Expected integer, got:"
<< parser.value(maxFrames);
return InvalidOption;
}
PerfUnwind unwind(outfile.get(), parser.value(sysroot),
parser.isSet(debug) ? parser.value(debug) : parser.value(sysroot) + parser.value(debug),
parser.value(extra), parser.value(appPath),
parser.isSet(customPerfMapPath) ? parser.value(customPerfMapPath) : QString {},
parser.isSet(printStats));
unwind.setKallsymsPath(parser.isSet(kallsymsPath)
? parser.value(kallsymsPath)
: (parser.value(sysroot) + parser.value(kallsymsPath)));
unwind.setIgnoreKallsymsBuildId(parser.isSet(kallsymsPath));
unwind.setTargetEventBufferSize(targetEventBufferSize);
unwind.setMaxEventBufferSize(maxEventBufferSize);
unwind.setMaxUnwindFrames(maxFramesValue);
PerfHeader header(infile.get());
PerfAttributes attributes;
PerfFeatures features;
PerfData data(&unwind, &header, &attributes);
features.setArchitecture(parser.value(arch).toLatin1());
auto readFileHeader = [&]() {
const qint64 filePos = infile->pos();
if (!attributes.read(infile.get(), &header)) {
qWarning() << "Failed to read attributes";
QCoreApplication::exit(DataError);
return;
}
if (!features.read(infile.get(), &header)) {
qWarning() << "Failed to read features";
QCoreApplication::exit(DataError);
return;
}
infile->seek(filePos);
// first send features, as it may contain better event descriptions
if (header.hasFeature(PerfHeader::COMPRESSED) && !data.setCompressed(features.compressed())) {
QCoreApplication::exit(DataError);
return;
}
unwind.features(features);
const auto& attrs = attributes.attributes();
for (auto it = attrs.begin(), end = attrs.end(); it != end; ++it) {
unwind.attr(PerfRecordAttr(it.value(), {it.key()}));
}
};
auto readData = [&]() {
const QByteArray &featureArch = features.architecture();
unwind.setArchitecture(PerfRegisterInfo::archByName(featureArch));
if (unwind.architecture() == PerfRegisterInfo::ARCH_INVALID) {
qWarning() << "No information about CPU architecture found. Cannot unwind.";
QCoreApplication::exit(MissingData);
return;
}
data.setSource(infile.get());
QObject::connect(infile.get(), &QIODevice::aboutToClose, &data, &PerfData::finishReading);
QObject::connect(&data, &PerfData::finished, infile.get(), [&]() { infile->disconnect(); });
QObject::connect(infile.get(), &QIODevice::readyRead, &data, &PerfData::read);
if (infile->bytesAvailable() > 0)
data.read();
};
auto writeBytes = [](QIODevice *target, const char *data, qint64 length) {
qint64 pos = 0;
while (pos < length) {
const qint64 written = target->write(data + pos, length - pos);
if (written < 0)
return false;
pos += written;
}
return true;
};
std::unique_ptr tempfile;
auto bufferSequentialData = [&](){
QByteArray buffer(1 << 25, Qt::Uninitialized);
const qint64 read = infile->read(buffer.data(), buffer.length());
if (read < 0) {
qWarning() << "Failed to read from input.";
QCoreApplication::exit(BufferingError);
return;
}
if (!writeBytes(tempfile.get(), buffer.data(), read)) {
qWarning() << "Failed to write buffer file.";
QCoreApplication::exit(BufferingError);
return;
}
};
QObject::connect(&header, &PerfHeader::finished, &app, [&]() {
unwind.setByteOrder(static_cast(header.byteOrder()));
if (!header.isPipe()) {
if (infile->isSequential()) {
qWarning() << "Reading a non-pipe perf.data from a stream requires buffering.";
tempfile = std::make_unique();
if (!tempfile->open(QIODevice::ReadWrite)) {
qWarning() << "Failed to open buffer file.";
QCoreApplication::exit(BufferingError);
return;
}
// We've checked this when parsing the header.
Q_ASSERT(header.size() <= std::numeric_limits::max());
const QByteArray fakeHeader(static_cast(header.size()), 0);
if (!writeBytes(tempfile.get(), fakeHeader.data(), fakeHeader.length())) {
qWarning() << "Failed to write fake header to buffer file.";
QCoreApplication::exit(BufferingError);
return;
}
QObject::connect(infile.get(), &QIODevice::readyRead, bufferSequentialData);
QObject::connect(infile.get(), &QIODevice::aboutToClose, [&]() {
infile->disconnect();
std::swap(infile, tempfile);
if (!infile->reset()) {
qWarning() << "Cannot reset buffer file.";
QCoreApplication::exit(BufferingError);
return;
}
readFileHeader();
readData();
});
if (infile->bytesAvailable() > 0)
bufferSequentialData();
} else {
readFileHeader();
readData();
}
} else {
readData();
}
});
QObject::connect(&header, &PerfHeader::error, []() {
QCoreApplication::exit(HeaderError);
});
QObject::connect(&data, &PerfData::finished, []() {
QCoreApplication::exit(NoError);
});
QObject::connect(&data, &PerfData::error, []() {
QCoreApplication::exit(DataError);
});
if (parser.isSet(host)) {
auto* socket = static_cast(infile.get());
socket->tryConnect();
} else {
if (!infile->open(QIODevice::ReadOnly))
return CannotOpen;
if (qobject_cast(infile.get())) // We don't get readyRead then ...
QTimer::singleShot(0, &header, &PerfHeader::read);
}
return QCoreApplication::exec();
}
#include "main.moc"
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfaddresscache.cpp 0000664 0000000 0000000 00000013263 15057302234 0025075 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfaddresscache.h"
#include "perfdwarfdiecache.h"
#include
namespace {
quint64 relativeAddress(const PerfElfMap::ElfInfo& elf, quint64 addr)
{
Q_ASSERT(elf.isValid());
const auto elfAddr = elf.baseAddrOrFallback();
Q_ASSERT(elfAddr <= addr);
Q_ASSERT((elf.addr + elf.length) > addr);
return addr - elfAddr;
}
}
PerfAddressCache::AddressCacheEntry PerfAddressCache::find(const PerfElfMap::ElfInfo& elf, quint64 addr,
OffsetAddressCache *invalidAddressCache) const
{
if (elf.isValid() && (elf.addr + elf.length) > addr)
return m_cache.value(elf.originalPath).value(relativeAddress(elf, addr));
else
return invalidAddressCache->value(addr);
}
void PerfAddressCache::cache(const PerfElfMap::ElfInfo& elf, quint64 addr,
PerfAddressCache::AddressCacheEntry entry,
OffsetAddressCache *invalidAddressCache)
{
if (elf.isValid() && (elf.addr + elf.length) > addr)
m_cache[elf.originalPath][relativeAddress(elf, addr)] = entry;
else
(*invalidAddressCache)[addr] = entry;
}
static bool operator<(const PerfAddressCache::SymbolCacheEntry &lhs, const PerfAddressCache::SymbolCacheEntry &rhs)
{
return lhs.offset < rhs.offset;
}
static bool operator==(const PerfAddressCache::SymbolCacheEntry &lhs, const PerfAddressCache::SymbolCacheEntry &rhs)
{
return lhs.offset == rhs.offset && lhs.size == rhs.size;
}
bool PerfAddressCache::hasSymbolCache(const QByteArray &filePath) const
{
return m_symbolCache.contains(filePath);
}
PerfAddressCache::SymbolCacheEntry PerfAddressCache::findSymbol(const QByteArray& filePath, quint64 relAddr)
{
auto &symbols = m_symbolCache[filePath];
auto it =
std::lower_bound(symbols.begin(), symbols.end(), relAddr,
[](const PerfAddressCache::SymbolCacheEntry& lhs, quint64 addr) { return lhs.value < addr; });
// demangle symbols on demand instead of demangling all symbols directly
// hopefully most of the symbols we won't ever encounter after all
auto lazyDemangle = [](PerfAddressCache::SymbolCacheEntry& entry) {
if (!entry.demangled) {
entry.symname = demangle(entry.symname);
entry.demangled = true;
}
return entry;
};
if (it != symbols.end() && it->value == relAddr)
return lazyDemangle(*it);
if (it == symbols.begin())
return {};
--it;
if (it->value <= relAddr && (it->value + it->size > relAddr || (it->size == 0))) {
return lazyDemangle(*it);
}
return {};
}
void PerfAddressCache::setSymbolCache(const QByteArray &filePath, SymbolCache cache)
{
/*
* use stable_sort to produce results that are comparable to what addr2line would
* return when we have entries like this in the symtab:
*
* 000000000045a130 l F .text 0000000000000033 .hidden __memmove_avx_unaligned
* 000000000045a180 l F .text 00000000000003d8 .hidden __memmove_avx_unaligned_erms
* 000000000045a180 l F .text 00000000000003d8 .hidden __memcpy_avx_unaligned_erms
* 000000000045a130 l F .text 0000000000000033 .hidden __memcpy_avx_unaligned
*
* here, addr2line would always find the first entry. we want to do the same
*/
std::stable_sort(cache.begin(), cache.end());
cache.erase(std::unique(cache.begin(), cache.end()), cache.end());
m_symbolCache[filePath] = cache;
}
static bool isMappingSymbol(const char* sym, PerfRegisterInfo::Architecture arch)
{
switch (arch) {
case PerfRegisterInfo::ARCH_AARCH64:
return strncmp(sym, "$x", 2) == 0;
case PerfRegisterInfo::ARCH_ARM:
return strncmp(sym, "$a", 2) == 0 || strncmp(sym, "$t", 2) == 0;
// TODO: Add cases for RISC-V and CSKY when supported, see:
// https://github.com/llvm/llvm-project/blob/de93f7ed0d615060735ad15e720f2497ed1d2468/llvm/include/llvm/Object/ELFObjectFile.h#L817
default:
return false;
}
}
PerfAddressCache::SymbolCache PerfAddressCache::extractSymbols(Dwfl_Module* module, quint64 elfStart,
PerfRegisterInfo::Architecture arch)
{
PerfAddressCache::SymbolCache cache;
const auto numSymbols = dwfl_module_getsymtab(module);
for (int i = 0; i < numSymbols; ++i) {
GElf_Sym sym;
GElf_Addr symAddr;
const auto symbol = dwfl_module_getsym_info(module, i, &sym, &symAddr, nullptr, nullptr, nullptr);
if (symbol && !isMappingSymbol(symbol, arch)) {
const quint64 start = alignedAddress(sym.st_value, arch == PerfRegisterInfo::ARCH_ARM);
cache.append({symAddr - elfStart, start, sym.st_size, symbol});
}
}
return cache;
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfaddresscache.h 0000664 0000000 0000000 00000007433 15057302234 0024544 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#ifndef PERFADDRESSCACHE_H
#define PERFADDRESSCACHE_H
#include
#include
#include "perfelfmap.h"
#include "perfregisterinfo.h"
#include
class PerfAddressCache
{
public:
static quint64 symbolAddress(quint64 addr, bool isArmArch)
{
// For dwfl API call we need the raw pointer into symtab, so we need to adjust ip.
return (!isArmArch || (addr & 1)) ? addr : addr + 1;
}
static quint64 alignedAddress(quint64 addr, bool isArmArch)
{
// Adjust addr back. The symtab entries are 1 off for all practical purposes.
return (isArmArch && (addr & 1)) ? addr - 1 : addr;
}
struct AddressCacheEntry
{
AddressCacheEntry(int locationId = -1, bool isInterworking = false)
: locationId(locationId)
, isInterworking(isInterworking)
{}
bool isValid() const { return locationId >= 0; }
int locationId;
bool isInterworking;
};
using OffsetAddressCache = QHash;
struct SymbolCacheEntry
{
SymbolCacheEntry(quint64 offset = 0, quint64 value = 0, quint64 size = 0, const QByteArray &symname = {})
: offset(offset)
, value(value)
, size(size)
, symname(symname)
{}
bool isValid() const { return !symname.isEmpty(); }
// adjusted/absolute st_value, see documentation of the `addr` arg in `dwfl_module_getsym_info`
quint64 offset;
// unadjusted/relative st_value
quint64 value;
quint64 size;
QByteArray symname;
bool demangled = false;
};
using SymbolCache = QVector;
AddressCacheEntry find(const PerfElfMap::ElfInfo& elf, quint64 addr,
OffsetAddressCache *invalidAddressCache) const;
void cache(const PerfElfMap::ElfInfo& elf, quint64 addr,
AddressCacheEntry entry, OffsetAddressCache *invalidAddressCache);
/// check if @c setSymbolCache was called for @p filePath already
bool hasSymbolCache(const QByteArray &filePath) const;
/// take @p cache, sort it and use it for symbol lookups in @p filePath
void setSymbolCache(const QByteArray &filePath, SymbolCache cache);
/// find the symbol that encompasses @p relAddr in @p filePath
/// if the found symbol wasn't yet demangled, it will be demangled now
SymbolCacheEntry findSymbol(const QByteArray &filePath, quint64 relAddr);
/// extract all symbols in @p module into a structure suitable to be passed to @p setSymbols
static SymbolCache extractSymbols(Dwfl_Module *module, quint64 elfStart, PerfRegisterInfo::Architecture arch);
private:
QHash m_cache;
QHash m_symbolCache;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(PerfAddressCache::SymbolCacheEntry, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
#endif
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfattributes.cpp 0000664 0000000 0000000 00000026733 15057302234 0024660 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfattributes.h"
#include "perfdata.h"
#include
PerfEventAttributes::PerfEventAttributes()
{
memset(static_cast(this), 0, sizeof(PerfEventAttributes));
}
QDataStream &operator>>(QDataStream &stream, PerfEventAttributes &attrs)
{
quint64 flags;
stream >> attrs.m_type >> attrs.m_size;
if (attrs.m_size < PerfEventAttributes::SIZE_VER0) {
qWarning() << "unsupported file format. event attr size too small:" << attrs.m_size;
return stream;
}
stream >> attrs.m_config >> attrs.m_samplePeriod >> attrs.m_sampleType >> attrs.m_readFormat
>> flags >> attrs.m_wakeupEvents >> attrs.m_bpType >> attrs.m_bpAddr;
if (attrs.m_size > PerfEventAttributes::SIZE_VER0)
stream >> attrs.m_bpLen;
if (attrs.m_size > PerfEventAttributes::SIZE_VER1)
stream >> attrs.m_branchSampleType;
if (attrs.m_size > PerfEventAttributes::SIZE_VER2)
stream >> attrs.m_sampleRegsUser >> attrs.m_sampleStackUser >> attrs.m_clockid;
if (attrs.m_size > PerfEventAttributes::SIZE_VER3)
stream >> attrs.m_sampleRegsIntr;
if (attrs.m_size > PerfEventAttributes::SIZE_VER4)
stream >> attrs.m_auxWatermark >> attrs.m_sampleMaxStack >> attrs.m_reserved2;
if (static_cast(stream.byteOrder()) != QSysInfo::ByteOrder) {
// bit fields are saved in byte order; who came up with that BS?
quint64 newFlags = 0;
for (int i = 0; i < 64; ++i) {
if ((flags & (1ull << i)) != 0)
newFlags |= (1ull << (i / 8 + 7 - (i % 8)));
}
flags = newFlags;
}
*(&attrs.m_readFormat + 1) = flags;
if (attrs.m_size > PerfEventAttributes::SIZE_VER5) {
static const int intMax = std::numeric_limits::max();
quint32 skip = attrs.m_size - PerfEventAttributes::SIZE_VER5;
if (skip > intMax) {
stream.skipRawData(intMax);
skip -= intMax;
}
stream.skipRawData(static_cast(skip));
}
return stream;
}
int PerfEventAttributes::sampleIdOffset() const
{
int offset = 0;
if (m_sampleType & SAMPLE_IDENTIFIER)
return 0;
if (!(m_sampleType & SAMPLE_ID))
return -1;
if (m_sampleType & SAMPLE_IP)
offset += sizeof(quint64); // PerfRecordSample::m_ip
if (m_sampleType & SAMPLE_TID)
offset += sizeof(quint32) + sizeof(quint32); // PerfRecordSampleId::{m_pid|m_tid}
if (m_sampleType & SAMPLE_TIME)
offset += sizeof(quint64); // PerfSampleId::m_time
if (m_sampleType & SAMPLE_ADDR)
offset += sizeof(quint64); // PerfRecordSample::m_addr
return offset;
}
QByteArray PerfEventAttributes::name() const
{
switch (m_type) {
case TYPE_HARDWARE: {
switch (m_config) {
case HARDWARE_CPU_CYCLES: return QByteArrayLiteral("cpu-cycles");
case HARDWARE_INSTRUCTIONS: return QByteArrayLiteral("instructions");
case HARDWARE_CACHE_REFERENCES: return QByteArrayLiteral("cache-references");
case HARDWARE_CACHE_MISSES: return QByteArrayLiteral("cache-misses");
case HARDWARE_BRANCH_INSTRUCTIONS: return QByteArrayLiteral("branch-instructions");
case HARDWARE_BRANCH_MISSES: return QByteArrayLiteral("branch-misses");
case HARDWARE_BUS_CYCLES: return QByteArrayLiteral("bus-cycles");
case HARDWARE_STALLED_CYCLES_FRONTEND: return QByteArrayLiteral("stalled-cycles-frontend");
case HARDWARE_STALLED_CYCLES_BACKEND: return QByteArrayLiteral("stalled-cycles-backend");
case HARDWARE_REF_CPU_CYCLES: return QByteArrayLiteral("ref-cycles");
default: return QByteArrayLiteral("hardware event: 0x") + QByteArray::number(m_config, 16);
}
}
case TYPE_SOFTWARE: {
switch (m_config) {
case SOFTWARE_CPU_CLOCK: return QByteArrayLiteral("cpu-clock");
case SOFTWARE_TASK_CLOCK: return QByteArrayLiteral("task-clock");
case SOFTWARE_PAGE_FAULTS: return QByteArrayLiteral("page-faults");
case SOFTWARE_CONTEXT_SWITCHES: return QByteArrayLiteral("context-switches");
case SOFTWARE_CPU_MIGRATIONS: return QByteArrayLiteral("cpu-migrations");
case SOFTWARE_PAGE_FAULTS_MIN: return QByteArrayLiteral("minor-faults");
case SOFTWARE_PAGE_FAULTS_MAJ: return QByteArrayLiteral("major-faults");
case SOFTWARE_ALIGNMENT_FAULTS: return QByteArrayLiteral("alignment-faults");
case SOFTWARE_EMULATION_FAULTS: return QByteArrayLiteral("emulation-faults");
case SOFTWARE_DUMMY: return QByteArrayLiteral("dummy");
default: return QByteArrayLiteral("software event: 0x") + QByteArray::number(m_config, 16);
}
}
case TYPE_TRACEPOINT:
return QByteArrayLiteral("tracepoint: 0x") + QByteArray::number(m_config, 16);
case TYPE_HARDWARE_CACHE: {
QByteArray result;
switch (m_config & 0xff) {
case HARDWARE_CACHE_L1D: result += QByteArrayLiteral("L1-dcache"); break;
case HARDWARE_CACHE_L1I: result += QByteArrayLiteral("L1-icache"); break;
case HARDWARE_CACHE_LL: result += QByteArrayLiteral("LLC"); break;
case HARDWARE_CACHE_DTLB: result += QByteArrayLiteral("dTLB"); break;
case HARDWARE_CACHE_ITLB: result += QByteArrayLiteral("iTLB"); break;
case HARDWARE_CACHE_BPU: result += QByteArrayLiteral("branch"); break;
case HARDWARE_CACHE_NODE: result += QByteArrayLiteral("node"); break;
default: return QByteArrayLiteral("hardware cache event: 0x")
+ QByteArray::number(m_config, 16);
}
switch ((m_config >> 8) & 0xff) {
case HARDWARE_CACHE_OPERATION_READ: result += QByteArrayLiteral("-load"); break;
case HARDWARE_CACHE_OPERATION_WRITE: result += QByteArrayLiteral("-store"); break;
case HARDWARE_CACHE_OPERATION_PREFETCH: result += QByteArrayLiteral("-prefetch"); break;
default: return result + QByteArrayLiteral(" event: 0x") + QByteArray::number(m_config, 16);
}
switch ((m_config >> 16) & 0xff) {
case HARDWARE_CACHE_RESULT_OPERATION_ACCESS: return result + QByteArrayLiteral("-refs");
case HARDWARE_CACHE_RESULT_OPERATION_MISS: return result + QByteArrayLiteral("-misses");
default: return result + QByteArrayLiteral(" event: 0x") + QByteArray::number(m_config, 16);
};
}
case TYPE_RAW:
return QByteArrayLiteral("raw event: 0x") + QByteArray::number(m_config, 16);
case TYPE_BREAKPOINT:
return QByteArrayLiteral("breakpoint: 0x") + QByteArray::number(m_config, 16);
default:
return QByteArrayLiteral("unknown event ") + QByteArray::number(m_type)
+ QByteArrayLiteral(": 0x") + QByteArray::number(m_config, 16);
}
}
bool PerfEventAttributes::operator==(const PerfEventAttributes &rhs) const
{
return m_type == rhs.m_type
&& m_size == rhs.m_size
&& m_config == rhs.m_config
&& m_samplePeriod == rhs.m_samplePeriod
&& m_sampleType == rhs.m_sampleType
&& m_readFormat == rhs.m_readFormat
&& m_disabled == rhs.m_disabled
&& m_inherit == rhs.m_inherit
&& m_pinned == rhs.m_pinned
&& m_exclusive == rhs.m_exclusive
&& m_excludeUser == rhs.m_excludeUser
&& m_excludeKernel == rhs.m_excludeKernel
&& m_excludeHv == rhs.m_excludeHv
&& m_excludeIdle == rhs.m_excludeIdle
&& m_mmap == rhs.m_mmap
&& m_comm == rhs.m_comm
&& m_freq == rhs.m_freq
&& m_inheritStat == rhs.m_inheritStat
&& m_enableOnExec == rhs.m_enableOnExec
&& m_task == rhs.m_task
&& m_watermark == rhs.m_watermark
&& m_preciseIp == rhs.m_preciseIp
&& m_mmapData == rhs.m_mmapData
&& m_sampleIdAll == rhs.m_sampleIdAll
&& m_excludeHost == rhs.m_excludeHost
&& m_excludeGuest == rhs.m_excludeGuest
&& m_excludeCallchainKernel == rhs.m_excludeCallchainKernel
&& m_excludeCallchainUser == rhs.m_excludeCallchainUser
&& m_reserved1 == rhs.m_reserved1
&& m_wakeupEvents == rhs.m_wakeupEvents
&& m_bpType == rhs.m_bpType
&& m_bpAddr == rhs.m_bpAddr
&& m_bpLen == rhs.m_bpLen
&& m_branchSampleType == rhs.m_branchSampleType
&& m_sampleRegsUser == rhs.m_sampleRegsUser
&& m_sampleStackUser == rhs.m_sampleStackUser
&& m_clockid == rhs.m_clockid
&& m_sampleRegsIntr == rhs.m_sampleRegsIntr
&& m_auxWatermark == rhs.m_auxWatermark
&& m_sampleMaxStack == rhs.m_sampleMaxStack
&& m_reserved2 == rhs.m_reserved2;
}
bool PerfAttributes::read(QIODevice *device, PerfHeader *header)
{
if (header->attrSize() < PerfEventAttributes::SIZE_VER0 + PerfFileSection::fixedLength()) {
qWarning() << "unsupported file format: header attrSize too small:" << header->attrSize();
return false;
}
PerfEventAttributes attrs;
PerfFileSection ids;
for (uint i = 0; i < header->numAttrs(); ++i) {
if (!device->seek(header->attrs().offset + header->attrSize() * i)) {
qWarning() << "cannot seek to attribute section" << i
<< header->attrs().offset + header->attrSize() * i;
return false;
}
QDataStream stream(device);
stream.setByteOrder(header->byteOrder());
stream >> attrs;
if (attrs.size() < PerfEventAttributes::SIZE_VER0)
return false;
if (i == 0)
m_globalAttributes = attrs;
stream >> ids;
if (ids.size > 0) {
if (!device->seek(ids.offset)) {
qWarning() << "cannot seek to attribute ID section";
return false;
}
QDataStream idStream(device);
idStream.setByteOrder(header->byteOrder());
quint64 id;
for (qint64 i = 0, num = ids.size / static_cast(sizeof(quint64));
i < num; ++i) {
idStream >> id;
m_attributes[id] = attrs;
}
}
}
return true;
}
void PerfAttributes::setGlobalAttributes(const PerfEventAttributes &attributes)
{
m_globalAttributes = attributes;
}
void PerfAttributes::addAttributes(quint64 id, const PerfEventAttributes &attributes)
{
m_attributes[id] = attributes;
}
const PerfEventAttributes &PerfAttributes::attributes(quint64 id) const
{
QHash::ConstIterator i = m_attributes.find(id);
if (i != m_attributes.end())
return i.value();
else
return m_globalAttributes;
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfattributes.h 0000664 0000000 0000000 00000024202 15057302234 0024312 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include "perffilesection.h"
#include "perfheader.h"
#include
#include
#include
class PerfEventAttributes {
public:
enum Sizes {
SIZE_VER0 = 64, /* sizeof first published struct */
SIZE_VER1 = 72, /* add: config2 */
SIZE_VER2 = 80, /* add: branch_sample_type */
SIZE_VER3 = 96, /* add: sample_regs_user, sample_stack_user */
SIZE_VER4 = 104, /* add: sample_regs_intr */
SIZE_VER5 = 112, /* add: aux_watermark */
};
PerfEventAttributes();
bool sampleIdAll() const { return m_sampleIdAll; }
quint64 sampleType() const { return m_sampleType; }
quint64 readFormat() const { return m_readFormat; }
quint64 sampleRegsUser() const { return m_sampleRegsUser; }
quint32 size() const { return m_size; }
quint32 type() const { return m_type; }
quint64 config() const { return m_config; }
int sampleIdOffset() const;
bool usesFrequency() const { return m_freq; };
quint64 frequenyOrPeriod() const { return m_sampleFreq; }
QByteArray name() const;
enum ReadFormat {
FORMAT_TOTAL_TIME_ENABLED = 1U << 0,
FORMAT_TOTAL_TIME_RUNNING = 1U << 1,
FORMAT_ID = 1U << 2,
FORMAT_GROUP = 1U << 3,
FORMAT_LOST = 1U << 4,
FORMAT_MAX = 1U << 5
};
/*
* Bits that can be set in sampleType to request information
* in the overflow packets.
*/
enum SampleFormat {
SAMPLE_IP = 1U << 0,
SAMPLE_TID = 1U << 1,
SAMPLE_TIME = 1U << 2,
SAMPLE_ADDR = 1U << 3,
SAMPLE_READ = 1U << 4,
SAMPLE_CALLCHAIN = 1U << 5,
SAMPLE_ID = 1U << 6,
SAMPLE_CPU = 1U << 7,
SAMPLE_PERIOD = 1U << 8,
SAMPLE_STREAM_ID = 1U << 9,
SAMPLE_RAW = 1U << 10,
SAMPLE_BRANCH_STACK = 1U << 11,
SAMPLE_REGS_USER = 1U << 12,
SAMPLE_STACK_USER = 1U << 13,
SAMPLE_WEIGHT = 1U << 14,
SAMPLE_DATA_SRC = 1U << 15,
SAMPLE_IDENTIFIER = 1U << 16,
SAMPLE_TRANSACTION = 1U << 17,
SAMPLE_MAX = 1U << 18,
SAMPLE_ID_ALL = 1U << 31 // extra flag, to check if the sample has a sample ID at all
};
/*
* attr.type()
*/
enum TypeId {
TYPE_HARDWARE = 0,
TYPE_SOFTWARE = 1,
TYPE_TRACEPOINT = 2,
TYPE_HARDWARE_CACHE = 3,
TYPE_RAW = 4,
TYPE_BREAKPOINT = 5,
TYPE_MAX, /* non-ABI */
};
/*
* Generalized performance event eventId types, used by the
* attr.event_id parameter of the sys_perf_event_open()
* syscall.
*
* Ends up in attr.config() if type() is TYPE_HARDWARE
*/
enum HardwareId {
/*
* Common hardware events, generalized by the kernel:
*/
HARDWARE_CPU_CYCLES = 0,
HARDWARE_INSTRUCTIONS = 1,
HARDWARE_CACHE_REFERENCES = 2,
HARDWARE_CACHE_MISSES = 3,
HARDWARE_BRANCH_INSTRUCTIONS = 4,
HARDWARE_BRANCH_MISSES = 5,
HARDWARE_BUS_CYCLES = 6,
HARDWARE_STALLED_CYCLES_FRONTEND = 7,
HARDWARE_STALLED_CYCLES_BACKEND = 8,
HARDWARE_REF_CPU_CYCLES = 9,
HARDWARE_MAX, /* non-ABI */
};
/*
* Generalized hardware cache events:
*
* attr.config() for type() == TYPE_HW_CACHE.
*
* Encoding is (cacheId | (cacheOpId << 8) | (cacheOpResultId << 16))
* for example -e L1-dcache-store-misses results in config == 0x10100, or
* -e LLC-loads in config == 0x000002.
*/
enum HardwareCacheId {
HARDWARE_CACHE_L1D = 0,
HARDWARE_CACHE_L1I = 1,
HARDWARE_CACHE_LL = 2,
HARDWARE_CACHE_DTLB = 3,
HARDWARE_CACHE_ITLB = 4,
HARDWARE_CACHE_BPU = 5,
HARDWARE_CACHE_NODE = 6,
HARDWARE_CACHE_MAX, /* non-ABI */
};
enum HardwareCacheOperationId {
HARDWARE_CACHE_OPERATION_READ = 0,
HARDWARE_CACHE_OPERATION_WRITE = 1,
HARDWARE_CACHE_OPERATION_PREFETCH = 2,
HARDWARE_CACHE_OPERATION_MAX, /* non-ABI */
};
enum HardwareCacheOperationResultId {
HARDWARE_CACHE_RESULT_OPERATION_ACCESS = 0,
HARDWARE_CACHE_RESULT_OPERATION_MISS = 1,
HARDWARE_CACHE_RESULT_OPERATION_MAX, /* non-ABI */
};
/*
* Special "software" events provided by the kernel, even if the hardware
* does not support performance events. These events measure various
* physical and sw events of the kernel (and allow the profiling of them as
* well):
*/
enum SoftwareId {
SOFTWARE_CPU_CLOCK = 0,
SOFTWARE_TASK_CLOCK = 1,
SOFTWARE_PAGE_FAULTS = 2,
SOFTWARE_CONTEXT_SWITCHES = 3,
SOFTWARE_CPU_MIGRATIONS = 4,
SOFTWARE_PAGE_FAULTS_MIN = 5,
SOFTWARE_PAGE_FAULTS_MAJ = 6,
SOFTWARE_ALIGNMENT_FAULTS = 7,
SOFTWARE_EMULATION_FAULTS = 8,
SOFTWARE_DUMMY = 9,
SOFTWARE_MAX, /* non-ABI */
};
bool operator==(const PerfEventAttributes &rhs) const;
private:
/*
* Major type: hardware/software/tracepoint/etc.
*/
quint32 m_type;
/*
* Size of the attr structure, for fwd/bwd compat.
*/
quint32 m_size;
/*
* Type specific configuration information.
*/
quint64 m_config;
union {
quint64 m_samplePeriod;
quint64 m_sampleFreq;
};
quint64 m_sampleType;
quint64 m_readFormat;
quint64 m_disabled : 1, /* off by default */
m_inherit : 1, /* children inherit it */
m_pinned : 1, /* must always be on PMU */
m_exclusive : 1, /* only group on PMU */
m_excludeUser : 1, /* don't count user */
m_excludeKernel : 1, /* ditto kernel */
m_excludeHv : 1, /* ditto hypervisor */
m_excludeIdle : 1, /* don't count when idle */
m_mmap : 1, /* include mmap data */
m_comm : 1, /* include comm data */
m_freq : 1, /* use freq, not period */
m_inheritStat : 1, /* per task counts */
m_enableOnExec : 1, /* next exec enables */
m_task : 1, /* trace fork/exit */
m_watermark : 1, /* wakeup_watermark */
/*
* m_preciseIp:
*
* 0 - SAMPLE_IP can have arbitrary skid
* 1 - SAMPLE_IP must have constant skid
* 2 - SAMPLE_IP requested to have 0 skid
* 3 - SAMPLE_IP must have 0 skid
*
* See also PERF_RECORD_MISC_EXACT_IP
*/
m_preciseIp : 2, /* skid constraint */
m_mmapData : 1, /* non-exec mmap data */
m_sampleIdAll : 1, /* sample_type all events */
m_excludeHost : 1, /* don't count in host */
m_excludeGuest : 1, /* don't count in guest */
m_excludeCallchainKernel : 1, /* exclude kernel callchains */
m_excludeCallchainUser : 1, /* exclude user callchains */
m_reserved1 : 41;
union {
quint32 m_wakeupEvents; /* wakeup every n events */
quint32 m_wakeupWatermark; /* bytes before wakeup */
};
quint32 m_bpType;
union {
quint64 m_bpAddr;
quint64 m_config1; /* extension of config */
};
union {
quint64 m_bpLen;
quint64 m_config2; /* extension of config1 */
};
quint64 m_branchSampleType; /* enum perf_branch_sample_type */
/*
* Defines set of user regs to dump on samples.
* See asm/perf_regs.h for details.
*/
quint64 m_sampleRegsUser;
/*
* Defines size of the user stack to dump on samples.
*/
quint32 m_sampleStackUser;
qint32 m_clockid;
/*
* Defines set of regs to dump for each sample
* state captured on:
* - precise = 0: PMU interrupt
* - precise > 0: sampled instruction
*
* See asm/perf_regs.h for details.
*/
quint64 m_sampleRegsIntr;
/*
* Wakeup watermark for AUX area
*/
quint32 m_auxWatermark;
quint16 m_sampleMaxStack;
/* Align to u64. */
quint16 m_reserved2;
friend QDataStream &operator>>(QDataStream &stream, PerfEventAttributes &attrs);
};
QDataStream &operator>>(QDataStream &stream, PerfEventAttributes &attrs);
class PerfAttributes {
public:
bool read(QIODevice *device, PerfHeader *header);
void addAttributes(quint64 id, const PerfEventAttributes &attributes);
void setGlobalAttributes(const PerfEventAttributes &attributes);
const QHash &attributes() const { return m_attributes; }
const PerfEventAttributes &attributes(quint64 id) const;
const PerfEventAttributes &globalAttributes() const { return m_globalAttributes; }
private:
PerfEventAttributes m_globalAttributes;
QHash m_attributes;
};
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfdata.cpp 0000664 0000000 0000000 00000077074 15057302234 0023407 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfdata.h"
#include "perftracingdata.h"
#include "perfunwind.h"
#include
#include
#include
static const int intMax = std::numeric_limits::max();
PerfData::PerfData(PerfUnwind *destination, const PerfHeader *header, PerfAttributes *attributes) :
m_source(nullptr), m_destination(destination), m_header(header), m_attributes(attributes)
{
}
PerfData::~PerfData()
{
#if HAVE_ZSTD
if (m_zstdDstream)
ZSTD_freeDStream(m_zstdDstream);
#endif
}
void PerfData::setSource(QIODevice *source)
{
m_source = source;
}
bool PerfData::setCompressed(const PerfCompressed &compressed)
{
if (compressed.version != 0) {
qWarning() << "unsupported compression version" << compressed.version;
return false;
} else if (compressed.type != PerfCompressed::PERF_COMP_ZSTD) {
qWarning() << "unsupported compression type" << compressed.type;
return false;
} else if (!CAN_DECOMPRESS_ZSTD) {
qWarning() << "zstd decompression support not available";
return false;
} else if (!compressed.mmap_len) {
qWarning() << "invalid compression information" << compressed.mmap_len;
return false;
}
m_compressed = compressed;
return true;
}
const char* perfEventToString(quint32 type)
{
switch (type) {
case PERF_RECORD_MMAP: return "PERF_RECORD_MMAP";
case PERF_RECORD_LOST: return "PERF_RECORD_LOST";
case PERF_RECORD_COMM: return "PERF_RECORD_COMM";
case PERF_RECORD_EXIT: return "PERF_RECORD_EXIT";
case PERF_RECORD_THROTTLE: return "PERF_RECORD_THROTTLE";
case PERF_RECORD_UNTHROTTLE: return "PERF_RECORD_UNTHROTTLE";
case PERF_RECORD_FORK: return "PERF_RECORD_FORK";
case PERF_RECORD_READ: return "PERF_RECORD_READ";
case PERF_RECORD_SAMPLE: return "PERF_RECORD_SAMPLE";
case PERF_RECORD_MMAP2: return "PERF_RECORD_MMAP2";
case PERF_RECORD_SWITCH: return "PERF_RECORD_SWITCH";
case PERF_RECORD_SWITCH_CPU_WIDE: return "PERF_RECORD_SWITCH_CPU_WIDE";
case PERF_RECORD_NAMESPACES: return "PERF_RECORD_NAMESPACES";
case PERF_RECORD_KSYMBOL: return "PERF_RECORD_KSYMBOL";
case PERF_RECORD_BPF_EVENT: return "PERF_RECORD_BPF_EVENT";
case PERF_RECORD_CGROUP: return "PERF_RECORD_CGROUP";
case PERF_RECORD_HEADER_ATTR: return "PERF_RECORD_HEADER_ATTR";
case PERF_RECORD_HEADER_EVENT_TYPE: return "PERF_RECORD_HEADER_EVENT_TYPE";
case PERF_RECORD_HEADER_TRACING_DATA: return "PERF_RECORD_HEADER_TRACING_DATA";
case PERF_RECORD_HEADER_BUILD_ID: return "PERF_RECORD_HEADER_BUILD_ID";
case PERF_RECORD_FINISHED_ROUND: return "PERF_RECORD_FINISHED_ROUND";
case PERF_RECORD_ID_INDEX: return "PERF_RECORD_ID_INDEX";
case PERF_RECORD_AUXTRACE_INFO: return "PERF_RECORD_AUXTRACE_INFO";
case PERF_RECORD_AUXTRACE: return "PERF_RECORD_AUXTRACE";
case PERF_RECORD_AUXTRACE_ERROR: return "PERF_RECORD_AUXTRACE_ERROR";
case PERF_RECORD_THREAD_MAP: return "PERF_RECORD_THREAD_MAP";
case PERF_RECORD_CPU_MAP: return "PERF_RECORD_CPU_MAP";
case PERF_RECORD_STAT_CONFIG: return "PERF_RECORD_STAT_CONFIG";
case PERF_RECORD_STAT: return "PERF_RECORD_STAT";
case PERF_RECORD_STAT_ROUND: return "PERF_RECORD_STAT_ROUND";
case PERF_RECORD_EVENT_UPDATE: return "PERF_RECORD_EVENT_UPDATE";
case PERF_RECORD_TIME_CONV: return "PERF_RECORD_TIME_CONV";
case PERF_RECORD_HEADER_FEATURE: return "PERF_RECORD_HEADER_FEATURE";
case PERF_RECORD_COMPRESSED: return "PERF_RECORD_COMPRESSED";
case PERF_RECORD_FINISHED_INIT: return "PERF_RECORD_FINISHED_INIT";
case PERF_RECORD_COMPRESSED2: return "PERF_RECORD_COMPRESSED2";
case PERF_RECORD_BPF_METADATA: return "PERF_RECORD_BPF_METADATA";
}
return "unknown type";
}
#if HAVE_ZSTD
PerfData::ReadStatus PerfData::processCompressedEvents(QDataStream &stream, qint64 contentSize)
{
if (!m_zstdDstream) {
if (!m_header->hasFeature(PerfHeader::COMPRESSED)) {
qWarning() << "encountered PERF_RECORD_COMPRESSED without HEADER_COMPRESSED information";
return SignalError;
}
m_zstdDstream = ZSTD_createDStream();
ZSTD_initDStream(m_zstdDstream);
// preallocate a buffer to hold the compressed data
m_compressedBuffer.resize(std::numeric_limits::max());
}
// load compressed data into contiguous array
stream.readRawData(m_compressedBuffer.data(), contentSize);
ZSTD_inBuffer in = {m_compressedBuffer.constData(), static_cast(contentSize), 0};
// setup decompression buffer which may contain data from a previous compressed record
// i.e. one where we had to Rerun. the decompression can add at most mmap_len data on top
m_decompressBuffer.resize(static_cast(m_compressed.mmap_len + m_remaininingDecompressedDataSize));
auto outBuffer = m_decompressBuffer.data() + m_remaininingDecompressedDataSize;
auto outBufferSize = static_cast(m_decompressBuffer.size() - m_remaininingDecompressedDataSize);
ZSTD_outBuffer out = {outBuffer, outBufferSize, 0};
// now actually decompress the record data
while (in.pos < in.size) {
const auto err = ZSTD_decompressStream(m_zstdDstream, &out, &in);
if (ZSTD_isError(err)) {
qWarning() << "ZSTD decompression failed:" << ZSTD_getErrorName(err);
return SignalError;
}
out.dst = outBuffer + out.pos;
out.size = outBufferSize - out.pos;
}
// then resize the buffer to final size, which may be less than mmap_len
m_decompressBuffer.resize(static_cast(out.pos + m_remaininingDecompressedDataSize));
// reset this now that we start to parse from the start of the buffer again
m_remaininingDecompressedDataSize = 0;
QDataStream uncompressedStream(m_decompressBuffer);
uncompressedStream.setByteOrder(m_header->byteOrder());
// we have to set the size to zero here otherwise processEvents gets confused
m_eventHeader.size = 0;
auto status = SignalFinished;
while (status == SignalFinished) {
// position in the decompressed buffer that corresponds to a start of the next record
// when we encounter a Rerun scenario, we have to start again at this position the next time
const auto oldPos = uncompressedStream.device()->pos();
status = processEvents(uncompressedStream);
switch (status) {
case SignalFinished:
break;
case SignalError:
return SignalError;
case Rerun:
// unset the device to prevent the m_decompressBuffer from being shared
// we don't want to copy the data when we call .begin() below
uncompressedStream.setDevice(nullptr);
// remaining decompressed data that needs to be parsed the next time
// we handle an uncompressed record
m_remaininingDecompressedDataSize = static_cast(m_decompressBuffer.size() - oldPos);
// move that data up front in the buffer and continue appending data
std::move(m_decompressBuffer.begin() + oldPos, m_decompressBuffer.end(),
m_decompressBuffer.begin());
break;
}
};
return SignalFinished;
}
#endif
PerfData::ReadStatus PerfData::processEvents(QDataStream &stream)
{
const quint16 headerSize = PerfEventHeader::fixedLength();
if (m_eventHeader.size == 0) {
const qint64 available = stream.device()->bytesAvailable();
if (available < 0)
return SignalError;
if (available < headerSize)
return Rerun;
stream >> m_eventHeader;
if (m_eventHeader.size < headerSize) {
qWarning() << "bad event header size" << m_eventHeader.size << m_eventHeader.type
<< m_eventHeader.misc;
return SignalError;
}
}
const quint16 contentSize = m_eventHeader.size - headerSize;
qint64 expectedParsedContentSize = contentSize;
if (stream.device()->bytesAvailable() < contentSize)
return Rerun;
const PerfEventAttributes &attrs = m_attributes->globalAttributes();
int idOffset = attrs.sampleIdOffset();
bool sampleIdAll = attrs.sampleIdAll();
quint64 sampleType = attrs.sampleType();
const auto oldPos = stream.device()->isSequential() ? 0 : stream.device()->pos();
switch (m_eventHeader.type) {
case PERF_RECORD_MMAP: {
PerfRecordMmap mmap(&m_eventHeader, sampleType, sampleIdAll);
stream >> mmap;
m_destination->registerElf(mmap);
break;
}
case PERF_RECORD_LOST: {
PerfRecordLost lost(&m_eventHeader, sampleType, sampleIdAll);
stream >> lost;
m_destination->lost(lost);
break;
}
case PERF_RECORD_COMM: {
PerfRecordComm comm(&m_eventHeader, sampleType, sampleIdAll);
stream >> comm;
m_destination->comm(comm);
break;
}
case PERF_RECORD_SAMPLE: {
if (sampleIdAll && idOffset >= 0) {
QByteArray buffer(contentSize, Qt::Uninitialized);
stream.readRawData(buffer.data(), contentSize);
QDataStream contentStream(buffer);
contentStream.setByteOrder(stream.byteOrder());
Q_ASSERT(!contentStream.device()->isSequential());
// peek into the data structure to find the actual ID. Horrible.
quint64 id;
qint64 prevPos = contentStream.device()->pos();
contentStream.device()->seek(prevPos + idOffset);
contentStream >> id;
contentStream.device()->seek(prevPos);
PerfRecordSample sample(&m_eventHeader, &m_attributes->attributes(id));
contentStream >> sample;
m_destination->sample(sample);
} else {
PerfRecordSample sample(&m_eventHeader, &attrs);
stream >> sample;
m_destination->sample(sample);
}
break;
}
case PERF_RECORD_MMAP2: {
PerfRecordMmap2 mmap2(&m_eventHeader, sampleType, sampleIdAll);
stream >> mmap2;
// We only care about executable mappings, and registerElf will match this against an executable mapping in the
// program headers.
if (mmap2.prot() & PROT_EXEC) {
m_destination->registerElf(mmap2); // Throw out the extra data for now.
}
break;
}
case PERF_RECORD_HEADER_ATTR: {
PerfRecordAttr attr(&m_eventHeader, sampleType, sampleIdAll);
stream >> attr;
m_destination->attr(attr);
if (m_attributes->globalAttributes().size() == 0)
m_attributes->setGlobalAttributes(attr.attr());
const auto ids = attr.ids();
for (quint64 id : ids)
m_attributes->addAttributes(id, attr.attr());
break;
}
case PERF_RECORD_FORK: {
PerfRecordFork fork(&m_eventHeader, sampleType, sampleIdAll);
stream >> fork;
m_destination->fork(fork);
break;
}
case PERF_RECORD_EXIT: {
PerfRecordFork exit(&m_eventHeader, sampleType, sampleIdAll);
stream >> exit;
m_destination->exit(exit);
break;
}
case PERF_RECORD_HEADER_TRACING_DATA: {
if (contentSize == 4) {
// The content is actually another 4 byte integer,
// describing the size of the real content that follows.
if (m_tracingData.size() == 0) {
quint32 size;
stream >> size;
m_tracingData.setSize(size);
expectedParsedContentSize += size;
}
if (stream.device()->bytesAvailable() >= m_tracingData.size()) {
stream >> m_tracingData;
m_destination->tracing(m_tracingData);
m_tracingData = PerfTracingData();
} else {
return Rerun;
}
} else {
// contentSize is only 16bit. The tracing data frequently exceeds 2^16 bytes.
qWarning() << "HEADER_TRACING_DATA with unexpected contentSize" << contentSize;
stream.skipRawData(contentSize);
}
break;
}
case PERF_RECORD_FINISHED_ROUND: {
m_destination->finishedRound();
if (contentSize != 0) {
qWarning() << "FINISHED_ROUND with non-zero content size detected"
<< contentSize;
stream.skipRawData(contentSize);
}
break;
}
case PERF_RECORD_SWITCH: {
PerfRecordContextSwitch switchEvent(&m_eventHeader, sampleType, sampleIdAll);
stream >> switchEvent;
m_destination->contextSwitch(switchEvent);
break;
}
case PERF_RECORD_SWITCH_CPU_WIDE: {
PerfRecordContextSwitchCpuWide switchEvent(&m_eventHeader, sampleType, sampleIdAll);
stream >> switchEvent;
// TODO: also send prevNext{T,P}id, that would allow switch markers in the GUI to
// show where a switch comes from/goes to
m_destination->contextSwitch(switchEvent);
break;
}
#if HAVE_ZSTD
case PERF_RECORD_COMPRESSED: {
// possibly unaligned
auto status = processCompressedEvents(stream, contentSize);
if (status != SignalFinished)
return status;
break;
}
case PERF_RECORD_COMPRESSED2: {
// properly aligned
quint64 compressedContentSize = 0;
stream >> compressedContentSize;
if (compressedContentSize > contentSize) {
qWarning() << "bad PERF_RECORD_COMPRESSED2 size information" << compressedContentSize << contentSize;
return SignalError;
}
auto status = processCompressedEvents(stream, compressedContentSize);
if (status != SignalFinished)
return status;
stream.skipRawData(contentSize - compressedContentSize - sizeof(compressedContentSize));
break;
}
#endif
// list of events we are not interested in and just skip
// [UN]THROTTLE: if seen in a recording then commonly much too much to just warn on
case PERF_RECORD_THROTTLE:
case PERF_RECORD_UNTHROTTLE:
stream.skipRawData(contentSize);
break;
default:
qDebug() << "unhandled event type" << m_eventHeader.type << " " << perfEventToString(m_eventHeader.type);
stream.skipRawData(contentSize);
break;
}
if (!stream.device()->isSequential()) {
const auto parsedContentSize = stream.device()->pos() - oldPos;
if (parsedContentSize != expectedParsedContentSize) {
qWarning() << "Event not fully parsed" << m_eventHeader.type << expectedParsedContentSize
<< parsedContentSize;
stream.skipRawData(static_cast(contentSize - parsedContentSize));
}
}
m_eventHeader.size = 0;
return SignalFinished;
}
PerfData::ReadStatus PerfData::doRead()
{
QDataStream stream(m_source);
stream.setByteOrder(m_header->byteOrder());
ReadStatus returnCode = SignalFinished;
if (m_header->isPipe()) {
if (m_source->isSequential()) {
while (m_source->bytesAvailable() > 0) {
returnCode = processEvents(stream);
if (returnCode == SignalError || returnCode == Rerun)
break;
}
if (returnCode != SignalError) {
if (m_source->isOpen()) {
// finished some event, but not the whole stream
returnCode = Rerun;
} else {
// if there is a half event left when the stream finishes, that's bad
returnCode = m_eventHeader.size != 0 ? SignalError : SignalFinished;
}
}
} else {
while (!m_source->atEnd()) {
if (processEvents(stream) != SignalFinished) {
returnCode = SignalError;
break;
}
}
}
} else if (m_source->isSequential()) {
qWarning() << "cannot read non-stream format from stream";
returnCode = SignalError;
} else if (!m_source->seek(m_header->dataOffset())) {
qWarning() << "cannot seek to" << m_header->dataOffset();
returnCode = SignalError;
} else {
const auto dataOffset = m_header->dataOffset();
const auto dataSize = m_header->dataSize();
const auto endOfDataSection = dataOffset + dataSize;
m_destination->sendProgress(static_cast(m_source->pos() - dataOffset) / static_cast(dataSize));
const qint64 posDeltaBetweenProgress = dataSize / 100;
qint64 nextProgressAt = m_source->pos() + posDeltaBetweenProgress;
while (m_source->pos() < endOfDataSection) {
if (processEvents(stream) != SignalFinished) {
returnCode = SignalError;
break;
}
if (m_source->pos() >= nextProgressAt) {
m_destination->sendProgress(static_cast(m_source->pos() - dataOffset)
/ static_cast(dataSize));
nextProgressAt += posDeltaBetweenProgress;
}
}
}
return returnCode;
}
void PerfData::read()
{
ReadStatus returnCode = doRead();
switch (returnCode) {
case SignalFinished:
disconnect(m_source, &QIODevice::readyRead, this, &PerfData::read);
disconnect(m_source, &QIODevice::aboutToClose, this, &PerfData::finishReading);
emit finished();
break;
case SignalError:
disconnect(m_source, &QIODevice::readyRead, this, &PerfData::read);
disconnect(m_source, &QIODevice::aboutToClose, this, &PerfData::finishReading);
emit error();
break;
case Rerun:
break;
}
}
void PerfData::finishReading()
{
disconnect(m_source, &QIODevice::readyRead, this, &PerfData::read);
disconnect(m_source, &QIODevice::aboutToClose, this, &PerfData::finishReading);
ReadStatus returnCode = doRead();
switch (returnCode) {
case SignalFinished:
emit finished();
break;
case SignalError:
emit error();
break;
case Rerun:
if (m_eventHeader.size == 0)
emit finished();
else
emit error();
break;
}
}
PerfRecordMmap::PerfRecordMmap(PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecord(header, sampleType, sampleIdAll), m_pid(0), m_tid(0), m_addr(0), m_len(0), m_pgoff(0)
{
}
QDataStream &PerfRecordMmap::readNumbers(QDataStream &stream)
{
return stream >> m_pid >> m_tid >> m_addr >> m_len >> m_pgoff;
}
QDataStream &PerfRecordMmap::readFilename(QDataStream &stream, quint16 filenameLength)
{
m_filename.resize(filenameLength);
stream.readRawData(m_filename.data(), filenameLength);
int null = m_filename.indexOf('\0');
if (null != -1)
m_filename.truncate(null);
return stream;
}
QDataStream &PerfRecordMmap::readSampleId(QDataStream &stream)
{
stream >> m_sampleId;
return stream;
}
quint16 PerfRecordMmap::fixedLength() const
{
return sizeof(m_pid) + sizeof(m_tid) + sizeof(m_addr) + sizeof(m_len) + sizeof(m_pgoff)
+ m_header.fixedLength() + m_sampleId.fixedLength();
}
QDataStream &operator>>(QDataStream &stream, PerfRecordMmap &record)
{
record.readNumbers(stream);
record.readFilename(stream, record.m_header.size - record.fixedLength());
record.readSampleId(stream);
return stream;
}
PerfRecordMmap2::PerfRecordMmap2(PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecordMmap(header, sampleType, sampleIdAll), m_maj(0), m_min(0), m_ino(0),
m_ino_generation(0), m_prot(0), m_flags(0)
{
}
QDataStream &PerfRecordMmap2::readNumbers(QDataStream &stream)
{
PerfRecordMmap::readNumbers(stream);
return stream >> m_maj >> m_min >> m_ino >> m_ino_generation >> m_prot >> m_flags;
}
quint16 PerfRecordMmap2::fixedLength() const
{
return PerfRecordMmap::fixedLength() + sizeof(m_maj) + sizeof(m_min) + sizeof(m_ino)
+ sizeof(m_ino_generation) + sizeof(m_prot) + sizeof(m_flags);
}
QDataStream &operator>>(QDataStream &stream, PerfRecordMmap2 &record)
{
record.readNumbers(stream);
record.readFilename(stream, record.m_header.size - record.fixedLength());
record.readSampleId(stream);
return stream;
}
PerfRecordComm::PerfRecordComm(PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecord(header, sampleType, sampleIdAll), m_pid(0), m_tid(0)
{
}
QDataStream &operator>>(QDataStream &stream, PerfRecordComm &record)
{
stream >> record.m_pid >> record.m_tid;
const quint16 commLength = record.m_header.size - record.fixedLength();
record.m_comm.resize(commLength);
stream.readRawData(record.m_comm.data(), commLength);
int null = record.m_comm.indexOf('\0');
if (null != -1)
record.m_comm.truncate(null);
stream >> record.m_sampleId;
return stream;
}
PerfRecordLost::PerfRecordLost(PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecord(header, sampleType, sampleIdAll), m_id(0), m_lost(0)
{
}
QDataStream &operator>>(QDataStream &stream, PerfRecordLost &record)
{
stream >> record.m_id >> record.m_lost >> record.m_sampleId;
return stream;
}
QDataStream &operator>>(QDataStream &stream, PerfSampleId &sampleId)
{
if (sampleId.m_sampleType & PerfEventAttributes::SAMPLE_ID_ALL) {
if (sampleId.m_sampleType & PerfEventAttributes::SAMPLE_TID)
stream >> sampleId.m_pid >> sampleId.m_tid;
if (sampleId.m_sampleType & PerfEventAttributes::SAMPLE_TIME)
stream >> sampleId.m_time;
if (sampleId.m_sampleType & PerfEventAttributes::SAMPLE_ID)
stream >> sampleId.m_id;
if (sampleId.m_sampleType & PerfEventAttributes::SAMPLE_STREAM_ID)
stream >> sampleId.m_streamId;
if (sampleId.m_sampleType & PerfEventAttributes::SAMPLE_CPU)
stream >> sampleId.m_cpu >> sampleId.m_res;
if (sampleId.m_sampleType & PerfEventAttributes::SAMPLE_IDENTIFIER)
stream.skipRawData(sizeof(sampleId.m_ignoredDuplicateId));
}
return stream;
}
quint16 PerfSampleId::fixedLength() const
{
quint16 ret = 0;
if (m_sampleType & PerfEventAttributes::SAMPLE_ID_ALL) {
if (m_sampleType & PerfEventAttributes::SAMPLE_TID)
ret += sizeof(m_pid) + sizeof(m_tid);
if (m_sampleType & PerfEventAttributes::SAMPLE_TIME)
ret += sizeof(m_time);
if (m_sampleType & PerfEventAttributes::SAMPLE_ID)
ret += sizeof(m_id);
if (m_sampleType & PerfEventAttributes::SAMPLE_STREAM_ID)
ret += sizeof(m_streamId);
if (m_sampleType & PerfEventAttributes::SAMPLE_CPU)
ret += sizeof(m_res) + sizeof(m_cpu);
if (m_sampleType & PerfEventAttributes::SAMPLE_IDENTIFIER)
ret += sizeof(m_ignoredDuplicateId);
}
return ret;
}
PerfRecord::PerfRecord(const PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
m_header(header ? *header : PerfEventHeader()), m_sampleId(sampleType, sampleIdAll)
{
}
PerfRecordSample::PerfRecordSample(const PerfEventHeader *header,
const PerfEventAttributes *attributes)
: PerfRecord(header, attributes->sampleType(), false), m_readFormat(attributes->readFormat()),
m_registerMask(attributes->sampleRegsUser()), m_ip(0), m_addr(0), m_period(0),
m_timeEnabled(0), m_timeRunning(0), m_registerAbi(0), m_weight(0)
{
}
quint64 PerfRecordSample::registerValue(int reg) const
{
Q_ASSERT(reg >= 0);
Q_ASSERT(m_registerAbi && m_registerMask & (1ull << reg));
int index = 0;
for (int i = 0; i < reg; i++) {
if (m_registerMask & (1ull << i))
index++;
}
if (index < m_registers.length()) {
return m_registers[index];
} else {
qWarning() << "invalid register offset" << index;
return std::numeric_limits::max();
}
}
QDataStream &operator>>(QDataStream &stream, PerfRecordSample &record)
{
quint32 waste32;
const quint64 sampleType = record.m_sampleId.sampleType();
const auto withLostFormat = record.m_readFormat & PerfEventAttributes::FORMAT_LOST;
if (sampleType & PerfEventAttributes::SAMPLE_IDENTIFIER)
stream >> record.m_sampleId.m_id;
if (sampleType & PerfEventAttributes::SAMPLE_IP)
stream >> record.m_ip;
if (sampleType & PerfEventAttributes::SAMPLE_TID)
stream >> record.m_sampleId.m_pid >> record.m_sampleId.m_tid;
if (sampleType & PerfEventAttributes::SAMPLE_TIME)
stream >> record.m_sampleId.m_time;
if (sampleType & PerfEventAttributes::SAMPLE_ADDR)
stream >> record.m_addr;
if (sampleType & PerfEventAttributes::SAMPLE_ID)
stream >> record.m_sampleId.m_id; // It's the same as identifier
if (sampleType & PerfEventAttributes::SAMPLE_STREAM_ID)
stream >> record.m_sampleId.m_streamId;
if (sampleType & PerfEventAttributes::SAMPLE_CPU)
stream >> record.m_sampleId.m_cpu >> waste32;
if (sampleType & PerfEventAttributes::SAMPLE_PERIOD)
stream >> record.m_period;
if (sampleType & PerfEventAttributes::SAMPLE_READ) {
quint64 numFormats = 1;
PerfRecordSample::ReadFormat format;
if (record.m_readFormat & PerfEventAttributes::FORMAT_GROUP)
stream >> numFormats;
else
stream >> format.value;
if (record.m_readFormat & PerfEventAttributes::FORMAT_TOTAL_TIME_ENABLED)
stream >> record.m_timeEnabled;
if (record.m_readFormat & PerfEventAttributes::FORMAT_TOTAL_TIME_RUNNING)
stream >> record.m_timeRunning;
if (record.m_readFormat & PerfEventAttributes::FORMAT_GROUP) {
while (numFormats-- > 0) {
stream >> format.value >> format.id;
if (withLostFormat)
stream >> format.lost;
record.m_readFormats << format;
}
} else {
stream >> format.id;
if (withLostFormat)
stream >> format.lost;
record.m_readFormats << format;
}
}
if (sampleType & PerfEventAttributes::SAMPLE_CALLCHAIN) {
quint64 numIps;
quint64 ip;
stream >> numIps;
while (numIps-- > 0) {
stream >> ip;
record.m_callchain << ip;
}
}
if (sampleType & PerfEventAttributes::SAMPLE_RAW) {
quint32 rawSize;
stream >> rawSize;
if (rawSize > intMax) {
qWarning() << "Excessively long raw data section" << rawSize;
stream.skipRawData(intMax);
stream.skipRawData(static_cast(rawSize - intMax));
} else {
record.m_rawData.resize(static_cast(rawSize));
stream.readRawData(record.m_rawData.data(), record.m_rawData.length());
}
}
if (sampleType & PerfEventAttributes::SAMPLE_BRANCH_STACK) {
quint64 numBranches;
stream >> numBranches;
PerfRecordSample::BranchEntry entry;
while (numBranches-- > 0) {
stream >> entry.from >> entry.to;
stream.readRawData(reinterpret_cast(&entry.flags), sizeof(entry.flags));
record.m_branchStack << entry;
}
}
if (sampleType & PerfEventAttributes::SAMPLE_REGS_USER) {
quint64 reg;
stream >> record.m_registerAbi;
if (record.m_registerAbi) {
for (uint i = qPopulationCount(record.m_registerMask); i > 0; --i) {
stream >> reg;
record.m_registers << reg;
}
}
}
if (sampleType & PerfEventAttributes::SAMPLE_STACK_USER) {
quint64 sectionSize;
stream >> sectionSize;
if (sectionSize > intMax) {
// We don't accept stack samples of > 2G, sorry ...
qWarning() << "Excessively large stack snapshot" << sectionSize;
do {
stream.skipRawData(intMax);
sectionSize -= intMax;
} while (sectionSize > intMax);
stream.skipRawData(static_cast(sectionSize));
stream.skipRawData(sizeof(quint64)); // skip contentSize
} else if (sectionSize > 0) {
record.m_userStack.resize(static_cast(sectionSize));
stream.readRawData(record.m_userStack.data(), record.m_userStack.size());
quint64 contentSize;
stream >> contentSize;
if (contentSize > sectionSize)
qWarning() << "Truncated stack snapshot" << contentSize << sectionSize;
else
record.m_userStack.resize(static_cast(contentSize));
}
}
if (sampleType & PerfEventAttributes::SAMPLE_WEIGHT)
stream >> record.m_weight;
if (sampleType & PerfEventAttributes::SAMPLE_DATA_SRC)
stream >> record.m_dataSrc;
if (sampleType & PerfEventAttributes::SAMPLE_TRANSACTION)
stream >> record.m_transaction;
return stream;
}
PerfRecordAttr::PerfRecordAttr(const PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecord(header, sampleType, sampleIdAll)
{
}
PerfRecordAttr::PerfRecordAttr(const PerfEventAttributes &attributes, const QList &ids) :
PerfRecord(nullptr, 0, false), m_attr(attributes), m_ids(ids)
{
}
QDataStream &operator>>(QDataStream &stream, PerfRecordAttr &record)
{
stream >> record.m_attr;
quint32 read = record.m_attr.size() + PerfEventHeader::fixedLength();
quint64 id = 0;
for (quint32 i = 0; i < (record.m_header.size - read) / sizeof(quint64); ++i) {
stream >> id;
record.m_ids << id;
}
return stream;
}
PerfRecordFork::PerfRecordFork(PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecord(header, sampleType, sampleIdAll), m_pid(0), m_ppid(0), m_tid(0), m_ptid(0), m_time(0)
{
}
QDataStream &operator>>(QDataStream &stream, PerfRecordFork &record)
{
return stream >> record.m_pid >> record.m_ppid >> record.m_tid >> record.m_ptid >> record.m_time
>> record.m_sampleId;
}
PerfRecordContextSwitch::PerfRecordContextSwitch(PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecord(header, sampleType, sampleIdAll)
{
}
QDataStream &operator>>(QDataStream &stream, PerfRecordContextSwitch &record)
{
return stream >> record.m_sampleId;
}
PerfRecordContextSwitchCpuWide::PerfRecordContextSwitchCpuWide(PerfEventHeader *header, quint64 sampleType, bool sampleIdAll) :
PerfRecordContextSwitch(header, sampleType, sampleIdAll)
{
}
QDataStream &operator>>(QDataStream &stream, PerfRecordContextSwitchCpuWide &record)
{
return stream >> record.m_nextPrevPid >> record.m_nextPrevTid >> record.m_sampleId;
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfdata.h 0000664 0000000 0000000 00000050660 15057302234 0023044 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include "perfattributes.h"
#include "perffeatures.h"
#include "perfheader.h"
#include // generated by cmake
#include
#if HAVE_ZSTD
#include
constexpr bool CAN_DECOMPRESS_ZSTD = true;
#else
constexpr bool CAN_DECOMPRESS_ZSTD = false;
#endif
enum PerfEventType {
/*
* If perf_event_attr.sample_id_all is set then all event types will
* have the sample_type selected fields related to where/when
* (identity) an event took place (TID, TIME, ID, STREAM_ID, CPU,
* IDENTIFIER) described in PERF_RECORD_SAMPLE below, it will be stashed
* just after the perf_event_header and the fields already present for
* the existing fields, i.e. at the end of the payload. That way a newer
* perf.data file will be supported by older perf tools, with these new
* optional fields being ignored.
*
* struct sample_id {
* { u32 pid, tid; } && PERF_SAMPLE_TID
* { u64 time; } && PERF_SAMPLE_TIME
* { u64 id; } && PERF_SAMPLE_ID
* { u64 stream_id;} && PERF_SAMPLE_STREAM_ID
* { u32 cpu, res; } && PERF_SAMPLE_CPU
* { u64 id; } && PERF_SAMPLE_IDENTIFIER
* } && perf_event_attr::sample_id_all
*
* Note that PERF_SAMPLE_IDENTIFIER duplicates PERF_SAMPLE_ID. The
* advantage of PERF_SAMPLE_IDENTIFIER is that its position is fixed
* relative to header.size.
*/
/*
* The MMAP events record the PROT_EXEC mappings so that we can
* correlate userspace IPs to code. They have the following structure:
*
* struct {
* struct perf_event_header header;
*
* u32 pid, tid;
* u64 addr;
* u64 len;
* u64 pgoff;
* char filename[];
* struct sample_id sample_id;
* };
*/
PERF_RECORD_MMAP = 1,
/*
* struct {
* struct perf_event_header header;
* u64 id;
* u64 lost;
* struct sample_id sample_id;
* };
*/
PERF_RECORD_LOST = 2,
/*
* struct {
* struct perf_event_header header;
*
* u32 pid, tid;
* char comm[];
* struct sample_id sample_id;
* };
*/
PERF_RECORD_COMM = 3,
/*
* struct {
* struct perf_event_header header;
* u32 pid, ppid;
* u32 tid, ptid;
* u64 time;
* struct sample_id sample_id;
* };
*/
PERF_RECORD_EXIT = 4,
/*
* struct {
* struct perf_event_header header;
* u64 time;
* u64 id;
* u64 stream_id;
* struct sample_id sample_id;
* };
*/
PERF_RECORD_THROTTLE = 5,
PERF_RECORD_UNTHROTTLE = 6,
/*
* struct {
* struct perf_event_header header;
* u32 pid, ppid;
* u32 tid, ptid;
* u64 time;
* struct sample_id sample_id;
* };
*/
PERF_RECORD_FORK = 7,
/*
* struct {
* struct perf_event_header header;
* u32 pid, tid;
*
* struct read_format values;
* struct sample_id sample_id;
* };
*/
PERF_RECORD_READ = 8,
/*
* struct {
* struct perf_event_header header;
*
* #
* # Note that PERF_SAMPLE_IDENTIFIER duplicates PERF_SAMPLE_ID.
* # The advantage of PERF_SAMPLE_IDENTIFIER is that its position
* # is fixed relative to header.
* #
*
* { u64 id; } && PERF_SAMPLE_IDENTIFIER
* { u64 ip; } && PERF_SAMPLE_IP
* { u32 pid, tid; } && PERF_SAMPLE_TID
* { u64 time; } && PERF_SAMPLE_TIME
* { u64 addr; } && PERF_SAMPLE_ADDR
* { u64 id; } && PERF_SAMPLE_ID
* { u64 stream_id; } && PERF_SAMPLE_STREAM_ID
* { u32 cpu, res; } && PERF_SAMPLE_CPU
* { u64 period; } && PERF_SAMPLE_PERIOD
*
* { struct read_format values;} && PERF_SAMPLE_READ
*
* { u64 nr,
* u64 ips[nr]; } && PERF_SAMPLE_CALLCHAIN
*
* #
* # The RAW record below is opaque data wrt the ABI
* #
* # That is, the ABI doesn't make any promises wrt to
* # the stability of its content, it may vary depending
* # on event, hardware, kernel version and phase of
* # the moon.
* #
* # In other words, PERF_SAMPLE_RAW contents are not an ABI.
* #
*
* { u32 size;
* char data[size];} && PERF_SAMPLE_RAW
*
* { u64 nr;
* { u64 from, to, flags } lbr[nr];} && PERF_SAMPLE_BRANCH_STACK
*
* { u64 abi; # enum perf_sample_regs_abi
* u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_USER
*
* { u64 size;
* char data[size];
* u64 dyn_size; } && PERF_SAMPLE_STACK_USER
*
* { u64 weight; } && PERF_SAMPLE_WEIGHT
* { u64 data_src; } && PERF_SAMPLE_DATA_SRC
* { u64 transaction; } && PERF_SAMPLE_TRANSACTION
* };
*/
PERF_RECORD_SAMPLE = 9,
/*
* The MMAP2 records are an augmented version of MMAP, they add
* maj, min, ino numbers to be used to uniquely identify each mapping
*
* struct {
* struct perf_event_header header;
*
* u32 pid, tid;
* u64 addr;
* u64 len;
* u64 pgoff;
* u32 maj;
* u32 min;
* u64 ino;
* u64 ino_generation;
* u32 prot, flags;
* char filename[];
* struct sample_id sample_id;
* };
*/
PERF_RECORD_MMAP2 = 10,
/*
* Records a context switch in or out (flagged by
* PERF_RECORD_MISC_SWITCH_OUT). See also
* PERF_RECORD_SWITCH_CPU_WIDE.
*
* struct {
* struct perf_event_header header;
* struct sample_id sample_id;
* };
*/
PERF_RECORD_SWITCH = 14,
/*
* CPU-wide version of PERF_RECORD_SWITCH with next_prev_pid and
* next_prev_tid that are the next (switching out) or previous
* (switching in) pid/tid.
*
* struct {
* struct perf_event_header header;
* u32 next_prev_pid;
* u32 next_prev_tid;
* struct sample_id sample_id;
* };
*/
PERF_RECORD_SWITCH_CPU_WIDE = 15,
/*
* struct {
* struct perf_event_header header;
* u32 pid;
* u32 tid;
* u64 nr_namespaces;
* { u64 dev, inode; } [nr_namespaces];
* struct sample_id sample_id;
* };
*/
PERF_RECORD_NAMESPACES = 16,
/*
* Record ksymbol register/unregister events:
*
* struct {
* struct perf_event_header header;
* u64 addr;
* u32 len;
* u16 ksym_type;
* u16 flags;
* char name[];
* struct sample_id sample_id;
* };
*/
PERF_RECORD_KSYMBOL = 17,
/*
* Record bpf events:
* enum perf_bpf_event_type {
* PERF_BPF_EVENT_UNKNOWN = 0,
* PERF_BPF_EVENT_PROG_LOAD = 1,
* PERF_BPF_EVENT_PROG_UNLOAD = 2,
* };
*
* struct {
* struct perf_event_header header;
* u16 type;
* u16 flags;
* u32 id;
* u8 tag[BPF_TAG_SIZE];
* struct sample_id sample_id;
* };
*/
PERF_RECORD_BPF_EVENT = 18,
/*
* struct {
* struct perf_event_header header;
* u64 id;
* char path[];
* struct sample_id sample_id;
* };
*/
PERF_RECORD_CGROUP = 19,
PERF_RECORD_MAX, /* non-ABI */
PERF_RECORD_USER_TYPE_START = 64,
PERF_RECORD_HEADER_ATTR = 64,
PERF_RECORD_HEADER_EVENT_TYPE = 65, /* deprecated */
PERF_RECORD_HEADER_TRACING_DATA = 66,
PERF_RECORD_HEADER_BUILD_ID = 67,
PERF_RECORD_FINISHED_ROUND = 68,
PERF_RECORD_ID_INDEX = 69,
PERF_RECORD_AUXTRACE_INFO = 70,
PERF_RECORD_AUXTRACE = 71,
PERF_RECORD_AUXTRACE_ERROR = 72,
PERF_RECORD_THREAD_MAP = 73,
PERF_RECORD_CPU_MAP = 74,
PERF_RECORD_STAT_CONFIG = 75,
PERF_RECORD_STAT = 76,
PERF_RECORD_STAT_ROUND = 77,
PERF_RECORD_EVENT_UPDATE = 78,
PERF_RECORD_TIME_CONV = 79,
PERF_RECORD_HEADER_FEATURE = 80,
PERF_RECORD_COMPRESSED = 81,
PERF_RECORD_FINISHED_INIT = 82,
PERF_RECORD_COMPRESSED2 = 83,
PERF_RECORD_BPF_METADATA = 84,
PERF_RECORD_HEADER_MAX
};
enum PERF_RECORD_MISC {
PERF_RECORD_MISC_SWITCH_OUT = (1 << 13),
};
class PerfRecordSample;
// Use first attribute for deciding if this is present, not the header!
// Why the first?!? idiots ... => encoded in sampleType via sampleIdAll
struct PerfSampleId {
PerfSampleId(quint64 sampleType = 0, bool sampleIdAll = false) : m_pid(0), m_tid(0), m_time(0),
m_id(0), m_streamId(0), m_cpu(0), m_res(0),
m_sampleType(sampleType
| (sampleIdAll ? static_cast(PerfEventAttributes::SAMPLE_ID_ALL) : 0))
{}
qint32 pid() const { return m_pid; }
qint32 tid() const { return m_tid; }
quint64 time() const { return m_time; }
quint64 id() const { return m_id; }
quint16 fixedLength() const;
quint64 sampleType() const { return m_sampleType; }
quint32 cpu() const { return m_cpu; }
private:
qint32 m_pid;
qint32 m_tid;
quint64 m_time;
quint64 m_id;
quint64 m_streamId;
quint32 m_cpu;
quint32 m_res;
union {
quint64 m_ignoredDuplicateId; // In the file format this is the same as id above
quint64 m_sampleType; // As the id is ignored we can reuse the space for saving the flags
};
friend QDataStream &operator>>(QDataStream &stream, PerfSampleId &sampleId);
friend QDataStream &operator>>(QDataStream &stream, PerfRecordSample &record);
};
QDataStream &operator>>(QDataStream &stream, PerfSampleId &sampleId);
class PerfRecord {
public:
qint32 pid() const { return m_sampleId.pid(); }
qint32 tid() const { return m_sampleId.tid(); }
quint64 time() const { return m_sampleId.time(); }
quint64 id() const { return m_sampleId.id(); }
quint32 cpu() const { return m_sampleId.cpu(); }
quint16 size() const { return m_header.size; }
quint16 misc() const { return m_header.misc; }
quint64 type() const { return m_sampleId.sampleType(); }
protected:
PerfRecord(const PerfEventHeader *header, quint64 sampleType, bool sampleIdAll);
PerfEventHeader m_header;
PerfSampleId m_sampleId;
quint16 fixedLength() const { return m_header.fixedLength() + m_sampleId.fixedLength(); }
};
class PerfRecordMmap2;
class PerfRecordMmap : public PerfRecord {
public:
PerfRecordMmap(PerfEventHeader *header = nullptr, quint64 sampleType = 0,
bool sampleIdAll = false);
// The pids and tids in the sampleId are always 0 in this case. Go figure ...
qint32 pid() const { return m_pid; }
qint32 tid() const { return m_tid; }
quint64 addr() const { return m_addr; }
quint64 len() const { return m_len; }
quint64 pgoff() const { return m_pgoff; }
const QByteArray &filename() const { return m_filename; }
protected:
QDataStream &readNumbers(QDataStream &stream);
QDataStream &readFilename(QDataStream &stream, quint16 filenameLength);
QDataStream &readSampleId(QDataStream &stream);
quint16 fixedLength() const;
private:
qint32 m_pid;
qint32 m_tid;
quint64 m_addr;
quint64 m_len;
quint64 m_pgoff;
QByteArray m_filename;
friend QDataStream &operator>>(QDataStream &stream, PerfRecordMmap &record);
friend QDataStream &operator>>(QDataStream &stream, PerfRecordMmap2 &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordMmap &record);
class PerfRecordMmap2 : public PerfRecordMmap
{
public:
PerfRecordMmap2(PerfEventHeader *header = nullptr, quint64 sampleType = 0,
bool sampleIdAll = false);
quint32 prot() const { return m_prot; }
protected:
QDataStream &readNumbers(QDataStream &stream);
private:
quint32 m_maj;
quint32 m_min;
quint64 m_ino;
quint64 m_ino_generation;
quint32 m_prot;
quint32 m_flags;
quint16 fixedLength() const;
friend QDataStream &operator>>(QDataStream &stream, PerfRecordMmap2 &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordMmap2 &record);
class PerfRecordLost : public PerfRecord {
public:
PerfRecordLost(PerfEventHeader *header = nullptr, quint64 sampleType = 0,
bool sampleIdAll = false);
quint64 lost() const { return m_lost; }
private:
quint64 m_id;
quint64 m_lost;
friend QDataStream &operator>>(QDataStream &stream, PerfRecordLost &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordLost &record);
class PerfRecordComm : public PerfRecord {
public:
PerfRecordComm(PerfEventHeader *header = nullptr, quint64 sampleType = 0,
bool sampleIdAll = false);
const QByteArray &comm() const { return m_comm; }
// The pids and tids in the sampleId are always 0 in this case. Go figure ...
qint32 pid() const { return m_pid; }
qint32 tid() const { return m_tid; }
private:
qint32 m_pid;
qint32 m_tid;
QByteArray m_comm;
quint16 fixedLength() const { return PerfRecord::fixedLength() + sizeof(m_pid) + sizeof(m_tid); }
friend QDataStream &operator>>(QDataStream &stream, PerfRecordComm &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordComm &record);
class PerfRecordSample : public PerfRecord {
public:
PerfRecordSample(const PerfEventHeader *header = nullptr,
const PerfEventAttributes *attributes = nullptr);
quint64 registerAbi() const { return m_registerAbi; }
quint64 registerValue(int reg) const;
quint64 ip() const { return m_ip; }
const QByteArray &userStack() const { return m_userStack; }
const QList &callchain() const { return m_callchain; }
quint64 period() const { return m_period; }
quint64 weight() const { return m_weight; }
const QByteArray &rawData() const { return m_rawData; }
struct ReadFormat {
quint64 value;
quint64 id;
quint64 lost;
};
QList readFormats() const { return m_readFormats; }
struct BranchFlags {
quint64 mispred: 1;
quint64 predicted: 1;
quint64 in_tx: 1;
quint64 abort: 1;
quint64 cycles: 16;
quint64 type: 4;
quint64 reserved: 40;
};
struct BranchEntry {
quint64 from;
quint64 to;
BranchFlags flags;
};
const QList &branchStack() const { return m_branchStack; }
private:
quint64 m_readFormat;
quint64 m_registerMask;
quint64 m_ip;
quint64 m_addr;
quint64 m_period;
quint64 m_timeEnabled;
quint64 m_timeRunning;
quint64 m_registerAbi;
quint64 m_weight;
quint64 m_dataSrc;
quint64 m_transaction;
QList m_readFormats;
QList m_callchain;
QByteArray m_rawData;
QList m_branchStack;
QList m_registers;
QByteArray m_userStack;
friend QDataStream &operator>>(QDataStream &stream, PerfRecordSample &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordSample &record);
class PerfRecordAttr : public PerfRecord
{
public:
PerfRecordAttr(const PerfEventHeader *header = nullptr, quint64 sampleType = 0,
bool sampleIdAll = false);
PerfRecordAttr(const PerfEventAttributes &attributes, const QList &ids);
const PerfEventAttributes &attr() const { return m_attr; }
const QList &ids() const { return m_ids; }
private:
PerfEventAttributes m_attr;
QList m_ids;
friend QDataStream &operator>>(QDataStream &stream, PerfRecordAttr &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordAttr &record);
class PerfRecordFork : public PerfRecord
{
public:
PerfRecordFork(PerfEventHeader *header = nullptr, quint64 sampleType = 0,
bool sampleIdAll = false);
qint32 childTid() const { return m_tid; }
qint32 childPid() const { return m_pid; }
qint32 parentTid() const { return m_ptid; }
qint32 parentPid() const { return m_ppid; }
private:
qint32 m_pid, m_ppid;
qint32 m_tid, m_ptid;
quint64 m_time;
friend QDataStream &operator>>(QDataStream &stream, PerfRecordFork &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordFork &record);
typedef PerfRecordFork PerfRecordExit;
class PerfRecordContextSwitch : public PerfRecord
{
public:
PerfRecordContextSwitch(PerfEventHeader *header = 0, quint64 sampleType = 0,
bool sampleIdAll = false);
private:
friend QDataStream &operator>>(QDataStream &stream, PerfRecordContextSwitch &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordContextSwitch &record);
class PerfRecordContextSwitchCpuWide : public PerfRecordContextSwitch
{
public:
PerfRecordContextSwitchCpuWide(PerfEventHeader *header = 0, quint64 sampleType = 0,
bool sampleIdAll = false);
qint32 nextPrevPid() const { return m_nextPrevPid; }
qint32 nextPrevTid() const { return m_nextPrevTid; }
private:
qint32 m_nextPrevPid;
qint32 m_nextPrevTid;
friend QDataStream &operator>>(QDataStream &stream, PerfRecordContextSwitchCpuWide &record);
};
QDataStream &operator>>(QDataStream &stream, PerfRecordContextSwitchCpuWide &record);
class PerfUnwind;
class PerfData : public QObject
{
Q_OBJECT
public:
PerfData(PerfUnwind *destination, const PerfHeader *header, PerfAttributes *attributes);
~PerfData();
void setSource(QIODevice *source);
bool setCompressed(const PerfCompressed &compressed);
public slots:
void read();
void finishReading();
signals:
void finished();
void error();
private:
enum ReadStatus {
Rerun,
SignalError,
SignalFinished
};
QIODevice *m_source;
PerfUnwind *m_destination;
const PerfHeader *m_header;
PerfAttributes *m_attributes;
PerfEventHeader m_eventHeader;
PerfTracingData m_tracingData;
PerfCompressed m_compressed;
QByteArray m_decompressBuffer;
QByteArray m_compressedBuffer;
int m_remaininingDecompressedDataSize = 0;
#if HAVE_ZSTD
ZSTD_DStream *m_zstdDstream = nullptr;
ReadStatus processCompressedEvents(QDataStream &stream, qint64 contentSize);
#endif
ReadStatus processEvents(QDataStream &stream);
ReadStatus doRead();
};
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfdwarfdiecache.cpp 0000664 0000000 0000000 00000030403 15057302234 0025230 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2020 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include
#include "perfdwarfdiecache.h"
#include "perfeucompat.h"
#include
#include
#include "demangler.h"
namespace {
enum class WalkResult
{
Recurse,
Skip,
Return
};
template
WalkResult walkDieTree(const Callback &callback, Dwarf_Die *die)
{
auto result = callback(die);
if (result != WalkResult::Recurse)
return result;
Dwarf_Die childDie;
if (dwarf_child(die, &childDie) == 0) {
result = walkDieTree(callback, &childDie);
if (result == WalkResult::Return)
return result;
Dwarf_Die siblingDie;
while (dwarf_siblingof(&childDie, &siblingDie) == 0) {
result = walkDieTree(callback, &siblingDie);
if (result == WalkResult::Return)
return result;
childDie = siblingDie;
}
}
return WalkResult::Skip;
}
template
void walkRanges(const Callback &callback, Dwarf_Die *die)
{
Dwarf_Addr low = 0;
Dwarf_Addr high = 0;
Dwarf_Addr base = 0;
ptrdiff_t rangeOffset = 0;
while ((rangeOffset = dwarf_ranges(die, rangeOffset, &base, &low, &high)) > 0) {
if (!callback(DwarfRange{low, high}))
return;
}
}
// see libdw_visit_scopes.c in elfutils
bool mayHaveScopes(Dwarf_Die *die)
{
switch (dwarf_tag(die))
{
/* DIEs with addresses we can try to match. */
case DW_TAG_compile_unit:
case DW_TAG_module:
case DW_TAG_lexical_block:
case DW_TAG_with_stmt:
case DW_TAG_catch_block:
case DW_TAG_try_block:
case DW_TAG_entry_point:
case DW_TAG_inlined_subroutine:
case DW_TAG_subprogram:
/* DIEs without addresses that can own DIEs with addresses. */
case DW_TAG_namespace:
case DW_TAG_class_type:
case DW_TAG_structure_type:
return true;
/* Other DIEs we have no reason to descend. */
default:
break;
}
return false;
}
bool dieContainsAddress(Dwarf_Die *die, Dwarf_Addr address)
{
bool contained = false;
walkRanges([&contained, address](DwarfRange range) {
if (range.contains(address)) {
contained = true;
return false;
}
return true;
}, die);
return contained;
}
}
const char *linkageName(Dwarf_Die *die)
{
Dwarf_Attribute attr;
Dwarf_Attribute *result = dwarf_attr_integrate(die, DW_AT_MIPS_linkage_name, &attr);
if (!result)
result = dwarf_attr_integrate(die, DW_AT_linkage_name, &attr);
return result ? dwarf_formstring(result) : nullptr;
}
Dwarf_Die *specificationDie(Dwarf_Die *die, Dwarf_Die *dieMem)
{
Dwarf_Attribute attr;
if (dwarf_attr_integrate(die, DW_AT_specification, &attr))
return dwarf_formref_die(&attr, dieMem);
return nullptr;
}
/// prepend the names of all scopes that reference the @p die to @p name
void prependScopeNames(QByteArray &name, Dwarf_Die *die, QHash &cache)
{
Dwarf_Die dieMem;
Dwarf_Die *scopes = nullptr;
auto nscopes = dwarf_getscopes_die(die, &scopes);
// We essentially visit and build the scope name in reverse order.
// The cache ops encode offsets we can lookup directly that then map to fully
// qualified identifiers, which must obviously _not_ end on a double-colon separator.
// Note that while filling cacheOps below, we thus always have to prepend the double-colon
// first to the name, then store the cacheOps with the size of `name`. While that may sound
// confusing, that gives us the desired results: `ScopesToCache::trailing` will then be set
// to the size _following_ the current entry, which may get more identifiers appended to
// it when we continue to visit the other DIEs next.
struct ScopesToCache
{
Dwarf_Off offset;
int trailing;
};
std::vector cacheOps;
// skip scope for the die itself at the start and the compile unit DIE at end
for (int i = 1; i < nscopes - 1; ++i) {
auto scope = scopes + i;
const auto scopeOffset = dwarf_dieoffset(scope);
auto it = cache.find(scopeOffset);
if (it != cache.end()) {
// prepend the fully qualified cached identifier
// that won't end on `::`, so we have to add that manually here
if (!name.isEmpty())
name.prepend("::");
name.prepend(*it);
// we can stop, cached names are always fully qualified
break;
}
if (auto scopeLinkageName = linkageName(scope)) {
// prepend the fully qualified linkage name
name.prepend("::");
cacheOps.push_back({scopeOffset, int(name.size())});
// we have to demangle the scope linkage name, otherwise we get a
// mish-mash of mangled and non-mangled names
name.prepend(demangle(scopeLinkageName));
// we can stop now, the scope is fully qualified
break;
}
if (auto scopeName = dwarf_diename(scope)) {
// prepend this scope's name, e.g. the class or namespace name
name.prepend("::");
cacheOps.push_back({scopeOffset, int(name.size())});
name.prepend(scopeName);
}
if (auto specification = specificationDie(scope, &dieMem)) {
eu_compat_free(scopes);
scopes = nullptr;
cacheOps.push_back({scopeOffset, int(name.size())});
cacheOps.push_back({dwarf_dieoffset(specification), int(name.size())});
// follow the scope's specification DIE instead
prependScopeNames(name, specification, cache);
break;
}
}
for (const auto &cacheOp : cacheOps)
cache[cacheOp.offset] = name.mid(0, name.size() - cacheOp.trailing);
eu_compat_free(scopes);
}
bool operator==(const Dwarf_Die &lhs, const Dwarf_Die &rhs)
{
return lhs.addr == rhs.addr && lhs.cu == rhs.cu && lhs.abbrev == rhs.abbrev;
}
QByteArray qualifiedDieName(Dwarf_Die *die, QHash &cache)
{
// linkage names are fully qualified, meaning we can stop early then
if (auto name = linkageName(die))
return name;
// otherwise do a more complex lookup that includes namespaces and other context information
// this is important for inlined subroutines such as lambdas or std:: algorithms
QByteArray name = dwarf_diename(die);
// use the specification DIE which is within the DW_TAG_namespace
Dwarf_Die dieMem;
if (auto specification = specificationDie(die, &dieMem))
die = specification;
prependScopeNames(name, die, cache);
return name;
}
QByteArray demangle(const QByteArray &mangledName)
{
if (mangledName.length() < 3) {
return mangledName;
} else {
static size_t demangleBufferLength = 8192;
static char *demangleBuffer = reinterpret_cast(eu_compat_malloc(demangleBufferLength));
static Demangler demangler;
if (demangler.demangle(mangledName, demangleBuffer, demangleBufferLength)) {
return demangleBuffer;
}
// Require GNU v3 ABI by the "_Z" prefix.
if (mangledName[0] == '_' && mangledName[1] == 'Z') {
int status = -1;
char *dsymname = eu_compat_demangle(mangledName.constData(), demangleBuffer, &demangleBufferLength,
&status);
if (status == 0)
return demangleBuffer = dsymname;
}
}
return mangledName;
}
QVector findInlineScopes(Dwarf_Die *subprogram, Dwarf_Addr offset)
{
QVector scopes;
walkDieTree([offset, &scopes](Dwarf_Die *die) {
if (dwarf_tag(die) != DW_TAG_inlined_subroutine)
return WalkResult::Recurse;
if (dieContainsAddress(die, offset)) {
scopes.append(*die);
return WalkResult::Recurse;
}
return WalkResult::Skip;
}, subprogram);
return scopes;
}
QByteArray absoluteSourcePath(const char *path, Dwarf_Die *cuDie)
{
if (!path || !cuDie || path[0] == '/')
return path;
Dwarf_Attribute attr;
auto compDir = dwarf_formstring(dwarf_attr(cuDie, DW_AT_comp_dir, &attr));
if (!compDir)
return path;
QByteArray ret;
ret.reserve(static_cast(strlen(compDir) + strlen(path) + 1));
ret.append(compDir);
ret.append('/');
ret.append(path);
return ret;
}
DwarfSourceLocation findSourceLocation(Dwarf_Die* cuDie, Dwarf_Addr offset)
{
DwarfSourceLocation ret;
if (auto srcloc = dwarf_getsrc_die(cuDie, offset)) {
if (const char* srcfile = dwarf_linesrc(srcloc, nullptr, nullptr)) {
ret.file = absoluteSourcePath(srcfile, cuDie);
dwarf_lineno(srcloc, &ret.line);
dwarf_linecol(srcloc, &ret.column);
}
}
return ret;
}
SubProgramDie::SubProgramDie(Dwarf_Die die)
: m_ranges{die, {}}
{
walkRanges([this](DwarfRange range) {
m_ranges.ranges.append(range);
return true;
}, &die);
}
SubProgramDie::~SubProgramDie() = default;
CuDieRangeMapping::CuDieRangeMapping(Dwarf_Die cudie, Dwarf_Addr bias)
: m_bias{bias}
, m_cuDieRanges{cudie, {}}
{
walkRanges([this, bias](DwarfRange range) {
m_cuDieRanges.ranges.append({range.low + bias, range.high + bias});
return true;
}, &cudie);
}
CuDieRangeMapping::~CuDieRangeMapping() = default;
SubProgramDie *CuDieRangeMapping::findSubprogramDie(Dwarf_Addr offset)
{
if (m_subPrograms.isEmpty())
addSubprograms();
auto it = std::find_if(m_subPrograms.begin(), m_subPrograms.end(),
[offset](const SubProgramDie &program) {
return program.contains(offset);
});
if (it == m_subPrograms.end())
return nullptr;
return &(*it);
}
void CuDieRangeMapping::addSubprograms()
{
walkDieTree([this](Dwarf_Die *die) {
if (!mayHaveScopes(die))
return WalkResult::Skip;
if (dwarf_tag(die) == DW_TAG_subprogram) {
SubProgramDie program(*die);
if (!program.isEmpty())
m_subPrograms.append(program);
return WalkResult::Skip;
}
return WalkResult::Recurse;
}, cudie());
}
QByteArray CuDieRangeMapping::dieName(Dwarf_Die *die)
{
// in QT6 QHash is no longer iterator safe
// since qualifiedDieName can modify m_dieNameCache we need to insert name again
const auto offset = dwarf_dieoffset(die);
auto name = m_dieNameCache[offset];
if (name.isEmpty()) {
name = demangle(qualifiedDieName(die, m_dieNameCache));
m_dieNameCache[offset] = name;
}
return name;
}
PerfDwarfDieCache::PerfDwarfDieCache(Dwfl_Module *mod)
{
if (!mod)
return;
Dwarf_Die *die = nullptr;
Dwarf_Addr bias = 0;
while ((die = dwfl_module_nextcu(mod, die, &bias))) {
CuDieRangeMapping cuDieMapping(*die, bias);
if (!cuDieMapping.isEmpty())
m_cuDieRanges.push_back(cuDieMapping);
}
}
PerfDwarfDieCache::~PerfDwarfDieCache() = default;
CuDieRangeMapping *PerfDwarfDieCache::findCuDie(Dwarf_Addr addr)
{
auto it = std::find_if(m_cuDieRanges.begin(), m_cuDieRanges.end(),
[addr](const CuDieRangeMapping &cuDieMapping) {
return cuDieMapping.contains(addr);
});
if (it == m_cuDieRanges.end())
return nullptr;
return &(*it);
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfdwarfdiecache.h 0000664 0000000 0000000 00000011712 15057302234 0024677 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2020 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include
#include
#include
#include
/// @return the demangled symbol name
QByteArray demangle(const QByteArray &mangledName);
struct DwarfRange
{
Dwarf_Addr low;
Dwarf_Addr high;
bool contains(Dwarf_Addr addr) const
{
return low <= addr && addr < high;
}
};
/// cache of dwarf ranges for a given Dwarf_Die
struct DieRanges
{
Dwarf_Die die;
QVector ranges;
bool contains(Dwarf_Addr addr) const
{
return std::any_of(ranges.begin(), ranges.end(), [addr](DwarfRange range) {
return range.contains(addr);
});
}
};
/// cache of sub program DIE, its ranges and the accompanying die name
class SubProgramDie
{
public:
SubProgramDie() = default;
SubProgramDie(Dwarf_Die die);
~SubProgramDie();
bool isEmpty() const { return m_ranges.ranges.isEmpty(); }
/// @p offset a bias-corrected offset
bool contains(Dwarf_Addr offset) const { return m_ranges.contains(offset); }
Dwarf_Die *die() { return &m_ranges.die; }
private:
DieRanges m_ranges;
};
/// cache of dwarf ranges for a CU DIE and child sub programs
class CuDieRangeMapping
{
public:
CuDieRangeMapping() = default;
CuDieRangeMapping(Dwarf_Die cudie, Dwarf_Addr bias);
~CuDieRangeMapping();
bool isEmpty() const { return m_cuDieRanges.ranges.isEmpty(); }
bool contains(Dwarf_Addr addr) const { return m_cuDieRanges.contains(addr); }
Dwarf_Addr bias() { return m_bias; }
Dwarf_Die *cudie() { return &m_cuDieRanges.die; }
/// On first call this will visit the CU DIE to cache all subprograms
/// @return the DW_TAG_subprogram DIE that contains @p offset
/// @p offset a bias-corrected address to find a subprogram for
SubProgramDie *findSubprogramDie(Dwarf_Addr offset);
/// @return a fully qualified, demangled symbol name for @p die
QByteArray dieName(Dwarf_Die *die);
private:
void addSubprograms();
Dwarf_Addr m_bias = 0;
DieRanges m_cuDieRanges;
QVector m_subPrograms;
QHash m_dieNameCache;
};
/**
* @return all DW_TAG_inlined_subroutine DIEs that contain @p offset
* @p subprogram DIE sub tree that should be traversed to look for inlined scopes
* @p offset bias-corrected address that is checked against the dwarf ranges of the DIEs
*/
QVector findInlineScopes(Dwarf_Die *subprogram, Dwarf_Addr offset);
/**
* @return the absolute source path for a @p path that may be absolute already or relative to the compilation directory
* @p path either an absolute that will be passed through directly or a path relative to the compilation directory
* @p cuDie the CU DIE that will be queried for the compilation directory to resolve relative paths
* @sa findSourceLocation
*/
QByteArray absoluteSourcePath(const char *path, Dwarf_Die *cuDie);
struct DwarfSourceLocation
{
QByteArray file;
int line = -1;
int column = -1;
explicit operator bool() const
{
return !file.isEmpty();
}
};
/**
* @return the absolute file name, line number and column for the instruction at the given @p offset in @p cuDie
* @p cuDie CU DIE that should be queried
* @p offset bias-corrected address of an instruction for which the information should be found
* @sa CuDieRangeMapping
*/
DwarfSourceLocation findSourceLocation(Dwarf_Die* cuDie, Dwarf_Addr offset);
/**
* This cache makes it easily possible to find a CU DIE (i.e. Compilation Unit Debugging Information Entry)
* based on a
*/
class PerfDwarfDieCache
{
public:
PerfDwarfDieCache(Dwfl_Module *mod = nullptr);
~PerfDwarfDieCache();
/// @p addr absolute address, not bias-corrected
CuDieRangeMapping *findCuDie(Dwarf_Addr addr);
public:
QVector m_cuDieRanges;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(DwarfRange, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(PerfDwarfDieCache, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(DieRanges, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(CuDieRangeMapping, Q_MOVABLE_TYPE);
Q_DECLARE_TYPEINFO(Dwarf_Die, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfelfmap.cpp 0000664 0000000 0000000 00000013705 15057302234 0023731 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfdata.h"
#include "perfelfmap.h"
#include
QDebug operator<<(QDebug stream, const PerfElfMap::ElfInfo& info)
{
stream.nospace() << "ElfInfo{"
<< "localFile=" << info.localFile.absoluteFilePath() << ", "
<< "isFile=" << info.isFile() << ", "
<< "originalFileName=" << info.originalFileName << ", "
<< "originalPath=" << info.originalPath << ", "
<< "addr=" << Qt::hex << info.addr << ", "
<< "len=" << Qt::hex << info.length << ", "
<< "pgoff=" << Qt::hex << info.pgoff << ", "
<< "baseAddr=";
if (info.hasBaseAddr())
stream << Qt::hex << info.baseAddr;
else
stream << "n/a";
stream << "}";
return stream.space();
}
namespace {
struct SortByAddr
{
bool operator()(const PerfElfMap::ElfInfo &lhs, const quint64 addr) const
{
return lhs.addr < addr;
}
bool operator()(const quint64 addr, const PerfElfMap::ElfInfo &rhs) const
{
return addr < rhs.addr;
}
};
}
PerfElfMap::PerfElfMap(QObject *parent)
: QObject(parent)
{
}
PerfElfMap::~PerfElfMap() = default;
void PerfElfMap::registerElf(quint64 addr, quint64 len, quint64 pgoff, quint64 baseAddr, const QFileInfo& fullPath,
const QByteArray& originalFileName, const QByteArray& originalPath)
{
quint64 addrEnd = addr + len;
QVarLengthArray newElfs;
QVarLengthArray removedElfs;
for (auto i = m_elfs.begin(), end = m_elfs.end(); i != end && i->addr < addrEnd; ++i) {
const quint64 iEnd = i->addr + i->length;
if (iEnd < addr)
continue;
if (addr - pgoff == i->addr - i->pgoff && originalPath == i->originalPath) {
// Remapping parts of the same file in the same place: Extend to maximum continuous
// address range and check if we already have that.
addr = qMin(addr, i->addr);
pgoff = qMin(pgoff, i->pgoff);
addrEnd = qMax(addrEnd, iEnd);
len = addrEnd - addr;
if (addr == i->addr && len == i->length) {
// New mapping is fully contained in old one: Nothing to do.
Q_ASSERT(newElfs.isEmpty());
Q_ASSERT(removedElfs.isEmpty());
return;
}
} else if (iEnd == addr) {
// Directly adjacent sections of the same file can be merged. Ones of different files
// don't bother each other.
continue;
}
// Newly added elf overwrites existing one. Mark the existing one as overwritten and
// reinsert any fragments of it that remain.
if (i->addr < addr) {
newElfs.push_back(ElfInfo(i->localFile, i->addr, addr - i->addr, i->pgoff, i->baseAddr, i->originalFileName,
i->originalPath));
}
if (iEnd > addrEnd) {
newElfs.push_back(ElfInfo(i->localFile, addrEnd, iEnd - addrEnd, i->pgoff + addrEnd - i->addr, i->baseAddr,
i->originalFileName, i->originalPath));
}
emit aboutToInvalidate(*i);
removedElfs.push_back(static_cast(std::distance(m_elfs.begin(), i)));
}
// remove the overwritten elfs, iterate from the back to not invalidate the indices
for (auto it = removedElfs.rbegin(), end = removedElfs.rend(); it != end; ++it)
m_elfs.remove(*it);
ElfInfo elf(fullPath, addr, len, pgoff, baseAddr, originalFileName, originalPath);
if (elf.isFile()) {
if (m_lastBase.originalPath == originalPath && elf.addr > m_lastBase.addr && !elf.hasBaseAddr())
elf.baseAddr = m_lastBase.addr;
else if (!pgoff)
m_lastBase = elf;
else
m_lastBase = ElfInfo();
}
newElfs.push_back(elf);
for (const auto &elf : newElfs) {
auto it = std::lower_bound(m_elfs.begin(), m_elfs.end(),
elf.addr, SortByAddr());
m_elfs.insert(it, elf);
}
}
PerfElfMap::ElfInfo PerfElfMap::findElf(quint64 ip) const
{
auto i = std::upper_bound(m_elfs.begin(), m_elfs.end(), ip, SortByAddr());
Q_ASSERT (i == m_elfs.constEnd() || i->addr != ip);
if (i != m_elfs.constBegin())
--i;
else
return ElfInfo();
if (i->dwflStart < i->dwflEnd)
return (i->dwflStart <= ip && i->dwflEnd > ip) ? *i : ElfInfo();
else
return (i->addr + i->length > ip) ? *i : ElfInfo();
}
void PerfElfMap::updateElf(quint64 addr, quint64 dwflStart, quint64 dwflEnd)
{
auto i = std::upper_bound(m_elfs.begin(), m_elfs.end(), addr, SortByAddr());
Q_ASSERT(i != m_elfs.begin());
--i;
Q_ASSERT(i->addr == addr);
i->dwflStart = dwflStart;
i->dwflEnd = dwflEnd;
}
bool PerfElfMap::isAddressInRange(quint64 addr) const
{
if (m_elfs.isEmpty())
return false;
const auto &first = m_elfs.first();
const auto &last = m_elfs.last();
return first.addr <= addr && addr < (last.addr + last.length);
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfelfmap.h 0000664 0000000 0000000 00000010053 15057302234 0023367 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include
#include
#include
class PerfElfMap : public QObject
{
Q_OBJECT
public:
struct ElfInfo {
enum {
INVALID_BASE_ADDR = std::numeric_limits::max()
};
explicit ElfInfo(const QFileInfo &localFile = QFileInfo(), quint64 addr = 0,
quint64 length = 0, quint64 pgoff = 0, quint64 baseAddr = INVALID_BASE_ADDR,
const QByteArray &originalFileName = {},
const QByteArray &originalPath = {}) :
localFile(localFile),
originalFileName(originalFileName.isEmpty()
? localFile.fileName().toLocal8Bit()
: originalFileName),
originalPath(originalPath.isEmpty()
? localFile.absoluteFilePath().toLocal8Bit()
: originalPath),
addr(addr), length(length), pgoff(pgoff), baseAddr(baseAddr)
{}
bool isValid() const
{
return length > 0;
}
bool isFile() const
{
return localFile.isFile();
}
bool hasBaseAddr() const
{
return baseAddr != INVALID_BASE_ADDR;
}
quint64 baseAddrOrFallback() const
{
return hasBaseAddr() ? baseAddr : (addr - pgoff);
}
bool operator==(const ElfInfo& rhs) const
{
return isFile() == rhs.isFile()
&& (!isFile() || localFile == rhs.localFile)
&& originalFileName == rhs.originalFileName
&& originalPath == rhs.originalPath
&& addr == rhs.addr
&& length == rhs.length
&& pgoff == rhs.pgoff
&& baseAddr == rhs.baseAddr;
}
bool operator!=(const ElfInfo& rhs) const
{
return !operator==(rhs);
}
QFileInfo localFile;
QByteArray originalFileName;
QByteArray originalPath;
quint64 addr;
quint64 length;
quint64 pgoff;
quint64 baseAddr = INVALID_BASE_ADDR;
quint64 dwflStart = 0;
quint64 dwflEnd = 0;
};
explicit PerfElfMap(QObject *parent = nullptr);
~PerfElfMap();
void registerElf(quint64 addr, quint64 len, quint64 pgoff, quint64 baseAddr, const QFileInfo& fullPath,
const QByteArray& originalFileName = {}, const QByteArray& originalPath = {});
ElfInfo findElf(quint64 ip) const;
void updateElf(quint64 addr, quint64 dwflStart, quint64 dwflEnd);
bool isEmpty() const
{
return m_elfs.isEmpty();
}
bool isAddressInRange(quint64 addr) const;
void copyDataFrom(const PerfElfMap *parent)
{
m_elfs = parent->m_elfs;
m_lastBase = parent->m_lastBase;
}
signals:
void aboutToInvalidate(const PerfElfMap::ElfInfo &elf);
private:
// elf sorted by start address
QVector m_elfs;
// last registered elf with zero pgoff
ElfInfo m_lastBase;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(PerfElfMap::ElfInfo, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
QDebug operator<<(QDebug stream, const PerfElfMap::ElfInfo& info);
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfeucompat.h 0000664 0000000 0000000 00000003003 15057302234 0023735 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include
#ifdef Q_OS_WIN
#include
#else
#include
#include
#define eu_compat_open open
#define eu_compat_close close
#define eu_compat_malloc malloc
#define eu_compat_free free
#define eu_compat_demangle abi::__cxa_demangle
#define eu_compat_strdup strdup
#define O_BINARY 0
#endif
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perffeatures.cpp 0000664 0000000 0000000 00000024634 15057302234 0024306 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perffeatures.h"
#include
#include
// TODO: What to do if feature flags are set but features don't really exist in the file?
static void removeTrailingZeros(QByteArray *string)
{
int length = string->length();
// chop off trailing zeros to make the values directly usable
while (length > 0 && !string->at(length - 1))
--length;
string->resize(length);
}
void PerfFeatures::createFeature(QIODevice *device, QDataStream::ByteOrder byteOrder,
PerfFileSection section, PerfHeader::Feature featureId)
{
device->seek(section.offset);
QDataStream stream(device);
stream.setByteOrder(byteOrder);
switch (featureId) {
case PerfHeader::TRACING_DATA:
if (section.size > std::numeric_limits::max()) {
qWarning() << "Excessively large tracing data section" << section.size;
} else if (section.size < 0) {
qWarning() << "Tracing data section with negative size" << section.size;
} else {
m_tracingData.setSize(static_cast(section.size));
stream >> m_tracingData;
}
break;
case PerfHeader::BUILD_ID:
m_buildId.size = section.size;
stream >> m_buildId;
break;
case PerfHeader::HOSTNAME:
stream >> m_hostName;
break;
case PerfHeader::OSRELEASE:
stream >> m_osRelease;
break;
case PerfHeader::VERSION:
stream >> m_version;
break;
case PerfHeader::ARCH:
stream >> m_arch;
break;
case PerfHeader::CPUDESC:
stream >> m_cpuDesc;
break;
case PerfHeader::CPUID:
stream >> m_cpuId;
break;
case PerfHeader::NRCPUS:
stream >> m_nrCpus;
break;
case PerfHeader::TOTAL_MEM:
stream >> m_totalMem;
break;
case PerfHeader::CMDLINE:
stream >> m_cmdline;
break;
case PerfHeader::EVENT_DESC:
stream >> m_eventDesc;
break;
case PerfHeader::CPU_TOPOLOGY:
stream >> m_cpuTopology;
break;
case PerfHeader::NUMA_TOPOLOGY:
stream >> m_numaToplogy;
break;
case PerfHeader::BRANCH_STACK:
// Doesn't really exist
break;
case PerfHeader::PMU_MAPPINGS:
stream >> m_pmuMappings;
break;
case PerfHeader::GROUP_DESC:
stream >> m_groupDesc;
break;
case PerfHeader::COMPRESSED:
stream >> m_compressed;
break;
default:
qDebug() << "unhandled feature" << featureId << section.size;
return;
}
qint64 readSize = device->pos() - section.offset;
if (section.size != readSize)
qWarning() << "feature not properly read" << featureId << section.size << readSize;
}
bool PerfFeatures::read(QIODevice *device, const PerfHeader *header)
{
if (!device->seek(header->featureOffset())) {
qWarning() << "cannot seek to" << header->featureOffset();
return false;
}
QDataStream stream(device);
stream.setByteOrder(header->byteOrder());
QHash featureSections;
PerfFileSection section;
for (uint i = 0; i < PerfHeader::LAST_FEATURE; ++i) {
auto feature = static_cast(i);
if (header->hasFeature(feature)) {
stream >> section;
if (section.size > 0)
featureSections[feature] = section;
else
qWarning() << "Feature announced in header but not present:" << feature;
}
}
QHash::ConstIterator i;
for (i = featureSections.constBegin(); i != featureSections.constEnd(); ++i)
createFeature(device, stream.byteOrder(), i.value(), i.key());
return true;
}
QDataStream &operator>>(QDataStream &stream, PerfBuildId &buildId)
{
qint64 next = 0;
while (next < buildId.size) {
PerfEventHeader header;
stream >> header;
if (!header.size)
break;
PerfBuildId::BuildId build;
stream >> build.pid;
build.id.resize(PerfBuildId::s_idLength);
stream.readRawData(build.id.data(), PerfBuildId::s_idLength);
stream.skipRawData(PerfBuildId::s_idPadding);
quint16 fileNameLength = header.size - PerfEventHeader::fixedLength() - sizeof(build.pid)
- PerfBuildId::s_idPadding - PerfBuildId::s_idLength;
build.fileName.resize(fileNameLength);
stream.readRawData(build.fileName.data(), fileNameLength);
removeTrailingZeros(&build.fileName);
next += header.size;
buildId.buildIds << build;
}
return stream;
}
QDataStream &operator<<(QDataStream &stream, const PerfBuildId::BuildId &buildId)
{
return stream << buildId.pid << buildId.id << buildId.fileName;
}
QDataStream &operator>>(QDataStream &stream, PerfEventHeader &header)
{
return stream >> header.type >> header.misc >> header.size;
}
QDataStream &operator>>(QDataStream &stream, PerfStringFeature &string)
{
quint32 length;
stream >> length;
static const int intMax = std::numeric_limits::max();
if (length > intMax) {
qWarning() << "Excessively long string" << length;
stream.skipRawData(intMax);
stream.skipRawData(static_cast(length - intMax));
return stream;
}
string.value.resize(static_cast(length));
stream.readRawData(string.value.data(), string.value.length());
removeTrailingZeros(&string.value);
return stream;
}
QDataStream &operator>>(QDataStream &stream, PerfNrCpus &nrCpus)
{
return stream >> nrCpus.online >> nrCpus.available;
}
QDataStream &operator<<(QDataStream &stream, PerfNrCpus nrCpus)
{
return stream << nrCpus.online << nrCpus.available;
}
QDataStream &operator>>(QDataStream &stream, PerfTotalMem &totalMem)
{
return stream >> totalMem.totalMem;
}
QDataStream &operator>>(QDataStream &stream, PerfCmdline &cmdline)
{
quint32 numParts;
stream >> numParts;
PerfStringFeature stringFeature;
while (numParts-- > 0) {
stream >> stringFeature;
cmdline.cmdline << stringFeature.value;
}
return stream;
}
QDataStream &operator>>(QDataStream &stream, PerfEventDesc &eventDesc)
{
quint32 numEvents;
quint32 eventSize;
quint32 numIds;
quint64 id;
stream >> numEvents >> eventSize;
PerfStringFeature stringFeature;
while (numEvents-- > 0) {
eventDesc.eventDescs << PerfEventDesc::EventDesc();
PerfEventDesc::EventDesc ¤tEvent = eventDesc.eventDescs.last();
stream >> currentEvent.attrs;
stream >> numIds;
stream >> stringFeature;
currentEvent.name = stringFeature.value;
while (numIds-- > 0) {
stream >> id;
currentEvent.ids << id;
}
}
// There is some additional length-encoded stuff after this, but perf doesn't read that, either.
// On top of that perf is only interested in the event name and throws everything else away
// after reading.
return stream;
}
QDataStream &operator>>(QDataStream &stream, PerfCpuTopology &cpuTopology)
{
quint32 numSiblings;
PerfStringFeature stringFeature;
stream >> numSiblings;
while (numSiblings-- > 0) {
stream >> stringFeature;
cpuTopology.siblingCores << stringFeature.value;
}
stream >> numSiblings;
while (numSiblings-- > 0) {
stream >> stringFeature;
cpuTopology.siblingThreads << stringFeature.value;
}
return stream;
}
QDataStream &operator<<(QDataStream &stream, const PerfCpuTopology &cpuTopology)
{
return stream << cpuTopology.siblingCores << cpuTopology.siblingThreads;
}
QDataStream &operator>>(QDataStream &stream, PerfNumaTopology &numaTopology)
{
quint32 numNodes;
stream >> numNodes;
PerfStringFeature stringFeature;
while (numNodes-- > 0) {
PerfNumaTopology::NumaNode node;
stream >> node.nodeId >> node.memTotal >> node.memFree >> stringFeature;
node.topology = stringFeature.value;
numaTopology.nodes << node;
}
return stream;
}
QDataStream &operator<<(QDataStream &stream, const PerfNumaTopology::NumaNode &node)
{
return stream << node.nodeId << node.memTotal << node.memFree << node.topology;
}
QDataStream &operator>>(QDataStream &stream, PerfPmuMappings &pmuMappings)
{
quint32 numPmus;
stream >> numPmus;
PerfStringFeature stringFeature;
while (numPmus-- > 0) {
PerfPmuMappings::Pmu pmu;
stream >> pmu.type >> stringFeature;
pmu.name = stringFeature.value;
pmuMappings.pmus << pmu;
}
return stream;
}
QDataStream &operator<<(QDataStream &stream, const PerfPmuMappings::Pmu &pmu)
{
return stream << pmu.type << pmu.name;
}
QDataStream &operator>>(QDataStream &stream, PerfGroupDesc &groupDesc)
{
quint32 numGroups;
stream >> numGroups;
PerfStringFeature stringFeature;
while (numGroups-- > 0) {
PerfGroupDesc::GroupDesc desc;
stream >> stringFeature;
desc.name = stringFeature.value;
stream >> desc.leaderIndex >> desc.numMembers;
groupDesc.groupDescs << desc;
}
return stream;
}
QDataStream &operator<<(QDataStream &stream, const PerfGroupDesc::GroupDesc &groupDesc)
{
return stream << groupDesc.name << groupDesc.leaderIndex << groupDesc.numMembers;
}
QDataStream &operator>>(QDataStream &stream, PerfCompressed &compressed)
{
stream >> compressed.version;
stream >> compressed.type;
stream >> compressed.level;
stream >> compressed.ratio;
stream >> compressed.mmap_len;
return stream;
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perffeatures.h 0000664 0000000 0000000 00000014347 15057302234 0023753 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include "perfattributes.h"
#include "perfheader.h"
#include "perftracingdata.h"
#include
#include
struct PerfEventHeader {
quint32 type = 0;
quint16 misc = 0;
quint16 size = 0;
static quint16 fixedLength() { return sizeof(type) + sizeof(misc) + sizeof(size); }
};
QDataStream &operator>>(QDataStream &stream, PerfEventHeader &header);
struct PerfBuildId {
static const quint16 s_idLength = 20;
static const quint16 s_idPadding = 4; // 20 aligned to 8 gives 24 => 4 unused bytes
static const quint16 s_pathMax = 4096;
struct BuildId {
qint32 pid;
QByteArray id; // raw id, use .toHex() to get something human-readable
QByteArray fileName;
};
qint64 size = 0;
QList buildIds;
};
QDataStream &operator>>(QDataStream &stream, PerfBuildId &buildId);
QDataStream &operator<<(QDataStream &stream, const PerfBuildId::BuildId &buildId);
struct PerfStringFeature {
QByteArray value;
};
QDataStream &operator>>(QDataStream &stream, PerfStringFeature &stringFeature);
struct PerfNrCpus {
quint32 online;
quint32 available;
};
QDataStream &operator>>(QDataStream &stream, PerfNrCpus &nrCpus);
QDataStream &operator<<(QDataStream &stream, PerfNrCpus nrCpus);
struct PerfTotalMem {
quint64 totalMem;
};
QDataStream &operator>>(QDataStream &stream, PerfTotalMem &totalMem);
struct PerfCmdline {
QList cmdline;
};
QDataStream &operator>>(QDataStream &stream, PerfCmdline &cmdline);
struct PerfEventDesc {
struct EventDesc {
PerfEventAttributes attrs;
QByteArray name;
QList ids;
};
QList eventDescs;
};
QDataStream &operator>>(QDataStream &stream, PerfEventDesc &eventDesc);
struct PerfCpuTopology {
// Some kind of bitmask. Not so important for now
QList siblingCores;
QList siblingThreads;
};
QDataStream &operator>>(QDataStream &stream, PerfCpuTopology &cpuTopology);
QDataStream &operator<<(QDataStream &stream, const PerfCpuTopology &cpuTopology);
struct PerfNumaTopology {
struct NumaNode {
quint32 nodeId = 0;
quint64 memTotal = 0;
quint64 memFree = 0;
QByteArray topology;
};
QList nodes;
};
QDataStream &operator>>(QDataStream &stream, PerfNumaTopology &numaTopology);
QDataStream &operator<<(QDataStream &stream, const PerfNumaTopology::NumaNode &numaNode);
struct PerfPmuMappings {
struct Pmu {
quint32 type = 0;
QByteArray name;
};
QList pmus;
};
QDataStream &operator>>(QDataStream &stream, PerfPmuMappings &pmuMappings);
QDataStream &operator<<(QDataStream &stream, const PerfPmuMappings::Pmu &pmu);
struct PerfGroupDesc {
struct GroupDesc {
QByteArray name;
quint32 leaderIndex = 0;
quint32 numMembers = 0;
};
QList groupDescs;
};
QDataStream &operator>>(QDataStream &stream, PerfGroupDesc &groupDesc);
QDataStream &operator<<(QDataStream &stream, const PerfGroupDesc::GroupDesc &groupDesc);
struct PerfCompressed {
quint32 version = 0;
quint32 type = 0;
quint32 level = 0;
quint32 ratio = 0;
quint32 mmap_len = 0;
enum Type {
PERF_COMP_NONE = 0,
PERF_COMP_ZSTD,
PERF_COMP_MAX
};
Q_ENUM(Type)
Q_GADGET
};
QDataStream &operator>>(QDataStream &stream, PerfCompressed &compressed);
class PerfFeatures
{
public:
bool read(QIODevice *device, const PerfHeader *header);
const QByteArray &architecture() const { return m_arch.value; }
void setArchitecture(const QByteArray &arch) { m_arch.value = arch; }
PerfTracingData tracingData() const { return m_tracingData; }
QList buildIds() const { return m_buildId.buildIds; }
QByteArray hostName() const { return m_hostName.value; }
QByteArray osRelease() const { return m_osRelease.value; }
QByteArray version() const { return m_version.value; }
PerfNrCpus nrCpus() const { return m_nrCpus; }
QByteArray cpuDesc() const { return m_cpuDesc.value; }
QByteArray cpuId() const { return m_cpuId.value; }
quint64 totalMem() const { return m_totalMem.totalMem; }
QList cmdline() const { return m_cmdline.cmdline; }
PerfEventDesc eventDesc() const { return m_eventDesc; }
PerfCpuTopology cpuTopology() const { return m_cpuTopology; }
QList numaTopology() const { return m_numaToplogy.nodes; }
QList pmuMappings() const { return m_pmuMappings.pmus; }
QList groupDescs() const { return m_groupDesc.groupDescs; }
PerfCompressed compressed() const { return m_compressed; }
private:
void createFeature(QIODevice *device, QDataStream::ByteOrder byteOrder,
PerfFileSection section, PerfHeader::Feature featureId);
PerfTracingData m_tracingData;
PerfBuildId m_buildId;
PerfStringFeature m_hostName;
PerfStringFeature m_osRelease;
PerfStringFeature m_version;
PerfStringFeature m_arch;
PerfNrCpus m_nrCpus;
PerfStringFeature m_cpuDesc;
PerfStringFeature m_cpuId;
PerfTotalMem m_totalMem;
PerfCmdline m_cmdline;
PerfEventDesc m_eventDesc;
PerfCpuTopology m_cpuTopology;
PerfNumaTopology m_numaToplogy;
PerfPmuMappings m_pmuMappings;
PerfGroupDesc m_groupDesc;
PerfCompressed m_compressed;
};
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perffilesection.cpp 0000664 0000000 0000000 00000002156 15057302234 0024767 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perffilesection.h"
QDataStream &operator>>(QDataStream &stream, PerfFileSection §ion)
{
return stream >> section.offset >> section.size;
}
PerfFileSection::PerfFileSection() : offset(0), size(0) {}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perffilesection.h 0000664 0000000 0000000 00000002245 15057302234 0024433 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include
struct PerfFileSection {
PerfFileSection();
qint64 offset;
qint64 size;
static quint16 fixedLength() { return sizeof(offset) + sizeof(size); }
};
QDataStream &operator>>(QDataStream &stream, PerfFileSection §ion);
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfheader.cpp 0000664 0000000 0000000 00000012557 15057302234 0023721 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfheader.h"
#include
#include
PerfHeader::PerfHeader(QIODevice *source) :
m_source(source)
{
connect(source, &QIODevice::readyRead, this, &PerfHeader::read);
connect(source, &QIODevice::aboutToClose, this, &PerfHeader::error);
}
void PerfHeader::read()
{
QDataStream stream(m_source);
if (m_size == 0) {
if (!m_source->isSequential() && m_source->size() < pipeHeaderFixedLength()) {
qWarning() << "File is too small for perf header.";
emit error();
return;
}
if (m_source->bytesAvailable() < pipeHeaderFixedLength())
return;
stream >> m_magic;
if (m_magic != s_magicSame && m_magic != s_magicSwitched) {
qWarning() << "invalid magic:" << m_magic;
qWarning() << "we don't support V1 perf data";
emit error();
return;
} else {
stream.setByteOrder(byteOrder());
}
stream >> m_size;
}
if (m_size < pipeHeaderFixedLength()) {
qWarning() << "Header claims to be smaller than magic + size:" << m_size;
emit error();
return;
} else if (m_size > pipeHeaderFixedLength()) {
// read extended header information only available in perf.data files,
// not in piped perf streams
if (!m_source->isSequential() && m_source->size() < fileHeaderFixedLength()) {
qWarning() << "File is too small for perf header.";
emit error();
return;
}
if (m_source->bytesAvailable() < fileHeaderFixedLength() - pipeHeaderFixedLength())
return;
// file header
stream >> m_attrSize >> m_attrs >> m_data >> m_eventTypes;
for (auto &feature : m_features)
stream >> feature;
if (m_magic == s_magicSwitched && !hasFeature(HOSTNAME) && !hasFeature(CMDLINE)) {
for (auto &feature : m_features)
{
static_assert(std::is_same::type, quint64>::value, "");
auto feature32 = reinterpret_cast(&feature);
qSwap(feature32[0], feature32[1]);
}
if (!hasFeature(HOSTNAME) && !hasFeature(CMDLINE)) {
// It borked: blank it all
qWarning() << "bad feature data:" << m_features;
std::fill(std::begin(m_features), std::end(m_features), 0);
setFeature(BUILD_ID);
}
}
const auto minimumFileSize = static_cast(dataOffset() + dataSize());
if (!m_source->isSequential() && m_source->size() < minimumFileSize) {
qWarning() << "File is too small to hold perf data.";
emit error();
return;
}
if (m_size > fileHeaderFixedLength()) {
if (m_size > std::numeric_limits::max()) {
qWarning() << "Excessively large perf file header:" << m_size;
emit error();
return;
}
qWarning() << "Header not completely read.";
stream.skipRawData(static_cast(m_size) - fileHeaderFixedLength());
}
} else {
// pipe header, anything to do here?
}
disconnect(m_source, &QIODevice::readyRead, this, &PerfHeader::read);
disconnect(m_source, &QIODevice::aboutToClose, this, &PerfHeader::error);
m_source = nullptr;
emit finished();
}
quint16 PerfHeader::pipeHeaderFixedLength()
{
return sizeof(m_magic) + sizeof(m_size);
}
quint16 PerfHeader::fileHeaderFixedLength()
{
return pipeHeaderFixedLength() + sizeof(m_attrSize)
+ static_cast(3 * PerfFileSection::fixedLength()) // m_attrs, m_data, m_eventTypes
+ sizeof(m_features);
}
QDataStream::ByteOrder PerfHeader::byteOrder() const
{
// magic is read in QDataStream's default big endian mode
return m_magic == s_magicSame ? QDataStream::BigEndian : QDataStream::LittleEndian;
}
void PerfHeader::setFeature(PerfHeader::Feature feature)
{
Q_ASSERT(feature >= 0 && feature < FEAT_BITS);
m_features[feature / 64] |= (1ULL << (feature % 64));
}
void PerfHeader::clearFeature(PerfHeader::Feature feature)
{
Q_ASSERT(feature >= 0 && feature < FEAT_BITS);
m_features[feature / 64] &= ~(1ULL << (feature % 64));
}
bool PerfHeader::hasFeature(PerfHeader::Feature feature) const
{
Q_ASSERT(feature >= 0 && feature < FEAT_BITS);
return (m_features[feature / 64] & (1ULL << (feature % 64))) != 0;
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfheader.h 0000664 0000000 0000000 00000006102 15057302234 0023353 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include "perffilesection.h"
#include
#include
class PerfHeader : public QObject {
Q_OBJECT
public:
PerfHeader(QIODevice *source);
enum Feature {
RESERVED = 0, /* always cleared */
FIRST_FEATURE = 1,
TRACING_DATA = 1,
BUILD_ID,
HOSTNAME,
OSRELEASE,
VERSION,
ARCH,
NRCPUS,
CPUDESC,
CPUID,
TOTAL_MEM,
CMDLINE,
EVENT_DESC,
CPU_TOPOLOGY,
NUMA_TOPOLOGY,
BRANCH_STACK,
PMU_MAPPINGS,
GROUP_DESC,
AUXTRACE,
STAT,
CACHE,
SAMPLE_TIME,
MEM_TOPOLOGY,
CLOCKID,
DIR_FORMAT,
BPF_PROG_INFO,
BPF_BTF,
COMPRESSED,
CPU_PMU_CAPS,
LAST_FEATURE,
FEAT_BITS = 256,
};
Q_ENUM(Feature)
QDataStream::ByteOrder byteOrder() const;
bool hasFeature(Feature feature) const;
void setFeature(Feature feature);
void clearFeature(Feature feature);
qint64 numAttrs() const { return m_attrs.size > 0 ? m_attrs.size / m_attrSize : 0ll; }
qint64 attrSize() const { return m_attrSize; }
const PerfFileSection &attrs() const { return m_attrs; }
qint64 featureOffset() const { return m_data.offset + m_data.size; }
qint64 dataOffset() const { return m_data.offset; }
qint64 dataSize() const { return m_data.size; }
bool isPipe() const { return m_size == pipeHeaderFixedLength(); }
qint64 size() const { return m_size; }
public slots:
void read();
signals:
void finished();
void error();
private:
static quint16 fileHeaderFixedLength();
static quint16 pipeHeaderFixedLength();
QIODevice *m_source = nullptr;
qint64 m_magic = 0;
qint64 m_size = 0;
qint64 m_attrSize = 0;
PerfFileSection m_attrs;
PerfFileSection m_data;
PerfFileSection m_eventTypes;
static_assert(FEAT_BITS % 64 == 0, "");
static constexpr quint64 NUM_FEATURES = FEAT_BITS / 64;
quint64 m_features[NUM_FEATURES] = {0};
static const qint64 s_magicSame = 0x32454c4946524550LL;
static const qint64 s_magicSwitched = 0x50455246494c4532LL;
};
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfkallsyms.cpp 0000664 0000000 0000000 00000005405 15057302234 0024322 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfkallsyms.h"
#include
#include
#include
#include
bool PerfKallsyms::parseMapping(const QString &path)
{
m_entries.clear();
m_errorString.clear();
QFile file(path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
m_errorString = file.errorString();
return false;
}
QTextStream stream(&file);
stream.setLocale(QLocale::c());
QByteArray address;
// NOTE: don't use atEnd here, as /proc/kallsyms is has size of 0
bool valid = true;
while (true) {
PerfKallsymEntry entry;
char type = 0;
char eol = '\n';
stream >> address >> Qt::ws >> type >> Qt::ws >> entry.symbol >> eol;
if (address.isEmpty())
break;
bool ok = false;
entry.address = address.toULongLong(&ok, 16);
if (!ok && address != "(null)") {
m_errorString = tr("Invalid address: %1").arg(QString::fromUtf8(address));
valid = false;
break;
}
if (eol == '\t')
stream >> entry.module;
if (entry.address != 0)
m_entries.push_back(entry);
}
if (valid && m_entries.isEmpty()) {
m_errorString = tr("Mapping is empty.");
return false;
}
std::sort(m_entries.begin(), m_entries.end(),
[](const PerfKallsymEntry& lhs, const PerfKallsymEntry& rhs) -> bool {
return lhs.address < rhs.address;
});
return valid;
}
PerfKallsymEntry PerfKallsyms::findEntry(quint64 address) const
{
auto entry = std::upper_bound(m_entries.begin(), m_entries.end(), address,
[](quint64 address, const PerfKallsymEntry& entry) -> bool {
return address < entry.address;
});
if (entry != m_entries.begin()) {
--entry;
return *entry;
}
return {};
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfkallsyms.h 0000664 0000000 0000000 00000003043 15057302234 0023763 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2017 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include
#include
#include
struct PerfKallsymEntry
{
quint64 address = 0;
QByteArray symbol;
QByteArray module;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_TYPEINFO(PerfKallsymEntry, Q_MOVABLE_TYPE);
QT_END_NAMESPACE
class PerfKallsyms
{
Q_DECLARE_TR_FUNCTIONS(PerfKallsyms)
public:
bool parseMapping(const QString &path);
QString errorString() const { return m_errorString; }
bool isEmpty() const { return m_entries.isEmpty(); }
PerfKallsymEntry findEntry(quint64 address) const;
private:
QVector m_entries;
QString m_errorString;
};
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfregisterinfo.cpp 0000664 0000000 0000000 00000010607 15057302234 0025163 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfregisterinfo.h"
#include
#include
const int PerfRegisterInfo::s_numRegisters[PerfRegisterInfo::ARCH_INVALID][PerfRegisterInfo::s_numAbis] = {
{16, 16},
{33, 33},
{ 0, 0},
{ 0, 0},
{ 0, 0},
{ 0, 0},
{ 9, 17},
};
const int PerfRegisterInfo::s_wordWidth[PerfRegisterInfo::ARCH_INVALID][PerfRegisterInfo::s_numAbis] = {
{4, 4},
{8, 8},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{4, 8},
};
// Perf and Dwarf register layouts are the same for ARM and ARM64
static int arm[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
static int aarch64[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
// X86 is a mess
static int x86[] = {0, 2, 3, 1, 7, 6, 4, 5, 8};
static int x86_64[] = {0, 3, 2, 1, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23, 8};
#ifdef mips
// On MIPS systems, "mips" is a built-in compiler macro.
#undef mips
#endif
static int mips[] = { 32, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31};
static int none[] = {0};
const int *PerfRegisterInfo::s_perfToDwarf[PerfRegisterInfo::ARCH_INVALID][PerfRegisterInfo::s_numAbis] = {
{arm, arm },
{aarch64, aarch64},
{none, none },
{none, none },
{none, none },
{none, none },
{x86, x86_64 },
{mips, mips },
};
const int PerfRegisterInfo::s_perfIp[ARCH_INVALID] = {
15, 32, 0xffff, 0xffff, 0xffff, 0xffff, 8
};
const int PerfRegisterInfo::s_perfSp[ARCH_INVALID] = {
13, 31, 0xffff, 0xffff, 0xffff, 0xffff, 7
};
const int PerfRegisterInfo::s_dwarfLr[ARCH_INVALID][s_numAbis] = {
{14, 14},
{30, 30},
{0xffff, 0xffff},
{0xffff, 0xffff},
{0xffff, 0xffff},
{0xffff, 0xffff},
{0xffff, 0xffff}
};
const int PerfRegisterInfo::s_dwarfIp[ARCH_INVALID][s_numAbis] = {
{15, 15},
{32, 32},
{0xffff, 0xffff},
{0xffff, 0xffff},
{0xffff, 0xffff},
{0xffff, 0xffff},
{8, 16}
};
const int PerfRegisterInfo::s_dummyRegisters[ARCH_INVALID][2] = {
{0, 0},
{72, 80},
{0, 0},
{0, 0},
{0, 0},
{0, 0},
{0, 0}
};
QString PerfRegisterInfo::defaultArchitecture()
{
#if defined(__aarch64__)
return QStringLiteral("aarch64");
#elif defined(__arm__)
return QStringLiteral("arm");
#elif defined(__powerpc__)
return QStringLiteral("powerpc");
#elif defined(__s390__)
return QStringLiteral("s390");
#elif defined(__sh__)
return QStringLiteral("sh");
#elif defined(__sparc__)
return QStringLiteral("sparc");
#elif defined(__i386__) || defined(__x86_64__)
return QStringLiteral("x86");
#else
return QString();
#endif
}
PerfRegisterInfo::Architecture PerfRegisterInfo::archByName(const QByteArray &name)
{
if (name == "aarch64" || name == "arm64")
return ARCH_AARCH64;
if (name.startsWith("arm"))
return ARCH_ARM;
if (name.startsWith("powerpc"))
return ARCH_POWERPC;
if (name.startsWith("s390"))
return ARCH_S390;
if (name.startsWith("sh"))
return ARCH_SH;
if (name.startsWith("sparc"))
return ARCH_SPARC;
if (name.startsWith("x86") || name == "i386" || name == "i486" || name == "i586" || name == "i686" || name == "i786"
|| name == "amd64")
return ARCH_X86;
if (name.startsWith("mips"))
return ARCH_MIPS;
return ARCH_INVALID;
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfregisterinfo.h 0000664 0000000 0000000 00000005016 15057302234 0024626 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include
class PerfRegisterInfo
{
public:
enum Architecture {
ARCH_ARM = 0,
ARCH_AARCH64,
ARCH_POWERPC,
ARCH_S390,
ARCH_SH,
ARCH_SPARC,
ARCH_X86,
ARCH_MIPS,
ARCH_INVALID
};
static const int s_numAbis = 2; // maybe more for some archs?
static Architecture archByName(const QByteArray &name);
static const int s_numRegisters[ARCH_INVALID][s_numAbis];
static const int s_wordWidth[ARCH_INVALID][s_numAbis];
// Translation table for converting perf register layout to dwarf register layout
// This is specific to ABI as the different ABIs may have different numbers of registers.
static const int *s_perfToDwarf[ARCH_INVALID][s_numAbis];
// location of IP register or equivalent in perf register layout for each arch/abi
// This is not specific to ABI as perf makes sure IP is always in the same spot
static const int s_perfIp[ARCH_INVALID];
// location of SP register or equivalent in perf register layout for each arch/abi
static const int s_perfSp[ARCH_INVALID];
// location of LR register or equivalent in dwarf register layout for each arch/abi
static const int s_dwarfLr[ARCH_INVALID][s_numAbis];
// location of IP register or equivalent in dwarf register layout for each arch/abi
static const int s_dwarfIp[ARCH_INVALID][s_numAbis];
// ranges of registers expected by libdw, but not provided by perf
static const int s_dummyRegisters[ARCH_INVALID][2];
// default architecture for the system which was used for compilation
static QString defaultArchitecture();
};
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfstdin.cpp 0000664 0000000 0000000 00000007773 15057302234 0023616 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#include "perfstdin.h"
#include
#include
#include
#include
PerfStdin::PerfStdin(QObject *parent) : QIODevice(parent)
{
connect(&m_timer, &QTimer::timeout, this, &PerfStdin::receiveData);
}
PerfStdin::~PerfStdin()
{
if (isOpen())
close();
}
bool PerfStdin::open(QIODevice::OpenMode mode)
{
if (!(mode & QIODevice::ReadOnly) || (mode & QIODevice::WriteOnly))
return false;
if (QIODevice::open(mode)) {
m_buffer.resize(s_minBufferSize);
m_timer.start();
return true;
} else {
return false;
}
}
void PerfStdin::close()
{
m_timer.stop();
QIODevice::close();
}
qint64 PerfStdin::readData(char *data, qint64 maxlen)
{
if (maxlen <= 0)
return 0;
qint64 read = 0;
do {
Q_ASSERT(m_buffer.length() >= m_bufferPos);
Q_ASSERT(m_buffer.length() >= m_bufferUsed);
Q_ASSERT(m_bufferPos <= m_bufferUsed);
const size_t buffered = static_cast(qMin(bufferedAvailable(), maxlen - read));
memcpy(data + read, m_buffer.constData() + m_bufferPos, buffered);
m_bufferPos += static_cast(buffered);
read += static_cast(buffered);
} while (read < maxlen && fillBuffer(maxlen) > 0);
Q_ASSERT(read > 0 || bufferedAvailable() == 0);
return (read == 0 && stdinAtEnd()) ? -1 : read;
}
qint64 PerfStdin::writeData(const char *data, qint64 len)
{
Q_UNUSED(data);
Q_UNUSED(len);
return -1;
}
void PerfStdin::receiveData()
{
if (fillBuffer() > 0)
emit readyRead();
else if (stdinAtEnd())
close();
}
void PerfStdin::resizeBuffer(int newSize)
{
QByteArray newBuffer(newSize, Qt::Uninitialized);
std::memcpy(newBuffer.data(), m_buffer.data() + m_bufferPos,
static_cast(m_bufferUsed - m_bufferPos));
qSwap(m_buffer, newBuffer);
m_bufferUsed -= m_bufferPos;
Q_ASSERT(m_buffer.length() >= m_bufferUsed);
m_bufferPos = 0;
}
qint64 PerfStdin::fillBuffer(qint64 targetBufferSize)
{
if (m_bufferUsed == m_bufferPos)
m_bufferPos = m_bufferUsed = 0;
targetBufferSize = qMin(targetBufferSize, static_cast(s_maxBufferSize));
if (targetBufferSize > m_buffer.length())
resizeBuffer(static_cast(targetBufferSize));
if (m_bufferUsed == m_buffer.length()) {
if (m_bufferPos == 0) {
resizeBuffer(m_bufferUsed <= s_maxBufferSize / 2 ? m_bufferUsed * 2
: s_maxBufferSize);
} else {
resizeBuffer(m_bufferUsed);
}
}
const size_t read = fread(m_buffer.data() + m_bufferUsed, 1,
static_cast(m_buffer.length() - m_bufferUsed), stdin);
m_bufferUsed += static_cast(read);
Q_ASSERT(m_buffer.length() >= m_bufferUsed);
return static_cast(read);
}
bool PerfStdin::stdinAtEnd() const
{
return feof(stdin) || ferror(stdin);
}
bool PerfStdin::isSequential() const
{
return true;
}
qint64 PerfStdin::bytesAvailable() const
{
return bufferedAvailable() + QIODevice::bytesAvailable();
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfstdin.h 0000664 0000000 0000000 00000003401 15057302234 0023243 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd
** All rights reserved.
** For any questions to The Qt Company, please use contact form at http://www.qt.io/contact-us
**
** This file is part of the Qt Enterprise Perf Profiler Add-on.
**
** GNU General Public License Usage
** This file may be used under the terms of the GNU General Public License
** version 3 as published by the Free Software Foundation and appearing in
** the file LICENSE.GPLv3 included in the packaging of this file. Please
** review the following information to ensure the GNU General Public License
** requirements will be met: https://www.gnu.org/licenses/gpl.html.
**
** If you have questions regarding the use of this file, please use
** contact form at http://www.qt.io/contact-us
**
****************************************************************************/
#pragma once
#include
#include
class PerfStdin final : public QIODevice
{
Q_OBJECT
public:
PerfStdin(QObject *parent = nullptr);
~PerfStdin();
bool open(OpenMode mode) override;
void close() override;
bool isSequential() const override;
qint64 bytesAvailable() const override;
protected:
qint64 readData(char *data, qint64 maxlen) override;
qint64 writeData(const char *data, qint64 len) override;
private:
static const int s_minBufferSize = 1 << 10;
static const int s_maxBufferSize = 1 << 30;
void receiveData();
void resizeBuffer(int newSize);
qint64 fillBuffer(qint64 targetSize = -1);
qint64 bufferedAvailable() const { return m_bufferUsed - m_bufferPos; }
bool stdinAtEnd() const;
QTimer m_timer;
QByteArray m_buffer;
int m_bufferPos = 0;
int m_bufferUsed = 0;
};
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfsymboltable.cpp 0000664 0000000 0000000 00000114301 15057302234 0024774 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "perfsymboltable.h"
#include "perfunwind.h"
#include "perfdwarfdiecache.h"
#include "perfeucompat.h"
#include
#include
#include
#include
#include
#include
#include // generated by cmake
#include
#include
#if HAVE_DWFL_GET_DEBUGINFOD_CLIENT
#include
#endif
namespace {
QString perfMapFile(const QString& customPerfMapPath, int pid)
{
if (!customPerfMapPath.isEmpty()) {
QString path = customPerfMapPath + QDir::separator() + QLatin1String("perf-%1.map").arg(QString::number(pid));
if (QFile::exists(path)) {
return path;
}
}
return QDir::tempPath() + QDir::separator() + QLatin1String("perf-%1.map").arg(QString::number(pid));
}
}
PerfSymbolTable::PerfSymbolTable(qint32 pid, Dwfl_Callbacks *callbacks, PerfUnwind *parent) :
m_perfMapFile(perfMapFile(parent->perfMapPath(), pid)),
m_hasPerfMap(m_perfMapFile.exists()),
m_cacheIsDirty(false),
m_unwind(parent),
m_callbacks(callbacks),
m_pid(pid)
{
QObject::connect(&m_elfs, &PerfElfMap::aboutToInvalidate,
&m_elfs, [this](const PerfElfMap::ElfInfo &elf) {
if (m_dwfl && !m_cacheIsDirty && dwfl_addrmodule(m_dwfl, elf.addr)) {
m_cacheIsDirty = true;
}
});
m_dwfl = dwfl_begin(m_callbacks);
#if HAVE_DWFL_GET_DEBUGINFOD_CLIENT
auto client = dwfl_get_debuginfod_client(m_dwfl);
debuginfod_set_user_data(client, this);
debuginfod_set_progressfn(client, [](debuginfod_client* client, long numerator, long denominator) {
auto self = reinterpret_cast(debuginfod_get_user_data(client));
auto url = self->m_unwind->resolveString(QByteArray(debuginfod_get_url(client)));
self->m_unwind->sendDebugInfoDownloadProgress(self->m_currentFindDebugInfoModule, url, numerator, denominator);
// NOTE: eventually we could add a back channel to allow the user to cancel an ongoing download
// to do so, we'd have to return any non-zero value here then
return 0;
});
#endif
dwfl_report_begin(m_dwfl);
// "DWFL can not be used until this function returns 0"
const int reportEnd = dwfl_report_end(m_dwfl, NULL, NULL);
Q_ASSERT(reportEnd == 0);
}
PerfSymbolTable::~PerfSymbolTable()
{
dwfl_end(m_dwfl);
}
static bool findInExtraPath(QFileInfo &path, const QString &fileName, QSet &checkedCanonicalPaths)
{
path.setFile(path.absoluteFilePath() + QDir::separator() + fileName);
if (path.isFile())
return true;
QString canonicalPath = path.canonicalFilePath();
if (checkedCanonicalPaths.contains(canonicalPath))
return false;
checkedCanonicalPaths.insert(canonicalPath);
const QDir absDir = path.absoluteDir();
const auto entries = absDir.entryList({}, QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
path.setFile(absDir, entry);
if (findInExtraPath(path, fileName, checkedCanonicalPaths))
return true;
}
return false;
}
static bool findBuildIdPath(QFileInfo &path, const QString &fileName)
{
path.setFile(path.absoluteFilePath() + QDir::separator() + fileName);
if (path.isFile())
return true;
path.setFile(path.absoluteFilePath() + QDir::separator() + QLatin1String("elf"));
if (path.isFile())
return true;
return false;
}
static QStringList splitPath(const QString &path)
{
return path.split(QDir::listSeparator(), Qt::SkipEmptyParts);
}
static bool matchesBuildId(const QByteArray &buildId, const QFileInfo& path)
{
if (buildId.isEmpty())
return true;
QFile file(path.absoluteFilePath());
file.open(QIODevice::ReadOnly);
if (!file.isOpen())
return false;
auto elf = elf_begin(file.handle(), ELF_C_READ, NULL);
auto guard = qScopeGuard([elf] { elf_end(elf); });
if (!elf)
return false;
const void* pathBuildId = nullptr;
auto len = dwelf_elf_gnu_build_id(elf, &pathBuildId);
if (len != buildId.size())
return false;
return memcmp(buildId.constData(), pathBuildId, len) == 0;
}
QFileInfo PerfSymbolTable::findFile(const QString& path, const QString &fileName,
const QByteArray &buildId) const
{
QFileInfo fullPath;
// first try to find the debug information via build id, if available
if (!buildId.isEmpty()) {
const QString buildIdPath = path + QDir::separator() + QString::fromUtf8(buildId.toHex());
const auto extraPaths = splitPath(m_unwind->debugPath());
for (const QString &extraPath : extraPaths) {
fullPath.setFile(extraPath);
if (findBuildIdPath(fullPath, buildIdPath))
return fullPath;
}
}
// we want to ensure to not check a path twice (overlap of appPath and extraPath,
// recursive symlinks like /usr/bin/X11 as seen in Debian/Ubuntu, ...) so we store
// the canonical visited paths for each library during the lookup
QSet checkedCanonicalPaths;
// reserve an arbitrary small number to remove the first few reallocations and rehashes
checkedCanonicalPaths.reserve(16);
if (!m_unwind->appPath().isEmpty()) {
// try to find the file in the app path
fullPath.setFile(m_unwind->appPath());
if (findInExtraPath(fullPath, fileName, checkedCanonicalPaths) && matchesBuildId(buildId, fullPath)) {
return fullPath;
}
}
// try to find the file in the extra libs path
const auto extraPaths = splitPath(m_unwind->extraLibsPath());
for (const QString &extraPath : extraPaths) {
fullPath.setFile(extraPath);
if (findInExtraPath(fullPath, fileName, checkedCanonicalPaths) && matchesBuildId(buildId, fullPath)) {
return fullPath;
}
}
// last fall-back, try the system root
fullPath.setFile(m_unwind->systemRoot() + path);
return fullPath;
}
static quint64 readBaseAddr(Elf *elf, quint64 addr, quint64 fileOffset)
{
// Find the base address of the binary by reading ELF headers.
// This is based on the approach in https://github.com/google/glog/pull/115
// We are passed the mapped address and file offset of an executable mapping for the ELF file.
const quint64 invalid = PerfElfMap::ElfInfo::INVALID_BASE_ADDR;
size_t phdrnum;
if (elf_getphdrnum(elf, &phdrnum) != 0) {
return invalid;
}
for (size_t i = 0; i != phdrnum; ++i) {
GElf_Phdr phdr;
if (!gelf_getphdr(elf, i, &phdr) || phdr.p_type != PT_LOAD || (phdr.p_flags & (PF_R | PF_X)) != (PF_R | PF_X)) {
continue;
}
// Find the mapped address corresponding to virtual address zero. We do this by first adding (p_offset -
// fileOffset). This gives us the mapped address of the start of the segment, or in other words the mapped
// address corresponding to the virtual address of the segment. (Note that this is distinct from the start
// address, as p_offset is not guaranteed to be page aligned.) We then subtract p_vaddr, which takes us to
// virtual address zero.
return addr + (phdr.p_offset - fileOffset) - phdr.p_vaddr;
}
return invalid;
}
void PerfSymbolTable::registerElf(const PerfRecordMmap &mmap, const QByteArray &buildId)
{
const auto filePath = QString::fromUtf8(mmap.filename());
// special regions, such as [heap], [vdso], [stack], [kernel.kallsyms]_text ... as well as //anon
const bool isSpecialRegion = filePath.isEmpty()
|| (filePath.startsWith(QLatin1Char('[')) && filePath.contains(QLatin1Char(']')))
|| filePath.startsWith(QLatin1String("/dev/")) || filePath.startsWith(QLatin1String("/memfd:"))
|| filePath.startsWith(QLatin1String("/SYSV")) || filePath == QLatin1String("//anon");
const auto fileName = isSpecialRegion ? QString() : QFileInfo(filePath).fileName();
QFileInfo fullPath;
quint64 baseAddr = PerfElfMap::ElfInfo::INVALID_BASE_ADDR;
if (isSpecialRegion) {
// don not set fullPath, these regions don't represent a real file
} else if (mmap.pid() != PerfUnwind::s_kernelPid) {
fullPath = findFile(filePath, fileName, buildId);
if (!fullPath.isFile()) {
m_unwind->sendError(PerfUnwind::MissingElfFile,
PerfUnwind::tr("Could not find ELF file for %1. "
"This can break stack unwinding "
"and lead to missing symbols.").arg(filePath));
} else {
ElfAndFile elf(fullPath);
if (!elf.elf()) {
fullPath = QFileInfo();
} else {
baseAddr = readBaseAddr(elf.elf(), mmap.addr(), mmap.pgoff());
if (!m_firstElf.elf())
m_firstElf = std::move(elf);
}
}
} else { // kernel
fullPath.setFile(m_unwind->systemRoot() + filePath);
ElfAndFile elf(fullPath);
if (!elf.elf())
fullPath = QFileInfo();
}
m_elfs.registerElf(mmap.addr(), mmap.len(), mmap.pgoff(), baseAddr, fullPath,
fileName.toUtf8(), mmap.filename());
// There is no need to clear the symbol or location caches in PerfUnwind. Some locations become
// stale this way, but we still need to keep their IDs, as the receiver might still use them for
// past frames.
if (m_cacheIsDirty)
clearCache();
}
int PerfSymbolTable::insertSubprogram(CuDieRangeMapping *cudie, Dwarf_Die *top, Dwarf_Addr entry,
quint64 offset, quint64 size, quint64 relAddr,
qint32 binaryId, qint32 binaryPathId, qint32 actualPathId,
qint32 inlineCallLocationId, bool isKernel, bool isInline)
{
int line = 0;
dwarf_decl_line(top, &line);
int column = 0;
dwarf_decl_column(top, &column);
const QByteArray file = absoluteSourcePath(dwarf_decl_file(top), cudie->cudie());
qint32 fileId = m_unwind->resolveString(file);
int locationId = m_unwind->resolveLocation(PerfUnwind::Location(entry, relAddr, fileId, m_pid, line,
column, inlineCallLocationId));
qint32 symId = m_unwind->resolveString(cudie->dieName(top));
m_unwind->resolveSymbol(locationId, PerfUnwind::Symbol{symId, offset, size, binaryId, binaryPathId, actualPathId, isKernel, isInline});
return locationId;
}
int PerfSymbolTable::parseDie(CuDieRangeMapping *cudie, Dwarf_Die *top, quint64 offset, quint64 size, quint64 relAddr, qint32 binaryId, qint32 binaryPathId, qint32 actualPathId,
bool isKernel, Dwarf_Files *files, Dwarf_Addr entry, qint32 parentLocationId)
{
int tag = dwarf_tag(top);
switch (tag) {
case DW_TAG_inlined_subroutine: {
PerfUnwind::Location location(entry);
Dwarf_Attribute attr;
Dwarf_Word val = 0;
const QByteArray file = absoluteSourcePath((dwarf_formudata(dwarf_attr(top, DW_AT_call_file, &attr), &val) == 0)
? dwarf_filesrc(files, val, nullptr, nullptr)
: "",
cudie->cudie());
location.file = m_unwind->resolveString(file);
location.line
= (dwarf_formudata(dwarf_attr(top, DW_AT_call_line, &attr), &val) == 0)
? static_cast(val) : -1;
location.column
= (dwarf_formudata(dwarf_attr(top, DW_AT_call_column, &attr), &val) == 0)
? static_cast(val) : -1;
location.pid = m_pid;
location.parentLocationId = parentLocationId;
int callLocationId = m_unwind->resolveLocation(location);
return insertSubprogram(cudie, top, entry, offset, size, relAddr, binaryId, binaryPathId, actualPathId, callLocationId, isKernel, true);
}
case DW_TAG_subprogram:
return insertSubprogram(cudie, top, entry, offset, size, relAddr, binaryId, binaryPathId, actualPathId, -1, isKernel, false);
default:
return -1;
}
}
qint32 PerfSymbolTable::parseDwarf(CuDieRangeMapping *cudie, SubProgramDie *subprogram, const QVector &inlined,
Dwarf_Addr bias, quint64 offset, quint64 size, quint64 relAddr, qint32 binaryId, qint32 binaryPathId, qint32 actualPathId, bool isKernel)
{
Dwarf_Files *files = nullptr;
dwarf_getsrcfiles(cudie->cudie(), &files, nullptr);
qint32 parentLocationId = -1;
auto handleDie = [&](Dwarf_Die scope) {
Dwarf_Addr entry = 0;
if (dwarf_entrypc(&scope, &entry) != 0 || entry == 0)
entry = relAddr;
Dwarf_Addr scopeAddr = bias + entry;
auto locationId = parseDie(cudie, &scope, offset, size, relAddr, binaryId, binaryPathId, actualPathId, isKernel, files, scopeAddr, parentLocationId);
if (locationId != -1)
parentLocationId = locationId;
};
handleDie(*subprogram->die());
std::for_each(inlined.begin(), inlined.end(), handleDie);
return parentLocationId;
}
static void reportError(qint32 pid, const PerfElfMap::ElfInfo& info, const char *message)
{
qWarning() << "failed to report elf for pid =" << pid << ":" << info << ":" << message;
}
Dwfl_Module *PerfSymbolTable::reportElf(const PerfElfMap::ElfInfo& info)
{
if (!info.isValid() || !info.isFile())
return nullptr;
dwfl_report_begin_add(m_dwfl);
Dwfl_Module* ret = dwfl_report_elf(m_dwfl, info.originalFileName.constData(),
info.localFile.absoluteFilePath().toLocal8Bit().constData(), -1,
info.baseAddrOrFallback(), false);
if (!ret) {
reportError(m_pid, info, dwfl_errmsg(dwfl_errno()));
m_cacheIsDirty = true;
} else {
// set symbol table as user data, cf. find_debuginfo callback in perfunwind.cpp
void** userData;
Dwarf_Addr start = 0;
Dwarf_Addr end = 0;
dwfl_module_info(ret, &userData, &start, &end, nullptr, nullptr, nullptr, nullptr);
*userData = this;
m_elfs.updateElf(info.addr, start, end);
}
const int reportEnd = dwfl_report_end(m_dwfl, NULL, NULL);
Q_ASSERT(reportEnd == 0);
return ret;
}
Dwfl_Module *PerfSymbolTable::module(quint64 addr)
{
return module(addr, findElf(addr));
}
Dwfl_Module *PerfSymbolTable::module(quint64 addr, const PerfElfMap::ElfInfo &elf)
{
if (!m_dwfl)
return nullptr;
if (elf.hasBaseAddr() && elf.baseAddr != elf.addr) {
const auto base = m_elfs.findElf(elf.baseAddr);
if (base.addr == elf.baseAddr && !base.pgoff && elf.originalPath == base.originalPath && elf.addr != base.addr)
return module(addr, base);
}
Dwfl_Module *mod = dwfl_addrmodule(m_dwfl, addr);
if (!mod && elf.isValid()) {
// check whether we queried for an address outside the elf range parsed
// by dwfl. If that is the case, then we would invalidate the cache and
// re-report the library again - essentially recreating the current state
// for no gain, except wasting time
mod = dwfl_addrmodule(m_dwfl, elf.baseAddrOrFallback());
}
if (mod)
return mod;
return reportElf(elf);
}
QFileInfo PerfSymbolTable::findDebugInfoFile(
const QString &root, const QString &file,
const QString &debugLinkString)
{
auto dir = QFileInfo(root).dir();
const auto folder = QFileInfo(file).path();
QFileInfo debugLinkFile;
// try in .debug folder
if (!folder.isEmpty()) {
debugLinkFile.setFile(dir.path() + QDir::separator() + folder + QDir::separator() + QLatin1String(".debug")
+ QDir::separator() + debugLinkString);
if (debugLinkFile.isFile())
return debugLinkFile;
}
debugLinkFile.setFile(dir.path() + QDir::separator() + file + QDir::separator() + QLatin1String(".debug")
+ QDir::separator() + debugLinkString);
if (debugLinkFile.isFile())
return debugLinkFile;
// try again in /usr/lib/debug folder
// some distros use for example /usr/lib/debug/lib (ubuntu) and some use /usr/lib/debug/usr/lib (fedora)
const auto usr = QString(QDir::separator() + QLatin1String("usr") + QDir::separator());
auto folderWithoutUsr = folder;
folderWithoutUsr.replace(usr, QDir::separator());
// make sure both (/usr/ and /) are searched
for (const auto& path : {folderWithoutUsr, QString(usr + folderWithoutUsr)}) {
debugLinkFile.setFile(dir.path() + QDir::separator() + QLatin1String("usr") + QDir::separator()
+ QLatin1String("lib") + QDir::separator() + QLatin1String("debug") + QDir::separator()
+ path + QDir::separator() + debugLinkString);
if (debugLinkFile.isFile()) {
return debugLinkFile;
}
}
debugLinkFile.setFile(dir.path() + QDir::separator() + QLatin1String("usr") + QDir::separator()
+ QLatin1String("lib") + QDir::separator() + QLatin1String("debug") + QDir::separator()
+ folder + QDir::separator() + debugLinkString);
if (debugLinkFile.isFile()) {
return debugLinkFile;
}
debugLinkFile.setFile(dir,
QLatin1String("usr") + QDir::separator() + QLatin1String("lib") + QDir::separator()
+ QLatin1String("debug") + QDir::separator() + debugLinkString);
if (debugLinkFile.isFile()) {
return debugLinkFile;
}
// try the default files
if (!folder.isEmpty()) {
debugLinkFile.setFile(dir.path() + QDir::separator() + folder + QDir::separator() + debugLinkString);
if (debugLinkFile.isFile()) {
return debugLinkFile;
}
}
debugLinkFile.setFile(dir.path() + QDir::separator() + file + QDir::separator() + debugLinkString);
return debugLinkFile;
}
int PerfSymbolTable::findDebugInfo(Dwfl_Module *module, const char *moduleName, Dwarf_Addr base,
const char *file, const char *debugLink,
GElf_Word crc, char **debugInfoFilename)
{
m_currentFindDebugInfoModule = m_unwind->resolveString(QByteArray(moduleName));
int ret = dwfl_standard_find_debuginfo(module, nullptr, moduleName, base, file,
debugLink, crc, debugInfoFilename);
if (ret >= 0 || !debugLink || strlen(debugLink) == 0)
return ret;
// fall-back, mostly for situations where we loaded a file via it's build-id.
// search all known paths for the debug link in that case
const auto debugLinkPath = QString::fromUtf8(debugLink);
const auto debugLinkString = QFile(debugLinkPath).fileName();
auto debugLinkFile = findFile(debugLinkPath, debugLinkString);
if (!debugLinkFile.isFile()) {
// fall-back to original file path with debug link file name
const auto &elf = m_elfs.findElf(base);
const auto &path = QString::fromUtf8(elf.originalPath);
debugLinkFile = findDebugInfoFile(m_unwind->systemRoot(), path, debugLinkString);
}
/// FIXME: find a proper solution to this
if (file && !debugLinkFile.isFile() && QByteArray::fromRawData(file, static_cast(strlen(file))).endsWith("/elf")) {
// fall-back to original file if it's in a build-id path
debugLinkFile.setFile(QString::fromUtf8(file));
}
if (!debugLinkFile.isFile())
return ret;
const auto path = eu_compat_strdup(debugLinkFile.absoluteFilePath().toUtf8().constData());
// ugh, nasty - we have to return a fd here :-/
ret = eu_compat_open(path, O_RDONLY | O_BINARY);
if (ret < 0 ) {
qWarning() << "Failed to open debug info file" << path;
eu_compat_free(path);
} else {
*debugInfoFilename = path;
}
return ret;
}
PerfElfMap::ElfInfo PerfSymbolTable::findElf(quint64 ip) const
{
return m_elfs.findElf(ip);
}
int symbolIndex(Elf64_Rel rel)
{
return ELF64_R_SYM(rel.r_info);
}
int symbolIndex(const Elf64_Rela &rel)
{
return ELF64_R_SYM(rel.r_info);
}
int symbolIndex(Elf32_Rel rel)
{
return ELF32_R_SYM(rel.r_info);
}
int symbolIndex(Elf32_Rela rel)
{
return ELF32_R_SYM(rel.r_info);
}
template
int findPltSymbolIndex(Elf_Scn *section, const elf_shdr_t *shdr, Dwarf_Addr addr)
{
if (shdr->sh_entsize != sizeof(elf_relocation_t)) {
qWarning() << "size mismatch:" << shdr->sh_entsize << sizeof(elf_relocation_t);
return -1;
}
const size_t numEntries = shdr->sh_size / shdr->sh_entsize;
const auto *data = elf_getdata(section, nullptr);
const auto *entries = reinterpret_cast(data->d_buf);
const auto *entriesEnd = entries + numEntries;
auto it = std::lower_bound(entries, entriesEnd, addr,
[](const elf_relocation_t &lhs, Dwarf_Addr addr) {
return lhs.r_offset < addr;
});
if (it == entriesEnd || it->r_offset != addr)
return -1;
return symbolIndex(*it);
}
template
Elf64_Addr findPltGotAddr(Elf_Scn *section, elf_shdr_t* shdr)
{
const auto *data = elf_getdata(section, nullptr);
const size_t numEntries = shdr->sh_size / shdr->sh_entsize;
const auto *entries = reinterpret_cast(data->d_buf);
for (size_t i = 0; i < numEntries; ++i) {
if (entries[i].d_tag == DT_PLTGOT) {
return entries[i].d_un.d_ptr;
}
}
return 0;
}
const char *findPltSymbol(Elf *elf, int index)
{
if (!index) // first plt entry is special, skip it
return nullptr;
size_t numSections = 0;
if (elf_getshdrnum(elf, &numSections) != 0)
return nullptr;
Elf64_Addr pltGotAddr = 0;
Elf_Scn *symtab = nullptr;
for (size_t i = 0; (!pltGotAddr || !symtab) && i < numSections; ++i) {
auto *section = elf_getscn(elf, i);
if (const auto *shdr = elf64_getshdr(section)) {
if (shdr->sh_type == SHT_DYNAMIC)
pltGotAddr = findPltGotAddr(section, shdr);
else if (shdr->sh_type == SHT_DYNSYM)
symtab = section;
} else if (const auto *shdr = elf32_getshdr(section)) {
if (shdr->sh_type == SHT_DYNAMIC)
pltGotAddr = findPltGotAddr(section, shdr);
else if (shdr->sh_type == SHT_DYNSYM)
symtab = section;
}
}
if (!pltGotAddr || !symtab)
return nullptr;
Elf64_Addr indexAddr = 0;
for (size_t i = 0; !indexAddr && i < numSections; ++i) {
auto *section = elf_getscn(elf, i);
if (const auto *shdr = elf64_getshdr(section)) {
if (shdr->sh_addr <= pltGotAddr && pltGotAddr < shdr->sh_addr + shdr->sh_size)
indexAddr = shdr->sh_addr + (index + 2) * sizeof(Elf64_Addr);
} else if (const auto *shdr = elf32_getshdr(section)) {
if (shdr->sh_addr <= pltGotAddr && pltGotAddr < shdr->sh_addr + shdr->sh_size)
indexAddr = shdr->sh_addr + (index + 2) * sizeof(Elf32_Addr);
}
}
if (!indexAddr)
return nullptr;
int symbolIndex = -1;
for (size_t i = 0; symbolIndex == -1 && i < numSections; ++i) {
auto section = elf_getscn(elf, i);
if (const auto *shdr = elf64_getshdr(section)) {
if (shdr->sh_type == SHT_REL)
symbolIndex = findPltSymbolIndex(section, shdr, indexAddr);
else if (shdr->sh_type == SHT_RELA)
symbolIndex = findPltSymbolIndex(section, shdr, indexAddr);
} else if (const auto *shdr = elf32_getshdr(section)) {
if (shdr->sh_type == SHT_REL)
symbolIndex = findPltSymbolIndex(section, shdr, indexAddr);
else if (shdr->sh_type == SHT_RELA)
symbolIndex = findPltSymbolIndex(section, shdr, indexAddr);
}
}
if (symbolIndex == -1)
return nullptr;
const auto *symtabData = elf_getdata(symtab, nullptr)->d_buf;
if (const auto *shdr = elf64_getshdr(symtab)) {
const auto *symbols = reinterpret_cast(symtabData);
if (symbolIndex >= 0 && uint(symbolIndex) < (shdr->sh_size / shdr->sh_entsize))
return elf_strptr(elf, shdr->sh_link, symbols[symbolIndex].st_name);
} else if (const auto *shdr = elf32_getshdr(symtab)) {
const auto *symbols = reinterpret_cast(symtabData);
if (symbolIndex >= 0 && uint(symbolIndex) < (shdr->sh_size / shdr->sh_entsize))
return elf_strptr(elf, shdr->sh_link, symbols[symbolIndex].st_name);
}
return nullptr;
}
static QByteArray fakeSymbolFromSection(Dwfl_Module *mod, Dwarf_Addr addr)
{
Dwarf_Addr bias = 0;
auto elf = dwfl_module_getelf(mod, &bias);
const auto moduleAddr = addr - bias;
auto section = dwfl_module_address_section(mod, &addr, &bias);
if (!elf || !section)
return {};
size_t textSectionIndex = 0;
if (elf_getshdrstrndx(elf, &textSectionIndex) != 0)
return {};
size_t nameOffset = 0;
size_t entsize = 0;
if (const auto *shdr = elf64_getshdr(section)) {
nameOffset = shdr->sh_name;
entsize = shdr->sh_entsize;
} else if (const auto *shdr = elf32_getshdr(section)) {
nameOffset = shdr->sh_name;
entsize = shdr->sh_entsize;
}
auto str = elf_strptr(elf, textSectionIndex, nameOffset);
if (!str || str == QByteArrayLiteral(".text"))
return {};
if (str == QByteArrayLiteral(".plt") && entsize > 0) {
const auto* pltSymbol = findPltSymbol(elf, static_cast(addr / entsize));
if (pltSymbol)
return demangle(pltSymbol) + "@plt";
}
// mark other entries by section name, see also:
// http://www.mail-archive.com/elfutils-devel@sourceware.org/msg00019.html
QByteArray sym = str;
sym.prepend('<');
sym.append('+');
sym.append(QByteArray::number(quint64(moduleAddr), 16));
sym.append('>');
return sym;
}
int PerfSymbolTable::lookupFrame(Dwarf_Addr ip, bool isKernel,
bool *isInterworking)
{
auto addressCache = m_unwind->addressCache();
const auto& elf = findElf(ip);
auto cached = addressCache->find(elf, ip, &m_invalidAddressCache);
if (cached.isValid()) {
*isInterworking = cached.isInterworking;
return cached.locationId;
}
qint32 binaryId = -1;
qint32 binaryPathId = -1;
qint32 actualPathId = -1;
quint64 elfStart = 0;
if (elf.isValid()) {
binaryId = m_unwind->resolveString(elf.originalFileName);
binaryPathId = m_unwind->resolveString(elf.originalPath);
actualPathId = m_unwind->resolveString(elf.localFile.absoluteFilePath().toUtf8());
elfStart = elf.baseAddrOrFallback();
}
Dwfl_Module *mod = module(ip, elf);
const auto arch = m_unwind->architecture();
const bool isArmArch = (arch == PerfRegisterInfo::ARCH_ARM);
PerfUnwind::Location addressLocation(PerfAddressCache::symbolAddress(ip, isArmArch), 0, -1, m_pid);
PerfUnwind::Location functionLocation(addressLocation);
QByteArray symname;
GElf_Off off = 0;
quint64 start = 0;
quint64 size = 0;
quint64 relAddr = 0;
if (mod) {
if (!addressCache->hasSymbolCache(elf.originalPath)) {
// cache all symbols in a sorted lookup table and demangle them on-demand
// note that the symbols within the symtab aren't necessarily sorted,
// which makes searching repeatedly via dwfl_module_addrinfo potentially very slow
addressCache->setSymbolCache(elf.originalPath, PerfAddressCache::extractSymbols(mod, elfStart, arch));
}
auto cachedAddrInfo = addressCache->findSymbol(elf.originalPath, addressLocation.address - elfStart);
if (cachedAddrInfo.isValid()) {
off = addressLocation.address - elfStart - cachedAddrInfo.value;
symname = cachedAddrInfo.symname;
start = cachedAddrInfo.value;
size = cachedAddrInfo.size;
relAddr = PerfAddressCache::alignedAddress(start + off, isArmArch);
Dwarf_Addr bias = 0;
functionLocation.address -= off; // in case we don't find anything better
if (!m_cuDieRanges.contains(mod))
m_cuDieRanges[mod] = PerfDwarfDieCache(mod);
auto *cudie = m_cuDieRanges[mod].findCuDie(addressLocation.address);
if (cudie) {
bias = cudie->bias();
const auto offset = addressLocation.address - bias;
if (auto srcloc = findSourceLocation(cudie->cudie(), offset)) {
addressLocation.file = m_unwind->resolveString(srcloc.file);
addressLocation.line = srcloc.line;
addressLocation.column = srcloc.column;
}
auto *subprogram = cudie->findSubprogramDie(offset);
if (subprogram) {
const auto scopes = findInlineScopes(subprogram->die(), offset);
// setup function location, i.e. entry point of the (inlined) frame
[&](Dwarf_Die die) {
Dwarf_Addr entry = 0;
dwarf_entrypc(&die, &entry);
symname = cudie->dieName(&die); // use name of inlined function as symbol
functionLocation.address = entry + bias;
functionLocation.file =
m_unwind->resolveString(absoluteSourcePath(dwarf_decl_file(&die), cudie->cudie()));
dwarf_decl_line(&die, &functionLocation.line);
dwarf_decl_column(&die, &functionLocation.column);
}(scopes.isEmpty() ? *subprogram->die() : scopes.last());
// check if the inline chain was cached already
addressLocation.parentLocationId = m_unwind->lookupLocation(functionLocation);
// otherwise resolve the inline chain if possible
if (!scopes.isEmpty() && !m_unwind->hasSymbol(addressLocation.parentLocationId)) {
addressLocation.parentLocationId = parseDwarf(cudie, subprogram, scopes, bias, start, size, relAddr,
binaryId, binaryPathId, actualPathId, isKernel);
}
}
}
// resolve and cache the inline chain
if (addressLocation.parentLocationId == -1)
addressLocation.parentLocationId = m_unwind->resolveLocation(functionLocation);
} else {
// no symbol found
symname = fakeSymbolFromSection(mod, addressLocation.address);
addressLocation.parentLocationId = m_unwind->resolveLocation(functionLocation);
}
if (!m_unwind->hasSymbol(addressLocation.parentLocationId)) {
// no sufficient debug information. Use what we already know
qint32 symId = m_unwind->resolveString(symname);
m_unwind->resolveSymbol(addressLocation.parentLocationId,
PerfUnwind::Symbol(symId, start, size, binaryId, binaryPathId, actualPathId, isKernel));
}
} else {
if (isKernel) {
const auto entry = m_unwind->findKallsymEntry(addressLocation.address);
off = addressLocation.address - entry.address;
symname = entry.symbol;
if (!entry.module.isEmpty())
binaryId = m_unwind->resolveString(entry.module);
} else {
symname = symbolFromPerfMap(addressLocation.address, &off);
}
if (off)
functionLocation.address -= off;
else
functionLocation.address = elfStart;
addressLocation.parentLocationId = m_unwind->resolveLocation(functionLocation);
if (!m_unwind->hasSymbol(addressLocation.parentLocationId)) {
qint32 symId = m_unwind->resolveString(symname);
m_unwind->resolveSymbol(addressLocation.parentLocationId,
PerfUnwind::Symbol(symId, start, size, binaryId, binaryPathId, actualPathId, isKernel));
}
}
// relAddr - relative address of the function start added with offset from the function start
addressLocation.relAddr = relAddr;
Q_ASSERT(addressLocation.parentLocationId != -1);
Q_ASSERT(m_unwind->hasSymbol(addressLocation.parentLocationId));
int locationId = m_unwind->resolveLocation(addressLocation);
*isInterworking = (symname == "$a" || symname == "$t");
addressCache->cache(elf, ip, {locationId, *isInterworking}, &m_invalidAddressCache);
return locationId;
}
static bool operator<(const PerfSymbolTable::PerfMapSymbol &a,
const PerfSymbolTable::PerfMapSymbol &b)
{
return a.start < b.start;
}
QByteArray PerfSymbolTable::symbolFromPerfMap(quint64 ip, GElf_Off *offset) const
{
QVector::ConstIterator sym
= std::upper_bound(m_perfMap.begin(), m_perfMap.end(), PerfMapSymbol(ip));
if (sym != m_perfMap.begin()) {
--sym;
if (sym->start <= ip && sym->start + sym->length > ip) {
*offset = ip - sym->start;
return sym->name;
}
}
*offset = 0;
return QByteArray();
}
void PerfSymbolTable::updatePerfMap()
{
if (!m_hasPerfMap)
return;
if (!m_perfMapFile.isOpen())
m_perfMapFile.open(QIODevice::ReadOnly);
bool readLine = false;
while (!m_perfMapFile.atEnd()) {
QByteArrayList line = m_perfMapFile.readLine().split(' ');
if (line.length() >= 3) {
bool ok = false;
quint64 start = line.takeFirst().toULongLong(&ok, 16);
if (!ok)
continue;
quint64 length = line.takeFirst().toULongLong(&ok, 16);
if (!ok)
continue;
QByteArray name = line.join(' ').trimmed();
m_perfMap.append(PerfMapSymbol(start, length, name));
readLine = true;
}
}
if (readLine)
std::sort(m_perfMap.begin(), m_perfMap.end());
}
bool PerfSymbolTable::containsAddress(quint64 address) const
{
return m_elfs.isAddressInRange(address);
}
Dwfl *PerfSymbolTable::attachDwfl(const Dwfl_Thread_Callbacks *callbacks, PerfUnwind::UnwindInfo *unwindInfo)
{
if (static_cast(m_pid) == dwfl_pid(m_dwfl))
return m_dwfl; // Already attached, nothing to do
// only attach state when we have the required information for stack unwinding
// for normal symbol resolution and inline frame resolution this is not needed
// most notably, this isn't needed for frame pointer callchains
const auto sampleType = unwindInfo->sample->type();
const auto hasSampleRegsUser = (sampleType & PerfEventAttributes::SAMPLE_REGS_USER);
const auto hasSampleStackUser = (sampleType & PerfEventAttributes::SAMPLE_STACK_USER);
if (!hasSampleRegsUser || !hasSampleStackUser)
return nullptr;
if (!dwfl_attach_state(m_dwfl, m_firstElf.elf(), m_pid, callbacks, unwindInfo)) {
qWarning() << m_pid << "failed to attach state" << dwfl_errmsg(dwfl_errno());
return nullptr;
}
return m_dwfl;
}
void PerfSymbolTable::clearCache()
{
m_invalidAddressCache.clear();
m_cuDieRanges.clear();
m_perfMap.clear();
if (m_perfMapFile.isOpen())
m_perfMapFile.reset();
// Throw out the dwfl state
dwfl_report_begin(m_dwfl);
const int reportEnd = dwfl_report_end(m_dwfl, NULL, NULL);
Q_ASSERT(reportEnd == 0);
m_cacheIsDirty = false;
}
PerfSymbolTable::ElfAndFile &PerfSymbolTable::ElfAndFile::operator=(
PerfSymbolTable::ElfAndFile &&other)
{
if (&other != this) {
clear();
m_elf = other.m_elf;
m_file = other.m_file;
m_fullPath = std::move(other.m_fullPath);
other.m_elf = nullptr;
other.m_file = -1;
}
return *this;
}
PerfSymbolTable::ElfAndFile::~ElfAndFile()
{
clear();
}
void PerfSymbolTable::ElfAndFile::clear()
{
if (m_elf)
elf_end(m_elf);
if (m_file != -1)
eu_compat_close(m_file);
}
PerfSymbolTable::ElfAndFile::ElfAndFile(const QFileInfo &fullPath)
: m_fullPath(fullPath)
{
m_file = eu_compat_open(fullPath.absoluteFilePath().toLocal8Bit().constData(),
O_RDONLY | O_BINARY);
if (m_file == -1)
return;
m_elf = elf_begin(m_file, ELF_C_READ, nullptr);
if (m_elf && elf_kind(m_elf) == ELF_K_NONE) {
elf_end(m_elf);
m_elf = nullptr;
}
}
PerfSymbolTable::ElfAndFile::ElfAndFile(PerfSymbolTable::ElfAndFile &&other)
: m_elf(other.m_elf), m_file(other.m_file), m_fullPath(std::move(other.m_fullPath))
{
other.m_elf = nullptr;
other.m_file = -1;
}
void PerfSymbolTable::initAfterFork(const PerfSymbolTable* parent)
{
m_elfs.copyDataFrom(&parent->m_elfs);
m_firstElf = ElfAndFile(parent->m_firstElf.fullPath());
}
perfparser-65472541f74da213583535c8bb4fea831e875109/app/perfsymboltable.h 0000664 0000000 0000000 00000012547 15057302234 0024452 0 ustar 00root root 0000000 0000000 /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "perfaddresscache.h"
#include "perfdata.h"
#include "perfelfmap.h"
#include "perfunwind.h"
#include
#include
class PerfDwarfDieCache;
class SubProgramDie;
class CuDieRangeMapping;
class PerfSymbolTable
{
public:
PerfSymbolTable(qint32 pid, Dwfl_Callbacks *callbacks, PerfUnwind *parent);
~PerfSymbolTable();
static QFileInfo findDebugInfoFile(
const QString& root, const QString& file, const QString& debugLinkString);
struct PerfMapSymbol {
PerfMapSymbol(quint64 start = 0, quint64 length = 0, const QByteArray &name = QByteArray()) :
start(start), length(length), name(name) {}
quint64 start;
quint64 length;
QByteArray name;
};
// Announce an mmap. Invalidate the symbol and address cache and clear the dwfl if it overlaps
// with an existing one.
void registerElf(const PerfRecordMmap &mmap, const QByteArray &buildId);
PerfElfMap::ElfInfo findElf(quint64 ip) const;
// Find the module for the given address and report it if needed
Dwfl_Module *module(quint64 addr);
Dwfl_Module *module(quint64 addr, const PerfElfMap::ElfInfo &elf);
int findDebugInfo(Dwfl_Module *module, const char *moduleName, Dwarf_Addr base,
const char *file, const char *debugLink,
GElf_Word crc, char **debugInfoFilename);
// Look up a frame and all its inline parents and append them to the given vector.
// If the frame hits an elf that hasn't been reported, yet, report it.
int lookupFrame(Dwarf_Addr ip, bool isKernel, bool *isInterworking);
void updatePerfMap();
bool containsAddress(quint64 address) const;
Dwfl *attachDwfl(const Dwfl_Thread_Callbacks *callbacks, PerfUnwind::UnwindInfo *unwindInfo);
void clearCache();
bool cacheIsDirty() const { return m_cacheIsDirty; }
void initAfterFork(const PerfSymbolTable *parent);
private:
// Report an mmap to dwfl and parse it for symbols and inlines, or simply return it if dwfl has
// it already
Dwfl_Module *reportElf(const PerfElfMap::ElfInfo& elf);
QFileInfo findFile(const QString& path, const QString& fileName, const QByteArray& buildId = QByteArray()) const;
class ElfAndFile {
public:
ElfAndFile() {}
explicit ElfAndFile(const QFileInfo &fullPath);
ElfAndFile(ElfAndFile &&other);
ElfAndFile &operator=(ElfAndFile &&other);
ElfAndFile(const ElfAndFile &other) = delete;
ElfAndFile &operator=(const ElfAndFile &other) = delete;
~ElfAndFile();
Elf *elf() const { return m_elf; }
QFileInfo fullPath() const { return m_fullPath; }
private:
void clear();
Elf *m_elf = nullptr;
int m_file = -1;
QFileInfo m_fullPath;
};
QFile m_perfMapFile;
QVector m_perfMap;
bool m_hasPerfMap;
bool m_cacheIsDirty;
PerfUnwind *m_unwind;
Dwfl *m_dwfl;
// elf used to detect architecture
ElfAndFile m_firstElf;
PerfElfMap m_elfs;
PerfAddressCache::OffsetAddressCache m_invalidAddressCache;
QHash m_cuDieRanges;
Dwfl_Callbacks *m_callbacks;
qint32 m_pid;
qint32 m_currentFindDebugInfoModule = -1;
QByteArray symbolFromPerfMap(quint64 ip, GElf_Off *offset) const;
int parseDie(CuDieRangeMapping *cudie, Dwarf_Die *top, quint64 offset, quint64 size, quint64 relAddr, qint32 binaryId, qint32 binaryPathId, qint32 actualPathId, bool isKernel,
Dwarf_Files *files, Dwarf_Addr entry, qint32 parentLocationId);
int insertSubprogram(CuDieRangeMapping *cudie, Dwarf_Die *top, Dwarf_Addr entry, quint64 offset, quint64 size, quint64 relAddr, qint32 binaryId, qint32 binaryPathId, qint32 actualPathId,
qint32 inlineParent, bool isKernel, bool isInline);
qint32 parseDwarf(CuDieRangeMapping *cudie, SubProgramDie *subprogram, const QVector