aboutsummaryrefslogtreecommitdiff
path: root/src/share/demo/jvmti/hprof/hprof_listener.c
blob: f5fb89639871f06b6b34dcf597054bc9571d2a5c (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
 * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * This source code is provided to illustrate the usage of a given feature
 * or technique and has been deliberately simplified. Additional steps
 * required for a production-quality application, such as security checks,
 * input validation and proper error handling, might not be present in
 * this sample code.
 */


/* The hprof listener loop thread. net=hostname:port option */

/*
 * The option net=hostname:port causes all hprof output to be sent down
 *   a socket connection, and also allows for commands to come in over the
 *   socket. The commands are documented below.
 *
 * This thread can cause havoc when started prematurely or not terminated
 *   properly, see listener_init() and listener_term(), and their calls
 *   in hprof_init.c.
 *
 * The listener loop (hprof_listener.c) can dynamically turn on or off the
 *  sampling of all or selected threads.
 *
 * The specification of this command protocol is only here, in the comments
 *  below.  The HAT tools uses this interface.
 *  It is also unknown how well these options work given the limited
 *  testing of this interface.
 *
 */

#include "hprof.h"

/* When the hprof Agent in the VM is connected via a socket to the
 * profiling client, the client may send the hprof Agent a set of commands.
 * The commands have the following format:
 *
 * u1           a TAG denoting the type of the record
 * u4           a serial number
 * u4           number of bytes *remaining* in the record. Note that
 *              this number excludes the tag and the length field itself.
 * [u1]*        BODY of the record (a sequence of bytes)
 */

/* The following commands are presently supported:
 *
 * TAG           BODY       notes
 * ----------------------------------------------------------
 * HPROF_CMD_GC             force a GC.
 *
 * HPROF_CMD_DUMP_HEAP      obtain a heap dump
 *
 * HPROF_CMD_ALLOC_SITES    obtain allocation sites
 *
 *               u2         flags 0x0001: incremental vs. complete
 *                                0x0002: sorted by allocation vs. live
 *                                0x0004: whether to force a GC
 *               u4         cutoff ratio (0.0 ~ 1.0)
 *
 * HPROF_CMD_HEAP_SUMMARY   obtain heap summary
 *
 * HPROF_CMD_DUMP_TRACES    obtain all newly created traces
 *
 * HPROF_CMD_CPU_SAMPLES    obtain a HPROF_CPU_SAMPLES record
 *
 *               u2         ignored for now
 *               u4         cutoff ratio (0.0 ~ 1.0)
 *
 * HPROF_CMD_CONTROL        changing settings
 *
 *               u2         0x0001: alloc traces on
 *                          0x0002: alloc traces off
 *
 *                          0x0003: CPU sampling on
 *
 *                                  id:   thread object id (NULL for all)
 *
 *                          0x0004: CPU sampling off
 *
 *                                  id:   thread object id (NULL for all)
 *
 *                          0x0005: CPU sampling clear
 *
 *                          0x0006: clear alloc sites info
 *
 *                          0x0007: set max stack depth in CPU samples
 *                                  and alloc traces
 *
 *                                  u2:   new depth
 */

typedef enum HprofCmd {
    HPROF_CMD_GC                = 0x01,
    HPROF_CMD_DUMP_HEAP         = 0x02,
    HPROF_CMD_ALLOC_SITES       = 0x03,
    HPROF_CMD_HEAP_SUMMARY      = 0x04,
    HPROF_CMD_EXIT              = 0x05,
    HPROF_CMD_DUMP_TRACES       = 0x06,
    HPROF_CMD_CPU_SAMPLES       = 0x07,
    HPROF_CMD_CONTROL           = 0x08,
    HPROF_CMD_EOF               = 0xFF
} HprofCmd;

static jint
recv_fully(int f, char *buf, int len)
{
    jint nbytes;

    nbytes = 0;
    if ( f < 0 ) {
        return nbytes;
    }
    while (nbytes < len) {
        int res;

        res = md_recv(f, buf + nbytes, (len - nbytes), 0);
        if (res < 0) {
            /*
             * hprof was disabled before we returned from recv() above.
             * This means the command socket is closed so we let that
             * trickle back up the command processing stack.
             */
            LOG("recv() returned < 0");
            break;
        }
        nbytes += res;
    }
    return nbytes;
}

static unsigned char
recv_u1(void)
{
    unsigned char c;
    jint nbytes;

    nbytes = recv_fully(gdata->fd, (char *)&c, (int)sizeof(unsigned char));
    if (nbytes == 0) {
        c = HPROF_CMD_EOF;
    }
    return c;
}

static unsigned short
recv_u2(void)
{
    unsigned short s;
    jint nbytes;

    nbytes = recv_fully(gdata->fd, (char *)&s, (int)sizeof(unsigned short));
    if (nbytes == 0) {
        s = (unsigned short)-1;
    }
    return md_ntohs(s);
}

static unsigned
recv_u4(void)
{
    unsigned i;
    jint nbytes;

    nbytes = recv_fully(gdata->fd, (char *)&i, (int)sizeof(unsigned));
    if (nbytes == 0) {
        i = (unsigned)-1;
    }
    return md_ntohl(i);
}

static ObjectIndex
recv_id(void)
{
    ObjectIndex result;
    jint        nbytes;

    nbytes = recv_fully(gdata->fd, (char *)&result, (int)sizeof(ObjectIndex));
    if (nbytes == 0) {
        result = (ObjectIndex)0;
    }
    return result;
}

static void JNICALL
listener_loop_function(jvmtiEnv *jvmti, JNIEnv *env, void *p)
{
    jboolean keep_processing;
    unsigned char tag;
    jboolean kill_the_whole_process;

    kill_the_whole_process = JNI_FALSE;
    tag = 0;

    rawMonitorEnter(gdata->listener_loop_lock); {
        gdata->listener_loop_running = JNI_TRUE;
        keep_processing = gdata->listener_loop_running;
        /* Tell listener_init() that we have started */
        rawMonitorNotifyAll(gdata->listener_loop_lock);
    } rawMonitorExit(gdata->listener_loop_lock);

    while ( keep_processing ) {

        LOG("listener loop iteration");

        tag = recv_u1();  /* This blocks here on the socket read, a close()
                           *   on this fd will wake this up. And if recv_u1()
                           *   can't read anything, it returns HPROF_CMD_EOF.
                           */

        LOG3("listener_loop", "command = ", tag);

        if (tag == HPROF_CMD_EOF) {
            /* The cmd socket has closed so the listener thread is done
             *   just fall out of loop and let the thread die.
             */
            keep_processing = JNI_FALSE;
            break;
        }

        /* seq_num not used */
        (void)recv_u4();
        /* length not used */
        (void)recv_u4();

        switch (tag) {
            case HPROF_CMD_GC:
                runGC();
                break;
            case HPROF_CMD_DUMP_HEAP: {
                site_heapdump(env);
                break;
            }
            case HPROF_CMD_ALLOC_SITES: {
                unsigned short flags;
                unsigned i_tmp;
                float ratio;

                flags = recv_u2();
                i_tmp = recv_u4();
                ratio = *(float *)(&i_tmp);
                site_write(env, flags, ratio);
                break;
            }
            case HPROF_CMD_HEAP_SUMMARY: {
                rawMonitorEnter(gdata->data_access_lock); {
                    io_write_heap_summary(  gdata->total_live_bytes,
                                            gdata->total_live_instances,
                                            gdata->total_alloced_bytes,
                                            gdata->total_alloced_instances);
                } rawMonitorExit(gdata->data_access_lock);
                break;
            }
            case HPROF_CMD_EXIT:
                keep_processing = JNI_FALSE;
                kill_the_whole_process = JNI_TRUE;
                verbose_message("HPROF: received exit event, exiting ...\n");
                break;
            case HPROF_CMD_DUMP_TRACES:
                rawMonitorEnter(gdata->data_access_lock); {
                    trace_output_unmarked(env);
                } rawMonitorExit(gdata->data_access_lock);
                break;
            case HPROF_CMD_CPU_SAMPLES: {
                unsigned i_tmp;
                float ratio;

                /* flags not used */
                (void)recv_u2();
                i_tmp = recv_u4();
                ratio = *(float *)(&i_tmp);
                trace_output_cost(env, ratio);
                break;
            }
            case HPROF_CMD_CONTROL: {
                unsigned short cmd = recv_u2();
                if (cmd == 0x0001) {
                    setEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_OBJECT_FREE, NULL);
                    tracker_engage(env);
                } else if (cmd == 0x0002) {
                    setEventNotificationMode(JVMTI_DISABLE, JVMTI_EVENT_OBJECT_FREE, NULL);
                    tracker_disengage(env);
                } else if (cmd == 0x0003) {
                    ObjectIndex thread_object_index;
                    thread_object_index = recv_id();
                    cpu_sample_on(env, thread_object_index);
                } else if (cmd == 0x0004) {
                    ObjectIndex thread_object_index;
                    thread_object_index = recv_id();
                    cpu_sample_off(env, thread_object_index);
                } else if (cmd == 0x0005) {
                    rawMonitorEnter(gdata->data_access_lock); {
                        trace_clear_cost();
                    } rawMonitorExit(gdata->data_access_lock);
                } else if (cmd == 0x0006) {
                    rawMonitorEnter(gdata->data_access_lock); {
                        site_cleanup();
                        site_init();
                    } rawMonitorExit(gdata->data_access_lock);
                } else if (cmd == 0x0007) {
                    gdata->max_trace_depth = recv_u2();
                }
                break;
            }
            default:{
                char buf[80];

                keep_processing = JNI_FALSE;
                kill_the_whole_process = JNI_TRUE;
                (void)md_snprintf(buf, sizeof(buf),
                        "failed to recognize cmd %d, exiting..", (int)tag);
                buf[sizeof(buf)-1] = 0;
                HPROF_ERROR(JNI_FALSE, buf);
                break;
            }
        }

        rawMonitorEnter(gdata->data_access_lock); {
            io_flush();
        } rawMonitorExit(gdata->data_access_lock);

        rawMonitorEnter(gdata->listener_loop_lock); {
            if ( !gdata->listener_loop_running ) {
                keep_processing         = JNI_FALSE;
            }
        } rawMonitorExit(gdata->listener_loop_lock);

    }

    /* If listener_term() is causing this loop to terminate, then
     *   you will block here until listener_term wants you to proceed.
     */
    rawMonitorEnter(gdata->listener_loop_lock); {
        if ( gdata->listener_loop_running ) {
            /* We are terminating for our own reasons, maybe because of
             *   EOF (socket closed?), or EXIT request, or invalid command.
             *   Not from listener_term().
             *   We set gdata->listener_loop_running=FALSE so that any
             *   future call to listener_term() will do nothing.
             */
            gdata->listener_loop_running = JNI_FALSE;
        } else {
            /* We assume that listener_term() is stopping us,
             *    now we need to tell it we understood.
             */
            rawMonitorNotifyAll(gdata->listener_loop_lock);
        }
    } rawMonitorExit(gdata->listener_loop_lock);

    LOG3("listener_loop", "finished command = ", tag);

    /* If we got an explicit command request to die, die here */
    if ( kill_the_whole_process ) {
        error_exit_process(0);
    }

}

/* External functions */

void
listener_init(JNIEnv *env)
{
    /* Create the raw monitor */
    gdata->listener_loop_lock = createRawMonitor("HPROF listener lock");

    rawMonitorEnter(gdata->listener_loop_lock); {
        createAgentThread(env, "HPROF listener thread",
                                &listener_loop_function);
        /* Wait for listener_loop_function() to tell us it started. */
        rawMonitorWait(gdata->listener_loop_lock, 0);
    } rawMonitorExit(gdata->listener_loop_lock);
}

void
listener_term(JNIEnv *env)
{
    rawMonitorEnter(gdata->listener_loop_lock); {

        /* If we are in the middle of sending bytes down the socket, this
         *   at least keeps us blocked until that processing is done.
         */
        rawMonitorEnter(gdata->data_access_lock); {

            /* Make sure the socket gets everything */
            io_flush();

            /*
             * Graceful shutdown of the socket will assure that all data
             * sent is received before the socket close completes.
             */
            (void)md_shutdown(gdata->fd, 2 /* disallow sends and receives */);

            /* This close will cause the listener loop to possibly wake up
             *    from the recv_u1(), this is critical to get thread running again.
             */
            md_close(gdata->fd);
        } rawMonitorExit(gdata->data_access_lock);

        /* It could have shut itself down, so we check the global flag */
        if ( gdata->listener_loop_running ) {
            /* It stopped because of something listener_term() did. */
            gdata->listener_loop_running = JNI_FALSE;
            /* Wait for listener_loop_function() to tell us it finished. */
            rawMonitorWait(gdata->listener_loop_lock, 0);
        }
    } rawMonitorExit(gdata->listener_loop_lock);
}