Add markdown formatter (#1071)

This commit is contained in:
Kerem Kat
2024-12-07 01:37:33 +01:00
committed by GitHub
parent 9c37bb0f62
commit 5fe149a639
17 changed files with 322 additions and 274 deletions

View File

@@ -1,13 +1,21 @@
name: Linter Checks
name: lint
on:
- push
- pull_request
jobs:
check-license-headers:
license-header:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check license headers
uses: apache/skywalking-eyes/header@v0.6.0
markdown:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install prettier
run: |
npm install -g prettier@3.4.2
make check-md

View File

@@ -115,7 +115,13 @@ ifneq (,$(findstring $(ARCH_TAG),x86 x64 arm64))
endif
.PHONY: all jar release build-test test native clean coverage clean-coverage build-test-java build-test-cpp test-cpp test-java
.PHONY: all jar release build-test test native clean coverage clean-coverage build-test-java build-test-cpp test-cpp test-java format-md check-md
check-md:
prettier -c README.md "docs/**/*.md"
format-md:
prettier -w README.md "docs/**/*.md"
all: build/bin build/lib build/$(LIB_PROFILER) build/$(ASPROF) jar build/$(JFRCONV)

View File

@@ -41,7 +41,7 @@ click the desired build and scroll down to the artifacts section. These binaries
# Supported platforms
| | Officially maintained builds | Other available ports |
|-----------|------------------------------|-------------------------------------------|
| --------- | ---------------------------- | ----------------------------------------- |
| **Linux** | x64, arm64 | x86, arm32, ppc64le, riscv64, loongarch64 |
| **macOS** | x64, arm64 | |
@@ -49,9 +49,11 @@ click the desired build and scroll down to the artifacts section. These binaries
In a typical use case, profiling a Java application is just a matter of a running `asprof` with a PID of a
running Java process.
```
$ asprof -d 30 -f /tmp/flamegraph.html <PID>
```
The above command translates to: run profiler for 30 seconds and save results to `/tmp/flamegraph.html`
as an interactive `Flame Graph` that can be viewed in a browser.
@@ -65,25 +67,25 @@ as an interactive `Flame Graph` that can be viewed in a browser.
## Basic usage
* [Getting Started](docs/GettingStarted.md)
* [Profiler Options](docs/ProfilerOptions.md)
* [Profiling Modes](docs/ProfilingModes.md)
* [Integrating async-profiler](docs/IntegratingAsyncProfiler.md)
* [Profiling In Container](docs/ProfilingInContainer.md)
- [Getting Started](docs/GettingStarted.md)
- [Profiler Options](docs/ProfilerOptions.md)
- [Profiling Modes](docs/ProfilingModes.md)
- [Integrating async-profiler](docs/IntegratingAsyncProfiler.md)
- [Profiling In Container](docs/ProfilingInContainer.md)
## Profiler output
* [Output Formats](docs/OutputFormats.md)
* [FlameGraph Interpretation](docs/FlamegraphInterpretation.md)
* [JFR Visualization](docs/JfrVisualization.md)
* [Converter Usage](docs/ConverterUsage.md)
- [Output Formats](docs/OutputFormats.md)
- [FlameGraph Interpretation](docs/FlamegraphInterpretation.md)
- [JFR Visualization](docs/JfrVisualization.md)
- [Converter Usage](docs/ConverterUsage.md)
## Advanced usage
* [CPU Sampling Engines](docs/CpuSamplingEngines.md)
* [Stack Walking Modes](docs/StackWalkingModes.md)
* [Advanced Stacktrace Features](docs/AdvancedStacktraceFeatures.md)
* [Profiling Non-Java Applications](docs/ProfilingNonJavaApplications.md)
- [CPU Sampling Engines](docs/CpuSamplingEngines.md)
- [Stack Walking Modes](docs/StackWalkingModes.md)
- [Advanced Stacktrace Features](docs/AdvancedStacktraceFeatures.md)
- [Profiling Non-Java Applications](docs/ProfilingNonJavaApplications.md)
## Troubleshooting

View File

@@ -32,4 +32,4 @@ a synthetic frame with the address at the top of every stack trace.
![](https://github.com/async-profiler/async-profiler/blob/master/.assets/images/pcaddr_feature.png)
The feature can be enabled with the option `-F pcaddr` (or its agent equivalent `features=pcaddr`).
The feature can be enabled with the option `-F pcaddr` (or its agent equivalent `features=pcaddr`).

View File

@@ -6,9 +6,9 @@ standalone converter binary is also available [here](ttps://github.com/async-pro
## Supported conversions
* collapsed -> html, collapsed
* html -> html, collapsed
* jfr -> html, collapsed, pprof, pb.gz
- collapsed -> html, collapsed
- html -> html, collapsed
- jfr -> html, collapsed, pprof, pb.gz
## Usage
@@ -19,24 +19,24 @@ The output format specified can be only one at a time for conversion from one fo
### Available arguments
```
Conversion options:
Conversion options:
-o --output FORMAT, -o can be omitted if the output file extension unambiguously determines the format, e.g. profile.collapsed
FORMAT can be any of the following:
# collapsed: This is a collection of call stacks, where each line is a semicolon separated
list of frames followed by a counter. This is used by the FlameGraph script to
# collapsed: This is a collection of call stacks, where each line is a semicolon separated
list of frames followed by a counter. This is used by the FlameGraph script to
generate the FlameGraph visualization of the profile data.
# flamegraph: Flamegraph is a hierarchical representation of call traces of the profiled
# flamegraph: Flamegraph is a hierarchical representation of call traces of the profiled
software in a color coded format that helps to identify a particular resource
usage like CPU and memory for the application.
# pprof: pprof is a profiling visualization and analysis tool from Google. More details on
# pprof: pprof is a profiling visualization and analysis tool from Google. More details on
pprof on the official github page https://github.com/google/pprof.
# pb.gz: This is a compressed version of pprof output.
JFR options:
--cpu Generate only CPU profile during conversion
--wall Generate only Wall clock profile during conversion
@@ -44,15 +44,15 @@ JFR options:
--live Build allocation profile from live objects only during conversion
--lock Generate only Lock contention profile during conversion
-t --threads Split stack traces by threads
-s --state LIST Filter thread states: runnable, sleeping, default. State name is case insensitive
-s --state LIST Filter thread states: runnable, sleeping, default. State name is case insensitive
and can be abbreviated, e.g. -s r
--classify Classify samples into predefined categories
--total Accumulate total value (time, bytes, etc.) instead of samples
--lines Show line numbers
--bci Show bytecode indices
--simple Simple class names instead of fully qualified names
--norm Normalize names of hidden classes/lambdas, e.g. Original JFR transforms
lambda names to something like pkg.ClassName$$Lambda+0x00007f8177090218/543846639
--norm Normalize names of hidden classes/lambdas, e.g. Original JFR transforms
lambda names to something like pkg.ClassName$$Lambda+0x00007f8177090218/543846639
which gets normalized to pkg.ClassName$$Lambda
--dot Dotted class names, e.g. java.lang.String instead of java/lang/String
--from TIME Start time in ms (absolute or relative)
@@ -79,36 +79,42 @@ Flame Graph options:
This section explains how the binary `jfrconv` can be used which exists in the same bin folder as
`asprof`binary.
The below command will generate a foo.html. If no output file is specified, it defaults to a
Flame Graph output.
The below command will generate a foo.html. If no output file is specified, it defaults to a
Flame Graph output.
```
jfrconv foo.jfr
```
Profiling in JFR mode allows multi-mode profiling. So the command above will generate a Flame Graph
output, however, for a multi-mode profile output with both `cpu` and `wall-clock` events, the
Flame Graph will have an aggregation of both in the view. Such a view wouldn't make much sense and
hence it is advisable to use JFR conversion filter options like `--cpu` to filter out events
Profiling in JFR mode allows multi-mode profiling. So the command above will generate a Flame Graph
output, however, for a multi-mode profile output with both `cpu` and `wall-clock` events, the
Flame Graph will have an aggregation of both in the view. Such a view wouldn't make much sense and
hence it is advisable to use JFR conversion filter options like `--cpu` to filter out events
during a conversion.
```
jfrconv --cpu foo.jfr -o foo.html
```
or
```
jfrconv --cpu foo.jfr
```
for HTML output as HTML is the default format for conversion from JFR.
In case the conversion output is a Flame Graph, it can be further formatted with the use of flags
specified above under `Flame Graph options`. The below command(s) will add a title string named `Title`
to the Flame Graph instead of the default `Flame Graph` title and also will reverse the graph view
In case the conversion output is a Flame Graph, it can be further formatted with the use of flags
specified above under `Flame Graph options`. The below command(s) will add a title string named `Title`
to the Flame Graph instead of the default `Flame Graph` title and also will reverse the graph view
by reversing the stack traces.
```
jfrconv --cpu foo.jfr foo.html -r --title Title
```
or
```
jfrconv --cpu foo.jfr --reverse --title Title
```

View File

@@ -4,18 +4,18 @@ Async-profiler has three options for CPU profiling: `-e cpu`, `-e itimer` and `-
## cpu & itimer mode
Both cpu and itimer mode measure the CPU time spent by the running threads. For example,
if an application uses 2 cpu cores, each with 30% utilization, and the sampling interval is
10ms, then the profiler will collect about 2 * 0.3 * 100 = 60 samples per second.
Both cpu and itimer mode measure the CPU time spent by the running threads. For example,
if an application uses 2 cpu cores, each with 30% utilization, and the sampling interval is
10ms, then the profiler will collect about `2 * 0.3 * 100 = 60` samples per second.
In other words, 1 profiling sample means that one CPU was actively running for N nanoseconds,
In other words, 1 profiling sample means that one CPU was actively running for N nanoseconds,
where N is the profiling interval.
- `itimer` mode is based on [setitimer(ITIMER_PROF)](https://man7.org/linux/man-pages/man2/setitimer.2.html)
syscall, which ideally generates a signal every given interval of the CPU time consumed by the process.
- `cpu` mode relies on [perf_events](https://man7.org/linux/man-pages/man2/perf_event_open.2.html).
The idea is the same - to generate a signal every `N` nanoseconds of CPU time, which in this case
is achieved by configuring PMU to generate an interrupt every `K` CPU cycles. `cpu` mode has few additional features:
syscall, which ideally generates a signal every given interval of the CPU time consumed by the process.
- `cpu` mode relies on [perf_events](https://man7.org/linux/man-pages/man2/perf_event_open.2.html).
The idea is the same - to generate a signal every `N` nanoseconds of CPU time, which in this case
is achieved by configuring PMU to generate an interrupt every `K` CPU cycles. `cpu` mode has few additional features:
- `perf_events` availability is now automatically checked by trying to create a dummy perf_event.
- If kernel-space profiling using `perf_events` is not available (including when restricted by `perf_event_paranoid`
setting or by `seccomp`), async-profiler transparently falls back to `ctimer` mode.
@@ -25,8 +25,7 @@ is achieved by configuring PMU to generate an interrupt every `K` CPU cycles. `c
- `allkernel` option has been removed.
- JFR recording now contains engine setting with the current profiling engine: `perf_events`, `ctimer`, `wall` etc.
Ideally, both `itimer` and `cpu` should collect the same number of samples. Typically, the
Ideally, both `itimer` and `cpu` should collect the same number of samples. Typically, the
profiles indeed look very similar. However, in [some cases](https://github.com/golang/go/issues/14434)
cpu profile appears a bit more accurate though, since the signal is delivered exactly to the thread
that overflowed a hardware counter.
@@ -45,12 +44,12 @@ problematic for an application with many threads running under a low
- signals are not distributed evenly between running threads.
- sampling resolution is limited by the size of [jiffies](https://man7.org/linux/man-pages/man7/time.7.html).
`ctimer` aims to address these limitations of `perf_events` and `itimer`. `ctimer` relies on
[timer_create](https://man7.org/linux/man-pages/man2/timer_create.2.html). It combines benefits of
`-e cpu` and `-e itimer`, except that it does not allow collecting kernel stacks. `timer_create` is used
in [Go profiler](https://felixge.de/2022/02/11/profiling-improvements-in-go-1.18/). Below are some of
the benefits of `ctimer`:
- Works in containers by default.
- Does not suffer from `itimer` biases.
- Does not consume file descriptors.
- Does not consume file descriptors.

View File

@@ -4,7 +4,9 @@ To interpret a flame graph, the best way forward is to understand how they are c
profiling results are a set of stack traces.
## Example application to profile
Let's take the below example:
```
main() {
// some business logic
@@ -21,7 +23,7 @@ main() {
// some business logic
func5();
}
// some business logic
func2() {
// some business logic
@@ -33,23 +35,27 @@ main() {
```
## Profiler sampling
Profiling starts by taking samples x times per second. Whenever a sample is taken, the current call stack for it is saved. The diagram below shows the unsorted sampling view before the sorting and aggregation takes place.
![](https://github.com/async-profiler/async-profiler/blob/master/.assets/images/ProfilerSamplings.png)
Below are the sampling numbers:
* `func3()->func7()`: 3 samples
* `func4()`: 1 sample
* `func1()->func5()`: 2 samples
* `func2()->func8()`: 4 samples
* `func2()->func6()`: 1 sample
- `func3()->func7()`: 3 samples
- `func4()`: 1 sample
- `func1()->func5()`: 2 samples
- `func2()->func8()`: 4 samples
- `func2()->func6()`: 1 sample
## Sorting samples
Samples are then alphabetically sorted at the base level just after root(or main method) of the application.
![](https://github.com/async-profiler/async-profiler/blob/master/.assets/images/SortedSamplings.png)
## Aggregated view
For the aggregated view, the blocks for the same functions at each
level of stack depth are stitched together to get the aggregated
view of the flame graph.
@@ -67,6 +73,7 @@ heap utilization and wall-clock profiling to view latency.
[More on various modes of profiling](https://github.com/async-profiler/async-profiler/?tab=readme-ov-file#profiling-modes)
## Understanding FlameGraph colors
The various colours in a FlameGraph output with their relation to underlying code for a Java application:
![](https://github.com/async-profiler/async-profiler/blob/master/.assets/images/flamegraph_colors.png)

View File

@@ -1,6 +1,7 @@
# Getting started guide
## Before we start profiling
As of Linux 4.6, capturing kernel call stacks using `perf_events` from a non-root
process requires setting two runtime variables. You can set them using
sysctl or as follows:
@@ -11,12 +12,14 @@ sysctl or as follows:
```
## Find process to profile
Common ways to find the target process include using `jps` and `pgrep`. `pgrep` can be used
along with necessary flags for example `-l` and search for `java` to find all running java
processes and find the target process name and id from the list `pgrep ssh -l`. The next
processes and find the target process name and id from the list `pgrep ssh -l`. The next
section includes an example using `jps`.
## Start profiling
async-profiler works in the context of the target Java application,
i.e. it runs as an agent in the process being profiled.
`asprof` is a tool to attach and control the agent.
@@ -78,9 +81,9 @@ call stack leading to it comes from `Primes.primesThread`.
## Other use cases
* [Launching as an agent](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#launching-as-an-agent)
* [Java API](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#using-java-api)
* [IntelliJ IDEA](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#intellij-idea)
- [Launching as an agent](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#launching-as-an-agent)
- [Java API](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#using-java-api)
- [IntelliJ IDEA](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#intellij-idea)
## FlameGraph visualization
@@ -99,6 +102,6 @@ $ asprof -d 30 -f /tmp/flamegraph.html 8983
The flame graph html can be opened in any browser of your choice for further interpretation.
Please refer to
Please refer to
[Interpreting a Flame Graph](https://github.com/async-profiler/async-profiler/blob/master/docs/FlamegraphInterpretation.md)
to understand more on how to interpret a Flame Graph.

View File

@@ -17,9 +17,10 @@ The format of the arguments string is described
Another important use of attaching async-profiler as an agent is for continuous profiling.
## Using Java API
async-profiler Java API is published to maven central. Like any other dependency, we have to
just include the
[dependency](https://mvnrepository.com/artifact/tools.profiler/async-profiler/latest)
just include the
[dependency](https://mvnrepository.com/artifact/tools.profiler/async-profiler/latest)
from maven.
### Example usage with the API
@@ -28,18 +29,18 @@ from maven.
AsyncProfiler profiler = AsyncProfiler.getInstance();
```
The above gives us an instance of `AsyncProfiler` object which can be further used to start
The above gives us an instance of `AsyncProfiler` object which can be further used to start
actual profiling.
```
profiler.execute("start,jfr,event=cpu,file=/path/to/%p.jfr");
profiler.execute("start,jfr,event=cpu,file=/path/to/%p.jfr");
// do some meaningful work
profiler.execute("stop");
```
`%p` equates to the PID of the process. There are other options as well for filename which
can be found in [Profiler Options](https://github.com/async-profiler/async-profiler/blob/master/docs/ProfilerOptions.md).
`file` should be specified only once, either in
`file` should be specified only once, either in
`start` command with `jfr` output or in `stop` command with any other format.
## Intellij IDEA
@@ -47,4 +48,4 @@ can be found in [Profiler Options](https://github.com/async-profiler/async-profi
Intellij IDEA comes bundled with async-profiler, which can be further configured to our needs
by selecting the `Java Profiler` menu option at `Settings/Preferences > Build, Execution, Deployment`
Agent options can be modified for specific use cases and also `Collect native calls` can be checked
to monitor non-java threads and native frames in Java stack traces.
to monitor non-java threads and native frames in Java stack traces.

View File

@@ -5,8 +5,8 @@ below:
## Built-in converter
async-profiler provides a built-in converter which can be used to convert `jfr` output to
readable formats like `FlameGraph` visualization. More details on the built-in converter usage
async-profiler provides a built-in converter which can be used to convert `jfr` output to
readable formats like `FlameGraph` visualization. More details on the built-in converter usage
can be found [here](https://github.com/async-profiler/async-profiler/blob/master/docs/ConverterUsage.md).
## JMC
@@ -20,15 +20,15 @@ provides details on how a `jfr` output can be interpreted using `JMC`.
## IntelliJ IDEA
An open-source profiler
[plugin](https://plugins.jetbrains.com/plugin/20937-java-jfr-profiler) for JDK 11+ allows us to
profile your Java application with JFR and async-profiler and view the results in IntelliJ IDEA,
An open-source profiler
[plugin](https://plugins.jetbrains.com/plugin/20937-java-jfr-profiler) for JDK 11+ allows us to
profile your Java application with JFR and async-profiler and view the results in IntelliJ IDEA,
as well as opening JFR files.
## JFR command line
`jfr` provides a command line option to filter, summarize and output flight recording files
`jfr` provides a command line option to filter, summarize and output flight recording files
into human-readable format. The
[official documentation](https://docs.oracle.com/en/java/javase/21/docs/specs/man/jfr.html)
provides complete information on how to manipulate the contents and translate them as per
developers' needs to debug performance issues with their Java applications.
developers' needs to debug performance issues with their Java applications.

View File

@@ -1,27 +1,27 @@
# Output Formats
async-profiler currently supports the below output formats:
* `collapsed` - This is a collection of call stacks, where each line is a semicolon separated list of frames followed
- `collapsed` - This is a collection of call stacks, where each line is a semicolon separated list of frames followed
by a counter. This is used by the FlameGraph script to generate the FlameGraph visualization of the profile data.
![](https://github.com/async-profiler/async-profiler/blob/master/.assets/images/collapsed_example.png)
* `flamegraph` - FlameGraph is a hierarchical representation of call traces of the profiled software in a color coded
- `flamegraph` - FlameGraph is a hierarchical representation of call traces of the profiled software in a color coded
format that helps to identify a particular resource usage like CPU and memory for the application.
![](https://github.com/async-profiler/async-profiler/blob/master/.assets/images/flamegraph_example.png)
* `tree` - Profile output generated in a html format showing a tree view of resource usage beginning with the call stack
with the highest resource usage and then showing other call stacks in descending order of resource usage. Expanding a
- `tree` - Profile output generated in a html format showing a tree view of resource usage beginning with the call stack
with the highest resource usage and then showing other call stacks in descending order of resource usage. Expanding a
parent frame follows the same hierarchical representation within that frame.
![](https://github.com/async-profiler/async-profiler/blob/master/.assets/images/treeview_example.png)
* `text` - If no output format is specified with `-o` and filename has no extension provided, profiled output is
- `text` - If no output format is specified with `-o` and filename has no extension provided, profiled output is
generated in text format.
```
--- Execution profile ---
Total samples : 733
--- 8208 bytes (19.58%), 1 sample
[ 0] byte[]
[ 1] java.util.jar.Manifest$FastInputStream.<init>
@@ -44,7 +44,7 @@ async-profiler currently supports the below output formats:
[18] sun.launcher.LauncherHelper.checkAndLoadMain
```
* `jfr` - Java Flight Recording(JFR) is a widely known tool for profiling Java applications. The `jfr` format collects data
- `jfr` - Java Flight Recording(JFR) is a widely known tool for profiling Java applications. The `jfr` format collects data
about the JVM as well as the Java application running on it. async-profiler can generate output in `jfr` format
compatible with tools capable of viewing and analyzing `jfr` files. Java Mission Control(JMC) and Intellij IDEA are
some of many options to visualize `jfr` files. More details [here](https://github.com/async-profiler/async-profiler/blob/master/JfrVisualization.md).

View File

@@ -12,68 +12,71 @@ Usage: asprof [action] [options] [PID]
The below options are `action`s for async-profiler and common for both `asprof` binary and when `launching as an agent`
| Option | Description |
|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `start` | Starts profiling in semi-automatic mode, i.e. profiler will run until `stop` command is explicitly called. |
| `resume` | Starts or resumes earlier profiling session that has been stopped. All the collected data remains valid. The profiling options are not preserved between sessions, and should be specified again. |
| `stop` | Stops profiling and prints the report. |
| `dump` | Dump collected data without stopping profiling session. |
| `check` | Check if the specified profiling event is available. |
| `status` | Prints profiling status: whether profiler is active and for how long. |
| `meminfo` | Prints used memory statistics. |
| `list` | Show the list of profiling events available for the target process specified with PID. |
| Option | Description |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `start` | Starts profiling in semi-automatic mode, i.e. profiler will run until `stop` command is explicitly called. |
| `resume` | Starts or resumes earlier profiling session that has been stopped. All the collected data remains valid. The profiling options are not preserved between sessions, and should be specified again. |
| `stop` | Stops profiling and prints the report. |
| `dump` | Dump collected data without stopping profiling session. |
| `check` | Check if the specified profiling event is available. |
| `status` | Prints profiling status: whether profiler is active and for how long. |
| `meminfo` | Prints used memory statistics. |
| `list` | Show the list of profiling events available for the target process specified with PID. |
## Options applicable to any output format
| asprof | Launch as agent | Description |
|--------------------|-------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `-o fmt` | `fmt` | Specifies what information to dump when profiling ends. For various dump option details, please refer to [Dump Option Appendix](#dump-option). |
| `-d N` | N/A | asprof-only option designed for interactive use. It is a shortcut for running 3 actions: start, sleep for N seconds, stop. If no `start`, `resume`, `stop` or `status` option is given, the profiler will run for the specified period of time and then automatically stop.<br>Example: `asprof -d 30 <pid>`` |
| `--timeout N` | `timeout=N` | The profiling duration, in seconds. The profiler will run for the specified period of time and then automatically stop.<br>Example: `java -agentpath:/path/to/libasyncProfiler.so=start,event=cpu,timeout=30,file=profile.html <application>` |
| `-e --event EVENT` | `event=EVENT` | The profiling event: `cpu`, `alloc`, `lock`, `cache-misses` etc. Use `list` to see the complete list of available events.<br>Please refer to [Special Event Types](https://github.com/async-profiler/async-profiler/blob/master/docs/ProfilingModes.md#special-event-types-supported-on-linux) for additional information. |
| `-i --interval N` | `interval=N` | Interval has different meaning depending on the event. For CPU profiling, it's CPU time. In wall clock mode, it's wall clock time. For Java method profiling or native function profiling, it's number of calls. For PMU profiling, it's number of events.<br>Example: `asprof -e cpu -i 500us 8983` |
| `--alloc N` | `alloc=N` | Allocation profiling interval in bytes or in other units, if N is followed by `k` (kilobytes), `m` (megabytes), or `g` (gigabytes). |
| `--live` | `live` | Retain allocation samples with live objects only (object that have not been collected by the end of profiling session). Useful for finding Java heap memory leaks. |
| `--lock DURATION` | `lock=DURATION` | In lock profiling mode, sample contended locks when total lock duration overflows the threshold |
| `-j N` | `jstackdepth=N` | Sets the maximum stack depth. The default is 2048.<br>Example: `asprof -j 30 8983` |
| `-I PATTERN` | `include=PATTERN` | Filter stack traces by the given pattern(s). `-I` defines the name pattern that *must* be present in the stack traces. `-I` can be specified multiple times. A pattern may begin or end with a star `*` that denotes any (possibly empty) sequence of characters.<br>Example: `asprof -I 'Primes.*' -I 'java/*' 8983` |
| `-X PATTERN` | `exclude=PATTERN` | Filter stack traces by the given pattern(s). `-X` defines the name pattern that *must not* occur in any of stack traces in the output. `-X` can be specified multiple times. A pattern may begin or end with a star `*` that denotes any (possibly empty) sequence of characters.<br>Example: `asprof -X '*Unsafe.park*' 8983` |
| `-L level` | `loglevel=level` | Log level: `debug`, `info`, `warn`, `error` or `none`. |
| asprof | Launch as agent | Description |
| ------------------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-o fmt` | `fmt` | Specifies what information to dump when profiling ends. For various dump option details, please refer to [Dump Option Appendix](#dump-option). |
| `-d N` | N/A | asprof-only option designed for interactive use. It is a shortcut for running 3 actions: start, sleep for N seconds, stop. If no `start`, `resume`, `stop` or `status` option is given, the profiler will run for the specified period of time and then automatically stop.<br>Example: `asprof -d 30 <pid>`` |
| `--timeout N` | `timeout=N` | The profiling duration, in seconds. The profiler will run for the specified period of time and then automatically stop.<br>Example: `java -agentpath:/path/to/libasyncProfiler.so=start,event=cpu,timeout=30,file=profile.html <application>` |
| `-e --event EVENT` | `event=EVENT` | The profiling event: `cpu`, `alloc`, `lock`, `cache-misses` etc. Use `list` to see the complete list of available events.<br>Please refer to [Special Event Types](https://github.com/async-profiler/async-profiler/blob/master/docs/ProfilingModes.md#special-event-types-supported-on-linux) for additional information. |
| `-i --interval N` | `interval=N` | Interval has different meaning depending on the event. For CPU profiling, it's CPU time. In wall clock mode, it's wall clock time. For Java method profiling or native function profiling, it's number of calls. For PMU profiling, it's number of events.<br>Example: `asprof -e cpu -i 500us 8983` |
| `--alloc N` | `alloc=N` | Allocation profiling interval in bytes or in other units, if N is followed by `k` (kilobytes), `m` (megabytes), or `g` (gigabytes). |
| `--live` | `live` | Retain allocation samples with live objects only (object that have not been collected by the end of profiling session). Useful for finding Java heap memory leaks. |
| `--lock DURATION` | `lock=DURATION` | In lock profiling mode, sample contended locks when total lock duration overflows the threshold |
| `-j N` | `jstackdepth=N` | Sets the maximum stack depth. The default is 2048.<br>Example: `asprof -j 30 8983` |
| `-I PATTERN` | `include=PATTERN` | Filter stack traces by the given pattern(s). `-I` defines the name pattern that _must_ be present in the stack traces. `-I` can be specified multiple times. A pattern may begin or end with a star `*` that denotes any (possibly empty) sequence of characters.<br>Example: `asprof -I 'Primes.*' -I 'java/*' 8983` |
| `-X PATTERN` | `exclude=PATTERN` | Filter stack traces by the given pattern(s). `-X` defines the name pattern that _must not_ occur in any of stack traces in the output. `-X` can be specified multiple times. A pattern may begin or end with a star `*` that denotes any (possibly empty) sequence of characters.<br>Example: `asprof -X '*Unsafe.park*' 8983` |
| `-L level` | `loglevel=level` | Log level: `debug`, `info`, `warn`, `error` or `none`. |
| `-F features` | `features=LIST` | Comma separated (or `+` separated when launching as an agent) list of stack walking features. Supported features are:<ul><li>`stats` - log stack walking performance stats.</li><li>`vtable` - display targets of megamorphic virtual calls as an extra frame on top of `vtable stub` or `itable stub`.</li><li>`comptask` - display current compilation task (a Java method being compiled) in a JIT compiler stack trace.</li><li>`pcaddr` - display instruction addresses .</li></ul>More details [here](https://github.com/async-profiler/async-profiler/blob/master/docs/AdvancedStacktraceFeatures.md). |
| `-f FILENAME` | `file` | The file name to dump the profile information to.<br>`%p` in the file name is expanded to the PID of the target JVM;<br>`%t` - to the timestamp;<br>`%n{MAX}` - to the sequence number;<br>`%{ENV}` - to the value of the given environment variable.<br>Example: `asprof -o collapsed -f /tmp/traces-%t.txt 8983` |
| `--loop TIME` | `loop=TIME` | Run profiler in a loop (continuous profiling). The argument is either a clock time (`hh:mm:ss`) or a loop duration in `s`econds, `m`inutes, `h`ours, or `d`ays. Make sure the filename includes a timestamp pattern, or the output will be overwritten on each iteration.<br>Example: `asprof --loop 1h -f /var/log/profile-%t.jfr 8983` |
| `--all-user` | `alluser` | Include only user-mode events. This option is helpful when kernel profiling is restricted by `perf_event_paranoid` settings. |
| `--sched` | `sched` | Group threads by Linux-specific scheduling policy: BATCH/IDLE/OTHER. |
| `--cstack MODE` | `cstack=MODE` | How to walk native frames (C stack). Possible modes are `fp` (Frame Pointer), `dwarf` (DWARF unwind info), `lbr` (Last Branch Record, available on Haswell since Linux 4.1), `vm`, `vmx` (HotSpot VM Structs) and `no` (do not collect C stack).<br><br>By default, C stack is shown in cpu, ctimer, wall-clock and perf-events profiles. Java-level events like `alloc` and `lock` collect only Java stack. |
| `--signal NUM` | `signal=NUM` | Use alternative signal for cpu or wall clock profiling. To change both signals, specify two numbers separated by a slash: `--signal SIGCPU/SIGWALL`. |
| `--clock SOURCE` | `clock=SOURCE` | Clock source for JFR timestamps: `tsc` (default) or `monotonic` (equivalent for `CLOCK_MONOTONIC`). |
| `--begin function` | `begin=FUNCTION` | Automatically start profiling when the specified native function is executed. |
| `--end function` | `end=FUNCTION` | Automatically stop profiling when the specified native function is executed. |
| `--ttsp` | `ttsp` | time-to-safepoint profiling. An alias for `--begin SafepointSynchronize::begin --end RuntimeService::record_safepoint_synchronized`.<br>It is not a separate event type, but rather a constraint. Whatever event type you choose (e.g. `cpu` or `wall`), the profiler will work as usual, except that only events between the safepoint request and the start of the VM operation will be recorded. |
| `--libpath PATH` | `libpath=PATH` | Full path to libasyncProfiler.so in the container |
| `--filter FILTER` | `filter=FILTER` | Filter threads with thread ids during wall-clock profiling mode |
| `--fdtransfer` | `fdtransfer` | Runs a background process that provides access to perf_events to an unprivileged process. `--fdtransfer` is useful for profiling a process in a container (which lacks access to perf_events) from the host.<br>See [Profiling Java in a container](#https://github.com/async-profiler/async-profiler/blob/master/docs/ProfilingInContainer.md). |
| `-v --version` | `version` | Prints the version of profiler library. If PID is specified, gets the version of the library loaded into the given process. |
| `-f FILENAME` | `file` | The file name to dump the profile information to.<br>`%p` in the file name is expanded to the PID of the target JVM;<br>`%t` - to the timestamp;<br>`%n{MAX}` - to the sequence number;<br>`%{ENV}` - to the value of the given environment variable.<br>Example: `asprof -o collapsed -f /tmp/traces-%t.txt 8983` |
| `--loop TIME` | `loop=TIME` | Run profiler in a loop (continuous profiling). The argument is either a clock time (`hh:mm:ss`) or a loop duration in `s`econds, `m`inutes, `h`ours, or `d`ays. Make sure the filename includes a timestamp pattern, or the output will be overwritten on each iteration.<br>Example: `asprof --loop 1h -f /var/log/profile-%t.jfr 8983` |
| `--all-user` | `alluser` | Include only user-mode events. This option is helpful when kernel profiling is restricted by `perf_event_paranoid` settings. |
| `--sched` | `sched` | Group threads by Linux-specific scheduling policy: BATCH/IDLE/OTHER. |
| `--cstack MODE` | `cstack=MODE` | How to walk native frames (C stack). Possible modes are `fp` (Frame Pointer), `dwarf` (DWARF unwind info), `lbr` (Last Branch Record, available on Haswell since Linux 4.1), `vm`, `vmx` (HotSpot VM Structs) and `no` (do not collect C stack).<br><br>By default, C stack is shown in cpu, ctimer, wall-clock and perf-events profiles. Java-level events like `alloc` and `lock` collect only Java stack. |
| `--signal NUM` | `signal=NUM` | Use alternative signal for cpu or wall clock profiling. To change both signals, specify two numbers separated by a slash: `--signal SIGCPU/SIGWALL`. |
| `--clock SOURCE` | `clock=SOURCE` | Clock source for JFR timestamps: `tsc` (default) or `monotonic` (equivalent for `CLOCK_MONOTONIC`). |
| `--begin function` | `begin=FUNCTION` | Automatically start profiling when the specified native function is executed. |
| `--end function` | `end=FUNCTION` | Automatically stop profiling when the specified native function is executed. |
| `--ttsp` | `ttsp` | time-to-safepoint profiling. An alias for `--begin SafepointSynchronize::begin --end RuntimeService::record_safepoint_synchronized`.<br>It is not a separate event type, but rather a constraint. Whatever event type you choose (e.g. `cpu` or `wall`), the profiler will work as usual, except that only events between the safepoint request and the start of the VM operation will be recorded. |
| `--libpath PATH` | `libpath=PATH` | Full path to libasyncProfiler.so in the container |
| `--filter FILTER` | `filter=FILTER` | Filter threads with thread ids during wall-clock profiling mode |
| `--fdtransfer` | `fdtransfer` | Runs a background process that provides access to perf_events to an unprivileged process. `--fdtransfer` is useful for profiling a process in a container (which lacks access to perf_events) from the host.<br>See [Profiling Java in a container](#https://github.com/async-profiler/async-profiler/blob/master/docs/ProfilingInContainer.md). |
| `-v --version` | `version` | Prints the version of profiler library. If PID is specified, gets the version of the library loaded into the given process. |
## Options applicable to JFR output only
| asprof | Launch as agent | Description |
|----------------------|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `--chunksize N` | `chunksize=N` | Approximate size for a single JFR chunk. A new chunk will be started whenever specified size is reached. The default `chunksize` is 100MB.<br>Example: `asprof -f profile.jfr --chunksize 100m 8983` |
| `--chunktime N` | `chunktime=N` | Approximate time limit for a single JFR chunk. A new chunk will be started whenever specified time limit is reached. The default `chunktime` is 1 hour.<br>Example: `asprof -f profile.jfr --chunktime 1h 8983` |
| `--jfropts OPTIONS` | `jfropts=OPTIONS` | Comma separated list of JFR recording options. Currently, the only available option is `mem` supported on Linux 3.17+. `mem` enables accumulating events in memory instead of flushing synchronously to a file. |
| `--jfrsync CONFIG` | `jfrsync[=CONFIG]` | Start Java Flight Recording with the given configuration synchronously with the profiler. The output .jfr file will include all regular JFR events, except that execution samples will be obtained from async-profiler. This option implies `-o jfr`.<br>`CONFIG` is a predefined JFR profile or a JFR configuration file (.jfc) or a list of JFR events started with `+`.<br><br>Example: `asprof -e cpu --jfrsync profile -f combined.jfr 8983` |
| asprof | Launch as agent | Description |
| ------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `--chunksize N` | `chunksize=N` | Approximate size for a single JFR chunk. A new chunk will be started whenever specified size is reached. The default `chunksize` is 100MB.<br>Example: `asprof -f profile.jfr --chunksize 100m 8983` |
| `--chunktime N` | `chunktime=N` | Approximate time limit for a single JFR chunk. A new chunk will be started whenever specified time limit is reached. The default `chunktime` is 1 hour.<br>Example: `asprof -f profile.jfr --chunktime 1h 8983` |
| `--jfropts OPTIONS` | `jfropts=OPTIONS` | Comma separated list of JFR recording options. Currently, the only available option is `mem` supported on Linux 3.17+. `mem` enables accumulating events in memory instead of flushing synchronously to a file. |
| `--jfrsync CONFIG` | `jfrsync[=CONFIG]` | Start Java Flight Recording with the given configuration synchronously with the profiler. The output .jfr file will include all regular JFR events, except that execution samples will be obtained from async-profiler. This option implies `-o jfr`.<br>`CONFIG` is a predefined JFR profile or a JFR configuration file (.jfc) or a list of JFR events started with `+`.<br><br>Example: `asprof -e cpu --jfrsync profile -f combined.jfr 8983` |
## Options applicable to FlameGraph and Tree view outputs only
| asprof | Launch as agent | Description |
|----------------------|--------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `--title TITLE` | `title=TITLE` | Custom title of a FlameGraph.<br>Example: `asprof -f profile.html --title "Sample CPU profile" 8983` |
| `--minwidth PERCENT` | `minwidth=PERCENT` | Minimum frame width as a percentage. Smaller frames will not be visible.<br>Example: `asprof -f profile.html --minwidth 0.5 8983` |
| `--reverse` | `reverse` | Reverse stack traces.<br>Example: `asprof -f profile.html --reverse 8983` |
| asprof | Launch as agent | Description |
| -------------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `--title TITLE` | `title=TITLE` | Custom title of a FlameGraph.<br>Example: `asprof -f profile.html --title "Sample CPU profile" 8983` |
| `--minwidth PERCENT` | `minwidth=PERCENT` | Minimum frame width as a percentage. Smaller frames will not be visible.<br>Example: `asprof -f profile.html --minwidth 0.5 8983` |
| `--reverse` | `reverse` | Reverse stack traces.<br>Example: `asprof -f profile.html --reverse 8983` |
## Options applicable to any output format except JFR
| asprof | Launch as agent | Description |
|----------------|-----------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `-t --threads` | `threads` | Profile threads separately. Each stack trace will end with a frame that denotes a single thread.<br>Example: `asprof -t 8983` |
| -------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `-t --threads` | `threads` | Profile threads separately. Each stack trace will end with a frame that denotes a single thread.<br>Example: `asprof -t 8983` |
| `-s --simple` | `simple` | Print simple class names instead of fully qualified names. |
| `-n --norm` | `norm` | Normalize names of hidden classes / lambdas. |
| `-g --sig` | `sig` | Print method signatures. |
@@ -87,11 +90,12 @@ The below options are `action`s for async-profiler and common for both `asprof`
`-o fmt` - specifies what information to dump when profiling ends.
`fmt` can be one of the following options:
- `traces[=N]` - dump call traces (at most N samples);
- `flat[=N]` - dump flat profile (top N hot methods);
can be combined with `traces`, e.g. `traces=200,flat=200`
- `jfr` - dump events in Java Flight Recorder format readable by Java Mission Control.
This *does not* require JDK commercial features to be enabled.
This _does not_ require JDK commercial features to be enabled.
- `collapsed` - dump collapsed call traces in the format used by
[FlameGraph](https://github.com/brendangregg/FlameGraph) script. This is
a collection of call stacks, where each line is a semicolon separated list

View File

@@ -15,6 +15,7 @@ absolute path as on the host.
By default, Docker container restricts the access to `perf_event_open`
syscall. There are 3 alternatives to allow profiling in a container:
1. You can modify the [seccomp profile](https://docs.docker.com/engine/security/seccomp/)
or disable it altogether with `--security-opt seccomp=unconfined` option. In
addition, `--cap-add SYS_ADMIN` may be required.

View File

@@ -18,15 +18,15 @@ where `AsyncGetCallTrace` fails.
This approach has the following advantages compared to using `perf_events`
directly with a Java agent that translates addresses to Java method names:
* Does not require `-XX:+PreserveFramePointer`, which introduces
- Does not require `-XX:+PreserveFramePointer`, which introduces
performance overhead that can be sometimes as high as 10%.
* Does not require generating a map file for translating Java code addresses
- Does not require generating a map file for translating Java code addresses
to method names.
* Displays interpreter frames.
- Displays interpreter frames.
* Does not produce large intermediate files (perf.data) for further processing in
- Does not produce large intermediate files (perf.data) for further processing in
user space scripts.
If you wish to resolve frames within `libjvm`, the [debug symbols](#installing-debug-symbols) are required.
@@ -43,6 +43,7 @@ like allocation elimination. Only actual heap allocations are measured.
The profiler features TLAB-driven sampling. It relies on HotSpot-specific
callbacks to receive two kinds of notifications:
- when an object is allocated in a newly created TLAB;
- when an object is allocated on a slow path outside TLAB.
@@ -61,13 +62,16 @@ Some OpenJDK distributions (Amazon Corretto, Liberica JDK, Azul Zulu)
already have them embedded in `libjvm.so`, other OpenJDK builds typically
provide debug symbols in a separate package. For example, to install
OpenJDK debug symbols on Debian / Ubuntu, run:
```
# apt install openjdk-17-dbg
```
(replace `17` with the desired version of JDK).
On CentOS, RHEL and some other RPM-based distributions, this could be done with
[debuginfo-install](http://man7.org/linux/man-pages/man1/debuginfo-install.1.html) utility:
```
# debuginfo-install java-1.8.0-openjdk
```
@@ -77,9 +81,11 @@ On Gentoo the `icedtea` OpenJDK package can be built with the per-package settin
The `gdb` tool can be used to verify if debug symbols are properly installed for the `libjvm` library.
For example, on Linux:
```
$ gdb $JAVA_HOME/lib/server/libjvm.so -ex 'info address UseG1GC'
```
This command's output will either contain `Symbol "UseG1GC" is at 0xxxxx`
or `No symbol "UseG1GC" in current context`.
@@ -93,7 +99,6 @@ Wall-clock profiler is most useful in per-thread mode: `-t`.
Example: `asprof -e wall -t -i 5ms -f result.html 8983`
## Lock profiling
`-e lock` option tells async-profiler to measure lock contention in the profiled application. Lock profiling can help
@@ -123,10 +128,12 @@ of all compiled methods. The subsequent instrumentation flushes only the _depend
The massive CodeCache flush doesn't occur if attaching async-profiler as an agent.
### Java native method profiling
Here are some useful native methods to profile:
* ```G1CollectedHeap::humongous_obj_allocate``` - trace _humongous allocations_ of the G1 GC,
* ```JVM_StartThread``` - trace creation of new Java threads,
* ```Java_java_lang_ClassLoader_defineClass1``` - trace class loading.
- `G1CollectedHeap::humongous_obj_allocate` - trace _humongous allocations_ of the G1 GC,
- `JVM_StartThread` - trace creation of new Java threads,
- `Java_java_lang_ClassLoader_defineClass1` - trace class loading.
## Multiple events
@@ -136,6 +143,7 @@ perf event, tracepoint, Java method, etc.
The only output format that supports multiple events together is JFR.
The recording will contain the following event types:
- `jdk.ExecutionSample`
- `jdk.ObjectAllocationInNewTLAB` (alloc)
- `jdk.ObjectAllocationOutsideTLAB` (alloc)
@@ -143,29 +151,36 @@ The recording will contain the following event types:
- `jdk.ThreadPark` (lock)
To start profiling cpu + allocations + locks together, specify
```
asprof -e cpu,alloc,lock -f profile.jfr ...
```
or use `--alloc` and `--lock` parameters with the desired threshold:
```
asprof -e cpu --alloc 2m --lock 10ms -f profile.jfr ...
```
The same, when starting profiler as an agent:
```
-agentpath:/path/to/libasyncProfiler.so=start,event=cpu,alloc=2m,lock=10ms,file=profile.jfr
```
## Continuous profiling
Continuous profiling is a means using which an application can be profiled
continuously and dump profile outputs after a specified amount of time duration.
It is a very effective technique in finding performance degradations proactively
continuously and dump profile outputs after a specified amount of time duration.
It is a very effective technique in finding performance degradations proactively
and efficiently. Continuous profiling helps users to understand performance
differences between versions of the same application. Recent outputs can
be compared with continuous profiling output history to find differences
and optimize the changes introduced in case of performance degradations.
aysnc-profiler provides the ability to continously profile an application with
the `loop` option. Make sure the filename includes a timestamp pattern, or the
be compared with continuous profiling output history to find differences
and optimize the changes introduced in case of performance degradations.
aysnc-profiler provides the ability to continously profile an application with
the `loop` option. Make sure the filename includes a timestamp pattern, or the
output will be overwritten on each iteration.
```
asprof --loop 1h -f /var/log/profile-%t.jfr 8983
```
@@ -173,6 +188,7 @@ asprof --loop 1h -f /var/log/profile-%t.jfr 8983
## Special event types supported on Linux
Below special event types are supported on Linux:
- `-e mem:<func>[:rwx]` sets read/write/exec breakpoint at function
`<func>`. The format of `mem` event is the same as in `perf-record`.
Execution breakpoints can be also specified by the function name,

View File

@@ -1,15 +1,16 @@
# Profiling Non-Java applications
The scope of profiling non-java applications is limited to the case when profiler is controlled
programmatically from the process being profiled and with LD_PRELOAD. It is worth noting that
[dynamic attach](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#launching-as-an-agent)
programmatically from the process being profiled and with LD_PRELOAD. It is worth noting that
[dynamic attach](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#launching-as-an-agent)
which is available for Java is not supported for non-Java profiling.
## C API
Similar to the
[Java API](https://github.com/async-profiler/async-profiler/blob/master/docs/IntegratingAsyncProfiler.md#using-java-api),
there is a C API for using inside native applications.
```
typedef const char* asprof_error_t;
typedef void (*asprof_writer_t)(const char* buf, size_t size);
@@ -27,7 +28,9 @@ typedef const char* (*asprof_error_str_t)(asprof_error_t err);
DLLEXPORT asprof_error_t asprof_execute(const char* command, asprof_writer_t output_callback);
typedef asprof_error_t (*asprof_execute_t)(const char* command, asprof_writer_t output_callback);
```
To use it in a C/C++ application, include asprof.h. Below is an example usage showing how to use async-profiler command with the API:
```
#include "asprof.h"
#include <dlfcn.h>
@@ -53,13 +56,13 @@ int main() {
dlclose(lib);
exit(1);
}
asprof_init();
char cmd[] = "start,event=cpu,loglevel=debug,file=profile.jfr";
printf("Starting profiler\n");
asprof_execute_t asprof_execute = (asprof_execute_t)dlsym(lib, "asprof_execute");
if(asprof_execute == NULL) {
printf("%s\n", dlerror());
@@ -88,10 +91,11 @@ int main() {
```
In addition, async-profiler can be injected into a native application through LD_PRELOAD mechanism:
```
LD_PRELOAD=/path/to/libasyncProfiler.so ASPROF_COMMAND=start,event=cpu,file=profile.jfr NativeApp [args]
```
All basic functionality remains the same. Profiler can run in cpu, wall and other perf_events
All basic functionality remains the same. Profiler can run in cpu, wall and other perf_events
modes. Flame Graph and JFR output formats are supported, although JFR files will obviously lack
Java-specific events.

View File

@@ -24,13 +24,13 @@ The feature can be enabled with the option `--cstack dwarf` (or its agent equiva
Modern Intel CPUs can profile branch instructions, including `call`s and `ret`s, and store their source and destination
addresses (Last Branch Records) in hardware registers. Starting from Haswell, CPU can match these addresses to form a
branch stack. This branch stack will be effectively a call chain automatically collected by the hardware.
branch stack. This branch stack will be effectively a call chain automatically collected by the hardware.
LBR stacks are not always complete or accurate, but they still appear much more helpful comparing to FP-based stack
walking, when a native library is compiled with omitted frame pointers. It works only with hardware events like
`-e cycles` (`instructions`, `cache-misses` etc.) and the maximum call chain depth is 32 (hardware limit).
The feature can be enabled with the option `--cstack lbr` (or its agent equivalent `cstack=lbr`).
The feature can be enabled with the option `--cstack lbr` (or its agent equivalent `cstack=lbr`).
## VM Structs
@@ -51,6 +51,7 @@ AsyncGetCallTrace can crash JVM, and there is no reliable way to get around this
Due to issues with AGCT from time to time, including random crashes and missing stack traces,
`vm` stack walking mode based on HotSpot VM Structs was introduced in async-profiler.
`vm` stack walker has the following advantages:
- Fully enclosed by the crash protection based on `setjmp`/`longjmp`.
- Can show all frames: Java, native and JVM stubs throughout the whole stack.
- Provides additional information on each frame, like JIT compilation type.

View File

@@ -1,137 +1,127 @@
# Troubleshooting
* ```
perf_event mmap failed: Operation not permitted
```
Profiler allocates 8kB perf_event buffer for each thread of the target process.
Make sure `/proc/sys/kernel/perf_event_mlock_kb` value is large enough
(more than `8 * threads`) when running under unprivileged user. Otherwise, the above message
will be printed, and no native stack traces will be collected.
## Error Messages
* ```
Failed to change credentials to match the target process: Operation not permitted
```
Due to limitation of HotSpot Dynamic Attach mechanism, the profiler must be run
by exactly the same user (and group) as the owner of target JVM process.
If profiler is run by a different user, it will try to automatically change
current user and group. This will likely succeed for `root`, but not for
other users, resulting in the above error.
### perf_event mmap failed: Operation not permitted
Profiler allocates 8kB perf_event buffer for each thread of the target process.
Make sure `/proc/sys/kernel/perf_event_mlock_kb` value is large enough
(more than `8 * threads`) when running under unprivileged user. Otherwise, the above message
will be printed, and no native stack traces will be collected.
* ```
Could not start attach mechanism: No such file or directory
```
The profiler cannot establish communication with the target JVM through UNIX domain socket.
Usually this happens in one of the following cases:
1. Attach socket `/tmp/.java_pidNNN` has been deleted. It is a common
practice to clean `/tmp` automatically with some scheduled script.
Configure the cleanup software to exclude `.java_pid*` files from deletion.
How to check: run `lsof -p PID | grep java_pid`
If it lists a socket file, but the file does not exist, then this is exactly
### Failed to change credentials to match the target process: Operation not permitted
Due to limitation of HotSpot Dynamic Attach mechanism, the profiler must be run
by exactly the same user (and group) as the owner of target JVM process.
If profiler is run by a different user, it will try to automatically change
current user and group. This will likely succeed for `root`, but not for
other users, resulting in the above error.
### Could not start attach mechanism: No such file or directory
The profiler cannot establish communication with the target JVM through UNIX domain socket.
Usually this happens in one of the following cases:
1. Attach socket `/tmp/.java_pidNNN` has been deleted. It is a common
practice to clean `/tmp` automatically with some scheduled script.
Configure the cleanup software to exclude `.java_pid*` files from deletion.
- How to check: run `lsof -p PID | grep java_pid`. If it lists a socket file, but the file does not exist, then this is exactly
the described problem.
2. JVM is started with `-XX:+DisableAttachMechanism` option.
3. `/tmp` directory of Java process is not physically the same directory
as `/tmp` of your shell, because Java is running in a container or in
`chroot` environment. `jattach` attempts to solve this automatically,
but it might lack the required permissions to do so.
Check `strace build/jattach PID properties`
4. JVM is busy and cannot reach a safepoint. For instance,
JVM is in the middle of long-running garbage collection.
How to check: run `kill -3 PID`. Healthy JVM process should print
a thread dump and heap info in its console.
* ```
Target JVM failed to load libasyncProfiler.so
```
The connection with the target JVM has been established, but JVM is unable to load profiler shared library.
Make sure the user of JVM process has permissions to access `libasyncProfiler.so` by exactly the same absolute path.
For more information see [#78](https://github.com/async-profiler/async-profiler/issues/78).
2. JVM is started with `-XX:+DisableAttachMechanism` option.
3. `/tmp` directory of Java process is not physically the same directory
as `/tmp` of your shell, because Java is running in a container or in
`chroot` environment. `jattach` attempts to solve this automatically,
but it might lack the required permissions to do so.
- Check `strace build/jattach PID properties`
4. JVM is busy and cannot reach a safepoint. For instance,
JVM is in the middle of long-running garbage collection.
- How to check: run `kill -3 PID`. Healthy JVM process should print
a thread dump and heap info in its console.
### Target JVM failed to load libasyncProfiler.so
* ```
Perf events unavailable
```
`perf_event_open()` syscall has failed. Typical reasons include:
1. `/proc/sys/kernel/perf_event_paranoid` is set to restricted mode (>=2).
2. seccomp disables `perf_event_open` API in a container.
3. OS runs under a hypervisor that does not virtualize performance counters.
4. perf_event_open API is not supported on this system, e.g. WSL.
The connection with the target JVM has been established, but JVM is unable to load profiler shared library.
Make sure the user of JVM process has permissions to access `libasyncProfiler.so` by exactly the same absolute path.
For more information see [#78](https://github.com/async-profiler/async-profiler/issues/78).
<br>For permissions-related reasons (such as 1 and 2), using `--fdtransfer` while running the profiler
as a privileged user may solve the issue.
If changing the configuration is not possible, you may fall back to
`-e ctimer` profiling mode. It is similar to `cpu` mode, but does not
require perf_events support. As a drawback, there will be no kernel
stack traces.
### Perf events unavailable
* ```
No AllocTracer symbols found. Are JDK debug symbols installed?
```
The OpenJDK debug symbols are required for allocation profiling for applications developed
with JDK prior to 11. See [Installing Debug Symbols](ProfilingModes.md#installing-debug-symbols) for more
details. If the error message persists after a successful installation of the debug symbols,
it is possible that the JDK was upgraded when installing the debug symbols.
In this case, profiling any Java process which had started prior to the installation
will continue to display this message, since the process had loaded
the older version of the JDK which lacked debug symbols.
Restarting the affected Java processes should resolve the issue.
`perf_event_open()` syscall has failed. Typical reasons include:
* ```
VMStructs unavailable. Unsupported JVM?
```
JVM shared library does not export `gHotSpotVMStructs*` symbols -
apparently this is not a HotSpot JVM. Sometimes the same message
can be also caused by an incorrectly built JDK
(see [#218](https://github.com/async-profiler/async-profiler/issues/218)).
In these cases installing JDK debug symbols may solve the problem.
1. `/proc/sys/kernel/perf_event_paranoid` is set to restricted mode (>=2).
2. seccomp disables `perf_event_open` API in a container.
3. OS runs under a hypervisor that does not virtualize performance counters.
4. perf_event_open API is not supported on this system, e.g. WSL.
* ```
Could not parse symbols from <libname.so>
```
Async-profiler was unable to parse non-Java function names because of
the corrupted contents in `/proc/[pid]/maps`. The problem is known to
occur in a container when running Ubuntu with Linux kernel 5.x.
This is the OS bug, see https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1843018.
<br>For permissions-related reasons (such as 1 and 2), using `--fdtransfer` while running the profiler
as a privileged user may solve the issue.
* ```
Could not open output file
```
Output file is written by the target JVM process, not by the profiler script.
Make sure the path specified in `-f` option is correct and is accessible by the JVM.
If changing the configuration is not possible, you may fall back to
`-e ctimer` profiling mode. It is similar to `cpu` mode, but does not
require perf_events support. As a drawback, there will be no kernel
stack traces.
### No AllocTracer symbols found. Are JDK debug symbols installed?
* No Java stacks will be collected if `-XX:MaxJavaStackTraceDepth` is zero
or negative. The exception is `--cstack vm` mode, which does not take
`MaxJavaStackTraceDepth` into account.
The OpenJDK debug symbols are required for allocation profiling for applications developed
with JDK prior to 11. See [Installing Debug Symbols](ProfilingModes.md#installing-debug-symbols) for more
details. If the error message persists after a successful installation of the debug symbols,
it is possible that the JDK was upgraded when installing the debug symbols.
In this case, profiling any Java process which had started prior to the installation
will continue to display this message, since the process had loaded
the older version of the JDK which lacked debug symbols.
Restarting the affected Java processes should resolve the issue.
### VMStructs unavailable. Unsupported JVM?
* Too short profiling interval may cause continuous interruption of heavy
system calls like `clone()`, so that it will never complete;
see [#97](https://github.com/async-profiler/async-profiler/issues/97).
The workaround is simply to increase the interval.
JVM shared library does not export `gHotSpotVMStructs*` symbols -
apparently this is not a HotSpot JVM. Sometimes the same message
can be also caused by an incorrectly built JDK
(see [#218](https://github.com/async-profiler/async-profiler/issues/218)).
In these cases installing JDK debug symbols may solve the problem.
### Could not parse symbols from <libname.so>
* When agent is not loaded at JVM startup (by using -agentpath option) it is
highly recommended to use `-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints` JVM flags.
Without those flags the profiler will still work correctly but results might be
less accurate. For example, without `-XX:+DebugNonSafepoints` there is a high chance
that simple inlined methods will not appear in the profile. When the agent is attached at runtime,
`CompiledMethodLoad` JVMTI event enables debug info, but only for methods compiled after attaching.
Async-profiler was unable to parse non-Java function names because of
the corrupted contents in `/proc/[pid]/maps`. The problem is known to
occur in a container when running Ubuntu with Linux kernel 5.x.
This is the OS bug, see <https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1843018>.
### Could not open output file
* On most Linux systems, `perf_events` captures call stacks with a maximum depth
of 127 frames. On recent Linux kernels, this can be configured using
`sysctl kernel.perf_event_max_stack` or by writing to the
`/proc/sys/kernel/perf_event_max_stack` file.
Output file is written by the target JVM process, not by the profiler script.
Make sure the path specified in `-f` option is correct and is accessible by the JVM.
## Known Limitations
* You will not see the non-Java frames _preceding_ the Java frames on the
stack, unless `--cstack vmx` is specified.
For example, if `start_thread` called `JavaMain` and then your Java
code started running, you will not see the first two frames in the resulting
stack. On the other hand, you _will_ see non-Java frames (user and kernel)
invoked by your Java code.
- No Java stacks will be collected if `-XX:MaxJavaStackTraceDepth` is zero
or negative. The exception is `--cstack vm` mode, which does not take
`MaxJavaStackTraceDepth` into account.
- Too short profiling interval may cause continuous interruption of heavy
system calls like `clone()`, so that it will never complete;
see [#97](https://github.com/async-profiler/async-profiler/issues/97).
The workaround is simply to increase the interval.
* macOS profiling is limited to user space code only.
- When agent is not loaded at JVM startup (by using -agentpath option) it is
highly recommended to use `-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints` JVM flags.
Without those flags the profiler will still work correctly but results might be
less accurate. For example, without `-XX:+DebugNonSafepoints` there is a high chance
that simple inlined methods will not appear in the profile. When the agent is attached at runtime,
`CompiledMethodLoad` JVMTI event enables debug info, but only for methods compiled after attaching.
- On most Linux systems, `perf_events` captures call stacks with a maximum depth
of 127 frames. On recent Linux kernels, this can be configured using
`sysctl kernel.perf_event_max_stack` or by writing to the
`/proc/sys/kernel/perf_event_max_stack` file.
- You will not see the non-Java frames _preceding_ the Java frames on the
stack, unless `--cstack vmx` is specified.
For example, if `start_thread` called `JavaMain` and then your Java
code started running, you will not see the first two frames in the resulting
stack. On the other hand, you _will_ see non-Java frames (user and kernel)
invoked by your Java code.
- macOS profiling is limited to user space code only.