id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
754,985
|
RendererHUDNeo.h
|
dridri_bcflight/libhud/RendererHUDNeo.h
|
/*
* BCFlight
* Copyright (C) 2016 Adrien Aubry (drich)
*
* 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 <http://www.gnu.org/licenses/>.
**/
#ifndef RENDERERHUDNEO_H
#define RENDERERHUDNEO_H
#include <string>
#include "RendererHUD.h"
#include <Controller.h>
class RendererHUDNeo : public RendererHUD
{
public:
RendererHUDNeo( int width, int height, float ratio, uint32_t fontsize = 28, Vector4i render_region = Vector4i( 10, 10, 20, 20 ), bool barrel_correction = true );
~RendererHUDNeo();
void Compute();
void Render( DroneStats* dronestats, float localVoltage, VideoStats* videostats, LinkStats* iwstats );
void RenderThrustAcceleration( float thrust, float acceleration );
void RenderLink( float quality, float level );
void RenderBattery( float level );
void RenderAttitude( const Vector3f& rpy );
protected:
Vector3f mSmoothRPY;
Shader mShader;
Shader mColorShader;
uint32_t mThrustVBO;
uint32_t mAccelerationVBO;
uint32_t mLinkVBO;
uint32_t mBatteryVBO;
uint32_t mLineVBO;
uint32_t mCircleVBO;
uint32_t mStaticLinesVBO;
uint32_t mStaticLinesCount;
uint32_t mStaticLinesCountNoAttitude;
float mSpeedometerSize;
Texture* mIconNight;
Texture* mIconPhoto;
};
#endif // RENDERERHUDNEO_H
| 1,797
|
C++
|
.h
| 51
| 33.196078
| 162
| 0.78143
|
dridri/bcflight
| 131
| 22
| 8
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,986
|
RendererHUD.h
|
dridri_bcflight/libhud/RendererHUD.h
|
/*
* BCFlight
* Copyright (C) 2016 Adrien Aubry (drich)
*
* 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 <http://www.gnu.org/licenses/>.
**/
#ifndef RENDERERHUD_H
#define RENDERERHUD_H
#include <GLES2/gl2.h>
#include <vector>
#include <string>
#include <cstring>
#include "Vector.h"
#include "Matrix.h"
class Controller;
typedef struct VideoStats {
VideoStats(int w = 0, int h = 0, int f = 0, uint32_t p = 0, const std::string& wb = "", const std::string& e = "")
: width(w)
, height(h)
, fps(f)
, photo_id(p)
, vtxPower( -1 )
, vtxPowerDbm( -1 )
, vtxFrequency( 0 )
, vtxChannel( 0 )
{
strncpy( whitebalance, wb.c_str(), 32 );
strncpy( exposure, e.c_str(), 32 );
memset( vtxBand, 0, sizeof(vtxBand) );
}
int width;
int height;
int fps;
uint32_t photo_id;
char whitebalance[32];
char exposure[32];
int8_t vtxPower;
int8_t vtxPowerDbm;
uint16_t vtxFrequency;
uint8_t vtxChannel;
char vtxBand[16];
} VideoStats;
typedef struct LinkStats {
LinkStats()
: qual(0)
, level(0)
, noise(0)
, channel(0)
, source(0)
{}
int qual;
int level;
int noise;
int channel;
char source;
} LinkStats;
typedef enum {
Rate = 0,
Stabilize = 1,
ReturnToHome = 2,
Follow = 3,
} DroneMode;
typedef struct DroneStats {
DroneStats()
: armed(false)
, mode(DroneMode::Rate)
, ping(0)
, blackBoxId(0)
, cpuUsage(0)
, memUsage(0)
, thrust(0)
, acceleration(0)
, rpy(Vector3f())
, batteryLevel(0)
, batteryVoltage(0)
, batteryTotalCurrent(0)
{}
// Status
bool armed;
DroneMode mode;
uint32_t ping;
uint32_t blackBoxId;
// CPU
uint32_t cpuUsage;
uint32_t memUsage;
// Attitude
float thrust;
float acceleration;
Vector3f rpy;
Vector3f gpsLocation;
float gpsSpeed;
uint32_t gpsSatellitesSeen;
uint32_t gpsSatellitesUsed;
// Battery
float batteryLevel;
float batteryVoltage;
uint32_t batteryTotalCurrent;
// Other
std::string username;
std::vector< std::string > messages;
} DroneStats;
class RendererHUD
{
public:
typedef enum {
START = 0,
CENTER = 1,
END = 2,
} TextAlignment;
// render_region is top,bottom,left,right
RendererHUD( int width, int height, float ratio, uint32_t fontsize, Vector4i render_region = Vector4i( 10, 10, 20, 20 ), bool barrel_correction = true );
virtual ~RendererHUD();
virtual void Compute() = 0;
virtual void Render( DroneStats* dronestats, float localVoltage, VideoStats* videostats, LinkStats* iwstats ) = 0;
void RenderQuadTexture( GLuint textureID, int x, int y, int width, int height, bool hmirror = false, bool vmirror = false, const Vector4f& color = { 1.0f, 1.0f, 1.0f, 1.0f } );
void RenderText( int x, int y, const std::string& text, uint32_t color, float size = 1.0f, TextAlignment halign = TextAlignment::START, TextAlignment valign = TextAlignment::START );
void RenderText( int x, int y, const std::string& text, const Vector4f& color, float size = 1.0f, TextAlignment halign = TextAlignment::START, TextAlignment valign = TextAlignment::START );
void RenderImage( int x, int y, int width, int height, uintptr_t img );
Vector2f VR_Distort( const Vector2f& coords );
void PreRender();
void setNightMode( bool m ) { mNightMode = m; }
void setStereo( bool en ) { mStereo = en; if ( not mStereo ) { m3DStrength = 0.0f; } }
void set3DStrength( float strength ) { m3DStrength = strength; }
uintptr_t LoadImage( const std::string& path ) { return reinterpret_cast<uintptr_t>( LoadTexture(path) ); };
bool nightMode() { return mNightMode; }
protected:
typedef struct {
float u, v;
float x, y;
} FastVertex;
typedef struct {
float u, v;
uint32_t color;
float x, y;
} FastVertexColor;
typedef struct {
uint32_t mShader;
uint32_t mVertexShader;
uint32_t mFragmentShader;
uint32_t mVertexTexcoordID;
uint32_t mVertexColorID;
uint32_t mVertexPositionID;
uint32_t mMatrixProjectionID;
uint32_t mDistorID;
uint32_t mOffsetID;
uint32_t mScaleID;
uint32_t mColorID;
} Shader;
typedef struct {
uint32_t width;
uint32_t height;
uint32_t* data;
uint32_t glID;
} Texture;
int LoadVertexShader( RendererHUD::Shader* target, const void* data, size_t size );
int LoadFragmentShader( RendererHUD::Shader* target, const void* data, size_t size );
void createPipeline( Shader* target );
Texture* LoadTexture( const std::string& filename );
Texture* LoadTexture( const uint8_t* data, uint32_t datalen );
void LoadPNG( Texture* tex, std::istream& filename );
void FontMeasureString( const std::string& str, int* width, int* height );
int32_t CharacterWidth( Texture* tex, unsigned char c );
int32_t CharacterHeight( Texture* tex, unsigned char c );
int32_t CharacterYOffset( Texture* tex, unsigned char c );
void DrawArrays( RendererHUD::Shader& shader, int mode, uint32_t ofs, uint32_t count, const Vector2f& offset = Vector2f() );
uint32_t mDisplayWidth;
uint32_t mDisplayHeight;
uint32_t mWidth;
uint32_t mHeight;
uint32_t mBorderTop;
uint32_t mBorderBottom;
uint32_t mBorderLeft;
uint32_t mBorderRight;
bool mStereo;
bool mNightMode;
bool mBarrelCorrection;
float m3DStrength;
bool mBlinkingViews;
float mHUDTick;
Matrix* mMatrixProjection;
uint32_t mQuadVBO;
Shader mFlatShader;
uint32_t mExposureID;
uint32_t mGammaID;
Texture* mFontTexture;
uint32_t mFontSize;
uint32_t mFontHeight;
Shader mTextShader;
uint32_t mTextVBO;
int mTextAdv[256];
std::string mWhiteBalance;
std::string mExposureMode;
float mWhiteBalanceTick;
uint32_t mLastPhotoID;
float mPhotoTick;
};
#endif // RENDERERHUD_H
| 6,097
|
C++
|
.h
| 208
| 27.019231
| 190
| 0.73721
|
dridri/bcflight
| 131
| 22
| 8
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
754,988
|
jvmSockCmd-test.cpp
|
HeapStats_heapstats/agent/test/gtest/src/jvmSockCmd-test.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <gtest/gtest.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <heapstats-engines/jvmSockCmd.hpp>
#include "run-libjvm.hpp"
#define RESULT_FILE "results/jvmsockcmd-results.txt"
class JVMSockCmdTest : public RunLibJVMTest{};
TEST_F(JVMSockCmdTest, runAttachListener){
char *tmpdir = GetSystemProperty("java.io.tmpdir");
TJVMSockCmd jvmCmd(tmpdir);
free(tmpdir);
ASSERT_EQ(jvmCmd.exec("properties", RESULT_FILE), 0);
struct stat buf;
int ret = stat(RESULT_FILE, &buf);
ASSERT_EQ(ret, 0);
ASSERT_TRUE(S_ISREG(buf.st_mode));
}
| 1,403
|
C++
|
.cpp
| 37
| 35.756757
| 82
| 0.758112
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,989
|
jvmInfo-test.cpp
|
HeapStats_heapstats/agent/test/gtest/src/jvmInfo-test.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <jvmti.h>
#include <gtest/gtest.h>
#include <heapstats-engines/jvmInfo.hpp>
#include "run-libjvm.hpp"
class JvmInfoTest : public RunLibJVMTest{
private:
static jvmtiEnv *jvmti;
protected:
static TJvmInfo info;
static void SetUpTestCase();
};
jvmtiEnv *JvmInfoTest::jvmti;
TJvmInfo JvmInfoTest::info;
void JvmInfoTest::SetUpTestCase(){
RunLibJVMTest::SetUpTestCase();
JavaVM *vm;
JNIEnv *env;
GetJVM(&vm, &env);
vm->GetEnv((void **)&jvmti, JVMTI_VERSION_1);
info.setHSVersion(jvmti);
info.detectInfoAddress(env);
info.detectDelayInfoAddress();
vm->DetachCurrentThread();
}
TEST_F(JvmInfoTest, GetMaxMemory){
JavaVM *vm;
JNIEnv *env;
GetJVM(&vm, &env);
ASSERT_NE(info.getMaxMemory(), -1);
vm->DetachCurrentThread();
}
TEST_F(JvmInfoTest, GetTotalMemory){
JavaVM *vm;
JNIEnv *env;
GetJVM(&vm, &env);
ASSERT_NE(info.getTotalMemory(), -1);
vm->DetachCurrentThread();
}
TEST_F(JvmInfoTest, GetNewAreaSize){
ASSERT_NE(info.getNewAreaSize(), -1);
}
TEST_F(JvmInfoTest, GetOldAreaSize){
ASSERT_NE(info.getOldAreaSize(), -1);
}
TEST_F(JvmInfoTest, GetMetaspaceUsage){
ASSERT_NE(info.getMetaspaceUsage(), -1);
}
TEST_F(JvmInfoTest, GetMetaspaceCapacity){
ASSERT_NE(info.getMetaspaceCapacity(), -1);
}
TEST_F(JvmInfoTest, GetFGCCount){
ASSERT_NE(info.getFGCCount(), -1);
}
TEST_F(JvmInfoTest, GetYGCCount){
ASSERT_NE(info.getYGCCount(), -1);
}
TEST_F(JvmInfoTest, GetGCCause){
ASSERT_STRNE(info.getGCCause(), NULL);
}
TEST_F(JvmInfoTest, GetGCWorktime){
info.getGCWorktime();
}
TEST_F(JvmInfoTest, GetSyncPark){
ASSERT_NE(info.getSyncPark(), -1);
}
TEST_F(JvmInfoTest, GetThreadLive){
ASSERT_NE(info.getThreadLive(), -1);
}
TEST_F(JvmInfoTest, GetSafepointTime){
ASSERT_NE(info.getSafepointTime(), -1);
}
TEST_F(JvmInfoTest, GetSafepoints){
ASSERT_NE(info.getSafepoints(), -1);
}
TEST_F(JvmInfoTest, GetVmVersion){
ASSERT_STREQ(info.getVmVersion(), GetSystemProperty("java.vm.version"));
}
TEST_F(JvmInfoTest, GetVmName){
ASSERT_STREQ(info.getVmName(), GetSystemProperty("java.vm.name"));
}
TEST_F(JvmInfoTest, GetClassPath){
ASSERT_STREQ(info.getClassPath(), GetSystemProperty("java.class.path"));
}
TEST_F(JvmInfoTest, GetEndorsedPath){
ASSERT_STREQ(info.getEndorsedPath(), GetSystemProperty("java.endorsed.dirs"));
}
TEST_F(JvmInfoTest, GetJavaVersion){
ASSERT_STREQ(info.getJavaVersion(), GetSystemProperty("java.version"));
}
TEST_F(JvmInfoTest, GetBootClassPath){
ASSERT_STREQ(info.getBootClassPath(),
GetSystemProperty("sun.boot.class.path"));
}
TEST_F(JvmInfoTest, GetVmArgs){
ASSERT_STRNE(info.getVmArgs(), NULL);
}
TEST_F(JvmInfoTest, GetVmFlags){
ASSERT_STRNE(info.getVmFlags(), NULL);
}
TEST_F(JvmInfoTest, GetJavaCommand){
ASSERT_STRNE(info.getJavaCommand(), NULL);
}
TEST_F(JvmInfoTest, GetTickTime){
ASSERT_NE(info.getTickTime(), -1);
}
TEST_F(JvmInfoTest, LoadGCCause){
info.loadGCCause();
}
| 3,758
|
C++
|
.cpp
| 126
| 27.460317
| 82
| 0.753341
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,990
|
fsUtil-test.cpp
|
HeapStats_heapstats/agent/test/gtest/src/fsUtil-test.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <gtest/gtest.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>
#include <openssl/md5.h>
#include <errno.h>
#include <stdlib.h>
#include <heapstats-engines/globals.hpp>
#include <heapstats-engines/fsUtil.hpp>
#define RESULT_DIR "results"
#define COPY_SRC "heapstats-test"
class FSUtilTest : public testing::Test{
protected:
bool GetMD5(const char *fname, unsigned char *md){
int fd = open(fname, O_RDONLY);
if(fd == -1){
return false;
}
struct stat st;
fstat(fd, &st);
void *data = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
MD5_CTX c;
MD5_Init(&c);
MD5_Update(&c, data, st.st_size);
MD5_Final(md, &c);
munmap(data, st.st_size);
close(fd);
return true;
}
};
TEST_F(FSUtilTest, copyFile){
ASSERT_EQ(copyFile(COPY_SRC, RESULT_DIR), 0);
unsigned char src_md5[MD5_DIGEST_LENGTH];
unsigned char dst_md5[MD5_DIGEST_LENGTH];
GetMD5(COPY_SRC, src_md5);
ASSERT_TRUE(GetMD5(RESULT_DIR "/" COPY_SRC, dst_md5));
ASSERT_EQ(0, memcmp(src_md5, dst_md5, MD5_DIGEST_LENGTH));
}
TEST_F(FSUtilTest, copyFileWithRename){
ASSERT_EQ(0, copyFile(COPY_SRC, RESULT_DIR, "renamed_copy"));
unsigned char src_md5[MD5_DIGEST_LENGTH];
unsigned char dst_md5[MD5_DIGEST_LENGTH];
GetMD5(COPY_SRC, src_md5);
ASSERT_TRUE(GetMD5(RESULT_DIR "/renamed_copy", dst_md5));
ASSERT_EQ(0, memcmp(src_md5, dst_md5, MD5_DIGEST_LENGTH));
}
TEST_F(FSUtilTest, tempDir){
char *tmp = NULL;
ASSERT_EQ(0, createTempDir(&tmp, "heapstats-test-tmp"));
ASSERT_FALSE(tmp == NULL);
struct stat st;
ASSERT_EQ(0, stat(tmp, &st));
ASSERT_TRUE(S_ISDIR(st.st_mode));
removeTempDir(tmp);
errno = 0;
stat(tmp, &st);
ASSERT_EQ(errno, ENOENT);
free(tmp);
}
TEST_F(FSUtilTest, getParentDirectoryPath){
char *result;
result = getParentDirectoryPath("test");
ASSERT_STREQ("./", result);
free(result);
result = getParentDirectoryPath("/test");
ASSERT_STREQ("/", result);
free(result);
result = getParentDirectoryPath("./test");
ASSERT_STREQ(".", result);
free(result);
result = getParentDirectoryPath("./path/to/file");
ASSERT_STREQ("./path/to", result);
free(result);
result = getParentDirectoryPath("/path/to/file");
ASSERT_STREQ("/path/to", result);
free(result);
result = getParentDirectoryPath("path/to/file");
ASSERT_STREQ("path/to", result);
free(result);
}
TEST_F(FSUtilTest, isAccessibleDirectory){
const char *dirname = RESULT_DIR "/access_test";
mkdir(dirname, S_IRUSR | S_IWUSR);
ASSERT_EQ(0, isAccessibleDirectory(dirname, true, true));
ASSERT_EQ(0, isAccessibleDirectory(dirname, true, false));
ASSERT_EQ(0, isAccessibleDirectory(dirname, false, true));
chmod(dirname, S_IRUSR);
ASSERT_NE(0, isAccessibleDirectory(dirname, true, true));
ASSERT_EQ(0, isAccessibleDirectory(dirname, true, false));
ASSERT_NE(0, isAccessibleDirectory(dirname, false, true));
chmod(dirname, S_IWUSR);
ASSERT_NE(0, isAccessibleDirectory(dirname, true, true));
ASSERT_NE(0, isAccessibleDirectory(dirname, true, false));
ASSERT_EQ(0, isAccessibleDirectory(dirname, false, true));
rmdir(dirname);
}
TEST_F(FSUtilTest, isValidPath){
ASSERT_TRUE(isValidPath("./"));
ASSERT_TRUE(isValidPath(COPY_SRC));
ASSERT_FALSE(isValidPath("./does/not/exist"));
}
TEST_F(FSUtilTest, checkDiskFull){
ASSERT_TRUE(checkDiskFull(ENOSPC, "testcase"));
ASSERT_FALSE(checkDiskFull(0, "testcase"));
}
| 4,352
|
C++
|
.cpp
| 126
| 31.34127
| 82
| 0.714627
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,992
|
heapstats-test.cpp
|
HeapStats_heapstats/agent/test/gtest/src/heapstats-test.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <dlfcn.h>
#include <gtest/gtest.h>
#include <heapstats.hpp>
/* This function will be called from heapstats.cpp . */
void *loadHeapStatsEngine(){
return dlopen("stub/libdummyJVMTI.so", RTLD_LAZY);
}
TEST(HeapStatsTest, Agent_OnLoad){
ASSERT_EQ(Agent_OnLoad(NULL, NULL, NULL), JNI_OK);
}
TEST(HeapStatsTest, Agent_OnUnload){
Agent_OnUnload(NULL);
}
TEST(HeapStatsTest, Agent_OnAttach){
ASSERT_EQ(Agent_OnAttach(NULL, NULL, NULL), JNI_OK);
}
| 1,261
|
C++
|
.cpp
| 34
| 35.147059
| 82
| 0.759016
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,993
|
heapstats-md-test.cpp
|
HeapStats_heapstats/agent/test/gtest/src/heapstats-md-test.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <dlfcn.h>
#include <gtest/gtest.h>
#include <heapstats_md.hpp>
class HeapStatsMDTest : public testing::Test {};
TEST_F(HeapStatsMDTest, loadHeapStatsEngine){
void *hHandle = loadHeapStatsEngine();
ASSERT_TRUE(hHandle != NULL);
if(hHandle != NULL){
dlclose(hHandle);
}
}
| 1,097
|
C++
|
.cpp
| 29
| 35.551724
| 82
| 0.75566
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,994
|
heapStatsEnvironment.cpp
|
HeapStats_heapstats/agent/test/gtest/src/heapStatsEnvironment.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <gtest/gtest.h>
#include <jni.h>
#include <heapstats-engines/globals.hpp>
#include "heapStatsEnvironment.hpp"
#define CLASSPATH "./stub"
void HeapStatsEnvironment::SetUp(){
logger = new TLogger();
JavaVMInitArgs args;
args.version = JNI_VERSION_1_6;
JNI_GetDefaultJavaVMInitArgs(&args);
JavaVMOption opt;
opt.optionString = (char *)"-Djava.class.path=" CLASSPATH;
args.nOptions = 1;
args.options = &opt;
JavaVM *vm;
JNIEnv *env;
if(JNI_CreateJavaVM(&vm, (void **)&env, &args) != JNI_OK){
throw "Could not create JavaVM";
}
}
void HeapStatsEnvironment::TearDown(){
JavaVM *vm;
jsize numVMs;
if(JNI_GetCreatedJavaVMs(&vm, 1, &numVMs) == JNI_OK){
vm->DestroyJavaVM();
}
}
| 1,530
|
C++
|
.cpp
| 45
| 31.422222
| 82
| 0.738273
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,995
|
symbolFinder-test.cpp
|
HeapStats_heapstats/agent/test/gtest/src/symbolFinder-test.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <dlfcn.h>
#include <gtest/gtest.h>
#include <heapstats-engines/symbolFinder.hpp>
#define LIBJVM_PATH_PATTERN "/usr/lib/jvm/java-"
#define LIBJVM_NAME "libjvm.so"
#define FIND_SYMBOL "JNI_CreateJavaVM"
class SymbolFinderTest : public testing::Test{};
TEST_F(SymbolFinderTest, findSymbol){
TSymbolFinder symFinder;
ASSERT_TRUE(symFinder.loadLibrary(LIBJVM_PATH_PATTERN, LIBJVM_NAME));
void *fromSymFinder = symFinder.findSymbol(FIND_SYMBOL);
void *fromDlsym = dlsym(RTLD_DEFAULT, FIND_SYMBOL);
ASSERT_TRUE(fromSymFinder == fromDlsym);
}
| 1,360
|
C++
|
.cpp
| 32
| 40.40625
| 82
| 0.772727
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,996
|
run-libjvm.cpp
|
HeapStats_heapstats/agent/test/gtest/src/run-libjvm.cpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <pthread.h>
#include <string.h>
#include <jni.h>
#include "run-libjvm.hpp"
pthread_t RunLibJVMTest::java_driver;
void RunLibJVMTest::GetJVM(JavaVM **vm, JNIEnv **env){
jsize numVMs;
if(JNI_GetCreatedJavaVMs(vm, 1, &numVMs) != JNI_OK){
throw "Could not get JavaVMs.";
}
if(numVMs < 1){
throw "Could not get JavaVMs.";
}
(*vm)->AttachCurrentThread((void **)env, NULL);
}
void *RunLibJVMTest::java_driver_main(void *data){
JavaVM *vm;
JNIEnv *env;
GetJVM(&vm, &env);
jclass LongSleepClass = env->FindClass("LongSleep");
if(LongSleepClass == NULL){
throw "Could not find LongSleep class.";
}
jmethodID mainMethod = env->GetStaticMethodID(LongSleepClass, "main",
"([Ljava/lang/String;)V");
if(mainMethod == NULL){
throw "Could not find LongSleep#main() .";
}
env->CallStaticVoidMethod(LongSleepClass, mainMethod, NULL);
vm->DetachCurrentThread();
return NULL;
}
void RunLibJVMTest::SetUpTestCase(){
java_driver = 0;
if(pthread_create(&java_driver, NULL, &java_driver_main, NULL) != 0){
throw "Could not create Java driver thread!";
}
}
void RunLibJVMTest::TearDownTestCase(){
JavaVM *vm;
JNIEnv *env;
GetJVM(&vm, &env);
if(java_driver != 0){
jclass LongSleepClass = env->FindClass("LongSleep");
jfieldID lockObjField = env->GetStaticFieldID(LongSleepClass,
"lock", "Ljava/lang/Object;");
if(lockObjField == NULL){
throw "Could not find LongSleep#lock .";
}
jobject lockObj = env->GetStaticObjectField(
LongSleepClass, lockObjField);
if(lockObj == NULL){
throw "Could not find lock object.";
}
jclass objClass = env->FindClass("java/lang/Object");
jmethodID notifyMethod = env->GetMethodID(objClass, "notifyAll", "()V");
env->MonitorEnter(lockObj);
env->CallVoidMethod(lockObj, notifyMethod);
env->MonitorExit(lockObj);
if(env->ExceptionOccurred()){
env->ExceptionDescribe();
env->ExceptionClear();
}
pthread_join(java_driver, NULL);
}
if(vm != NULL){
vm->DetachCurrentThread();
}
}
char *RunLibJVMTest::GetSystemProperty(const char *key){
JavaVM *vm;
JNIEnv *env;
GetJVM(&vm, &env);
jstring key_str = env->NewStringUTF(key);
jclass sysClass = env->FindClass("Ljava/lang/System;");
jmethodID getProperty = env->GetStaticMethodID(sysClass,
"getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
jstring value = (jstring)env->CallStaticObjectMethod(sysClass,
getProperty, key_str);
const char *ret_utf8 = env->GetStringUTFChars(value, NULL);
char *ret = strdup(ret_utf8);
env->ReleaseStringUTFChars(value, ret_utf8);
vm->DetachCurrentThread();
return ret;
}
| 3,698
|
C++
|
.cpp
| 103
| 30.485437
| 82
| 0.673492
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,998
|
heapstats.cpp
|
HeapStats_heapstats/agent/src/heapstats.cpp
|
/*!
* \file heapstats.cpp
* \brief Proxy library for HeapStats backend.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <jni.h>
#include <jvmti.h>
#include <link.h>
#include <libgen.h>
#include <stdio.h>
#include <dlfcn.h>
#include <limits.h>
#include <stddef.h>
#include <string.h>
#include "heapstats.hpp"
#include "heapstats_md.hpp"
/*!
* \brief Handle of HeapStats engine.
*/
static void *hEngine = NULL;
/*!
* \brief Agent attach entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Attach initialization result code.
*/
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) {
hEngine = loadHeapStatsEngine();
if (hEngine == NULL) {
return JNI_ERR;
}
TAgentOnLoadFunc onLoad = (TAgentOnLoadFunc)dlsym(hEngine, "Agent_OnLoad");
if (onLoad == NULL) {
fprintf(stderr, "Could not get Agent_OnLoad() from backend library.\n");
dlclose(hEngine);
return JNI_ERR;
}
return onLoad(vm, options, reserved);
}
/*!
* \brief Common agent unload entry points.
* \param vm [in] JavaVM object.
*/
JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) {
TAgentOnUnloadFunc onUnload =
(TAgentOnUnloadFunc)dlsym(hEngine, "Agent_OnUnload");
if (onUnload == NULL) {
fprintf(stderr, "Could not get Agent_OnUnload() from backend library.\n");
} else {
onUnload(vm);
}
dlclose(hEngine);
}
/*!
* \brief Ondemand attach's entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Ondemand-attach initialization result code.
*/
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM *vm, char *options, void *reserved) {
hEngine = loadHeapStatsEngine();
if (hEngine == NULL) {
return JNI_ERR;
}
TAgentOnAttachFunc onAttach =
(TAgentOnAttachFunc)dlsym(hEngine, "Agent_OnAttach");
if (onAttach == NULL) {
fprintf(stderr, "Could not get Agent_OnAttach() from backend library.\n");
dlclose(hEngine);
return JNI_ERR;
}
return onAttach(vm, options, reserved);
}
| 2,916
|
C++
|
.cpp
| 94
| 28.510638
| 82
| 0.721708
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
754,999
|
symbolFinder.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/symbolFinder.cpp
|
/*!
* \file symbolFinder.cpp
* \brief This file is used by search symbol in library.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <limits.h>
#include <link.h>
#include "globals.hpp"
#include "symbolFinder.hpp"
/*!
* \brief Flag of BFD libarary is already initialized.
*/
bool TSymbolFinder::initFlag = false;
/*!
* \brief Create record stored library information.
* \param libinfo [out] Record of library information.
* \param libPath [in] Part of target library path.
* \param libName [in] Target library name.
*/
inline void createLibInfo(TLibraryInfo *libinfo, const char *libPath,
const char *libName) {
libinfo->libpath_len = strlen(libPath);
libinfo->libpath = strdup(libPath);
if (unlikely(libinfo->libpath == NULL)) {
return;
}
libinfo->libname = strdup(libName);
libinfo->libname_len = strlen(libName);
if (unlikely(libinfo->libname == NULL)) {
free(libinfo->libpath);
libinfo->libpath = NULL;
return;
}
}
/*!
* \brief Callback function of dl_iterate_phdr(3).
* \param info [in] Information of loaded library on memory.
* \param size [in] Size of library area on memory.
* \param data [in] User data.
* \return Continues callback loop if value is 0.<br>
* Abort callback loop if value is 1.
*/
static int libraryCallback(struct dl_phdr_info *info, size_t size, void *data) {
TLibraryInfo *libinfo = (TLibraryInfo *)data;
/*
* Get real path of library.
* "sun.boot.library.path" system property for libjvm.so will be set real
* path.
* See os::jvm_path() in hotspot/src/os/linux/vm/os_linux.cpp
*/
char real_path[PATH_MAX];
realpath(info->dlpi_name, real_path);
/* If library is need. */
if ((strncmp(real_path, libinfo->libpath, libinfo->libpath_len) == 0) &&
(strncmp(basename(real_path), libinfo->libname, libinfo->libname_len) ==
0)) {
/* Store library information. */
libinfo->realpath = strdup(real_path);
libinfo->baseaddr = info->dlpi_addr;
/* Abort callback loop. */
return 1;
}
return 0;
}
/*!
* \brief TSymbolFinder constructor.
*/
TSymbolFinder::TSymbolFinder(void) {
if (unlikely(!initFlag)) {
initFlag = true;
/* Global initialize. */
bfd_init();
}
/* Zero clear records. */
memset(&libBfdInfo, 0, sizeof(libBfdInfo));
memset(&debugBfdInfo, 0, sizeof(debugBfdInfo));
memset(&targetLibInfo, 0, sizeof(targetLibInfo));
}
/*!
* \brief TSymbolFinder destructor.
*/
TSymbolFinder::~TSymbolFinder() {
/* Cleanup. */
this->clear();
}
/*!
* \brief Load target libaray.
* \param pathPattern [in] Pattern of target library path.
* \param libname [in] Name of library.
* \return Is success load library.<br>
*/
bool TSymbolFinder::loadLibrary(const char *pathPattern, const char *libname) {
/* Sanity check. */
if (unlikely(pathPattern == NULL)) {
logger->printWarnMsg("Library path is not set.");
return false;
}
if (unlikely(libname == NULL)) {
logger->printWarnMsg("Library name is not set.");
return false;
}
/* Initialize. */
createLibInfo(&targetLibInfo, pathPattern, libname);
targetLibInfo.realpath = NULL;
targetLibInfo.baseaddr = ((ptrdiff_t)0);
/* If failure allocate memory. */
if (unlikely((targetLibInfo.libpath == NULL) ||
(targetLibInfo.libname == NULL))) {
logger->printWarnMsg("Cannot allocate memory for searching symbols.");
return false;
}
/* Search target library on memory. */
if (unlikely(dl_iterate_phdr(&libraryCallback, &targetLibInfo) == 0)) {
logger->printWarnMsg("Cannot find library: %s", libname);
free(targetLibInfo.libname);
targetLibInfo.libname = NULL;
free(targetLibInfo.libpath);
targetLibInfo.libpath = NULL;
return false;
}
/* Load library with bfd record. */
loadLibraryInfo(targetLibInfo.realpath, &libBfdInfo);
/* If bfd record has the symbols, no need to search debuginfo */
if (libBfdInfo.hasSymtab && libBfdInfo.staticSymCnt > 0 &&
libBfdInfo.dynSymCnt > 0) {
return true;
}
char dbgInfoPath[PATH_MAX];
dbgInfoPath[0] = '\0';
/* Try to get debuginfo path from .note.gnu.build-id */
asection *buid_id_section =
bfd_get_section_by_name(libBfdInfo.bfdInfo, ".note.gnu.build-id");
if (buid_id_section != NULL) {
TBuildIdInfo *buildID;
if (bfd_malloc_and_get_section(libBfdInfo.bfdInfo, buid_id_section,
(bfd_byte **)&buildID)) {
sprintf(dbgInfoPath, DEBUGINFO_DIR "/.build-id/%02hhx/",
*(&(buildID->contents) + buildID->name_size));
for (unsigned int Cnt = buildID->name_size + 1;
Cnt < buildID->name_size + buildID->hash_size; Cnt++) {
char digitChars[3];
sprintf(digitChars, "%02hhx", *(&(buildID->contents) + Cnt));
strcat(dbgInfoPath, digitChars);
}
strcat(dbgInfoPath, DEBUGINFO_SUFFIX);
}
if (buildID != NULL) {
free(buildID);
}
}
if (dbgInfoPath[0] == '\0') {
/* Try to get debuginfo path from .gnu_debuglink */
char *buf = bfd_follow_gnu_debuglink(libBfdInfo.bfdInfo, DEBUGINFO_DIR);
if (buf != NULL) {
strcpy(dbgInfoPath, buf);
free(buf);
}
}
if (dbgInfoPath[0] != '\0') {
/* Load library's debuginfo with bfd record. */
struct stat st = {0};
if (unlikely(stat(&(dbgInfoPath[0]), &st) != 0)) {
logger->printWarnMsg("Cannot read debuginfo from %s", dbgInfoPath);
} else {
logger->printDebugMsg("Try to read debuginfo from %s", dbgInfoPath);
loadLibraryInfo(dbgInfoPath, &debugBfdInfo);
}
} else {
logger->printDebugMsg("The same version of debuginfo not found: %s",
libBfdInfo.bfdInfo->filename);
}
/* If failure both load process. */
if (unlikely(libBfdInfo.staticSymCnt == 0 && debugBfdInfo.staticSymCnt == 0 &&
libBfdInfo.dynSymCnt == 0 && debugBfdInfo.dynSymCnt == 0)) {
logger->printWarnMsg("Cannot load library information.");
free(targetLibInfo.libname);
targetLibInfo.libname = NULL;
free(targetLibInfo.libpath);
targetLibInfo.libpath = NULL;
free(targetLibInfo.realpath);
targetLibInfo.realpath = NULL;
return false;
}
return true;
}
/*!
* \brief Find symbol in target library.
* \param symbol [in] Symbol string.
* \return Address of designated symbol.<br>
* value is null if process is failure.
*/
void *TSymbolFinder::findSymbol(char const *symbol) {
void *result = NULL;
/* Search symbol in library as static symbol. */
if (likely(libBfdInfo.staticSymCnt != 0)) {
result = doFindSymbol(&libBfdInfo, symbol, false);
}
/* If not found symbol. */
if (unlikely(result == NULL)) {
/* Search symbol in library's debuginfo. */
if (likely(debugBfdInfo.staticSymCnt != 0)) {
result = doFindSymbol(&debugBfdInfo, symbol, false);
}
}
/* Search symbol in library as dynamic symbol. */
if (unlikely(result == NULL)) {
/* Search symbol in library. */
if (likely(libBfdInfo.dynSymCnt != 0)) {
result = doFindSymbol(&libBfdInfo, symbol, true);
}
}
if (unlikely(result == NULL)) {
/* Search symbol in library's debuginfo. */
if (likely(debugBfdInfo.dynSymCnt != 0)) {
result = doFindSymbol(&debugBfdInfo, symbol, true);
}
}
if (likely(result != NULL)) {
/* Convert absolute symbol address. */
result = getAbsoluteAddress(result);
}
return result;
}
/*!
* \brief Load target libaray information.
* \param path [in] Target library path.
* \param libInfo [out] BFD information record.<br>
* Value is null if process is failure.
*/
void TSymbolFinder::loadLibraryInfo(char const *path, TLibBFDInfo *libInfo) {
bfd *bfdDesc = NULL;
/* Open library. */
bfdDesc = bfd_openr(path, NULL);
if (unlikely(bfdDesc == NULL)) {
return;
}
/* If illegal format. */
if (!bfd_check_format(bfdDesc, bfd_object)) {
bfd_close(bfdDesc);
return;
}
/* If library don't have symbol. */
if (!(bfd_get_file_flags(bfdDesc) & HAS_SYMS)) {
bfd_close(bfdDesc);
return;
}
/* Library is legal binary file. */
asymbol *syms = NULL;
/* Create empty symbol as temporary working space. */
syms = bfd_make_empty_symbol(bfdDesc);
if (unlikely(syms == NULL)) {
bfd_close(bfdDesc);
return;
}
libInfo->bfdInfo = bfdDesc;
/* Load static symbols. */
libInfo->staticSymCnt = bfd_read_minisymbols(
bfdDesc, 0, (void **)&libInfo->staticSyms, &libInfo->staticSymSize);
/* Load dynamic symbols. */
libInfo->dynSymCnt = bfd_read_minisymbols(
bfdDesc, 1, (void **)&libInfo->dynSyms, &libInfo->dynSymSize);
/* Check .symtab section. If there are no symbols in the BFD,
* below function returns the size of terminal Null pointer or 0 */
libInfo->hasSymtab = ((size_t)bfd_get_symtab_upper_bound(bfdDesc)
> sizeof(NULL));
libInfo->workSym = syms;
}
/*!
* \brief Find symbol in target library to use BFD.
* \param libInfo [in] BFD information record.
* \param symbol [in] Symbol string.
* \param isDynSym [in] Symbol is dynamic symbol.
* \return Address of designated symbol.<br>
* value is null if process is failure.
*/
void *TSymbolFinder::doFindSymbol(TLibBFDInfo *libInfo, char const *symbol,
bool isDynSym) {
bfd *bfdDesc = libInfo->bfdInfo;
asymbol *syms = libInfo->workSym;
char *miniSymsEntry = NULL;
int miniSymCnt = 0;
int dyn = ((isDynSym) ? 1 : 0);
void *result = NULL;
unsigned int size = 0;
if (isDynSym) {
miniSymCnt = libInfo->dynSymCnt;
miniSymsEntry = libInfo->dynSyms;
size = libInfo->dynSymSize;
} else {
miniSymCnt = libInfo->staticSymCnt;
miniSymsEntry = libInfo->staticSyms;
size = libInfo->staticSymSize;
}
/* Search symbol. */
for (int idx = 0; idx < miniSymCnt; idx++) {
/* Convert symbol to normally symbol. */
asymbol *symEntry =
bfd_minisymbol_to_symbol(bfdDesc, dyn, miniSymsEntry, syms);
if (strcmp(bfd_asymbol_name(symEntry), symbol) == 0) {
/* Found target symbol. */
result = (void *)bfd_asymbol_value(symEntry);
break;
}
/* Move next symbol entry. */
miniSymsEntry += (ptrdiff_t)size;
}
return result;
}
/*!
* \brief Clear loaded libaray data.
*/
void TSymbolFinder::clear(void) {
/* Cleanup. */
free(targetLibInfo.libname);
targetLibInfo.libname = NULL;
free(targetLibInfo.libpath);
targetLibInfo.libpath = NULL;
free(targetLibInfo.realpath);
targetLibInfo.realpath = NULL;
/* Deallocate and null-clear bfd object. */
if (unlikely(libBfdInfo.bfdInfo != NULL)) {
bfd_close(libBfdInfo.bfdInfo);
libBfdInfo.bfdInfo = NULL;
}
if (unlikely(debugBfdInfo.bfdInfo != NULL)) {
bfd_close(debugBfdInfo.bfdInfo);
debugBfdInfo.bfdInfo = NULL;
}
/* Deallocate and null-clear each symbol object. */
free(libBfdInfo.staticSyms);
libBfdInfo.staticSyms = NULL;
libBfdInfo.staticSymCnt = 0;
free(debugBfdInfo.staticSyms);
debugBfdInfo.staticSyms = NULL;
debugBfdInfo.staticSymCnt = 0;
free(libBfdInfo.dynSyms);
libBfdInfo.dynSyms = NULL;
libBfdInfo.dynSymCnt = 0;
free(debugBfdInfo.dynSyms);
debugBfdInfo.dynSyms = NULL;
debugBfdInfo.dynSymCnt = 0;
}
| 12,175
|
C++
|
.cpp
| 360
| 29.611111
| 82
| 0.673136
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,000
|
jniZipArchiver.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/jniZipArchiver.cpp
|
/*!
* \file jniZipArchiver.cpp
* \brief This file is used create archive file to use java zip library.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <dirent.h>
#include <fcntl.h>
#include "globals.hpp"
#include "fsUtil.hpp"
#include "jniZipArchiver.hpp"
/*!
* \brief Refference of "BufferedOutputStream" class data.
*/
jclass TJniZipArchiver::clsBuffOutStrm = NULL;
/*!
* \brief Refference of "BufferedOutputStream" class constructer.
*/
jmethodID TJniZipArchiver::clsBuffOutStrm_init = NULL;
/*!
* \brief Refference of "FileOutputStream" class data.
*/
jclass TJniZipArchiver::clsFileOutStrm = NULL;
/*!
* \brief Refference of "FileOutputStream" class constructer.
*/
jmethodID TJniZipArchiver::clsFileOutStrm_init = NULL;
/*!
* \brief Refference of "ZipOutputStream" class data.
*/
jclass TJniZipArchiver::clsZipOutStrm = NULL;
/*!
* \brief Refference of "ZipOutputStream" class constructer.
*/
jmethodID TJniZipArchiver::clsZipOutStrm_init = NULL;
/*!
* \brief Refference of "ZipEntry" class data.
*/
jclass TJniZipArchiver::clsZipEntry = NULL;
/*!
* \brief Refference of "ZipEntry" class constructer.
*/
jmethodID TJniZipArchiver::clsZipEntry_init = NULL;
/*!
* \brief Refference of "ZipOutputStream" class method "close".
*/
jmethodID TJniZipArchiver::clsZipOutStrm_close = NULL;
/*!
* \brief Refference of "ZipOutputStream" class method "closeEntry".
*/
jmethodID TJniZipArchiver::clsZipOutStrm_closeEntry = NULL;
/*!
* \brief Refference of "ZipOutputStream" class method "putNextEntry".
*/
jmethodID TJniZipArchiver::clsZipOutStrm_putNextEntry = NULL;
/*!
* \brief Refference of "ZipOutputStream" class method "write".
*/
jmethodID TJniZipArchiver::clsZipOutStrm_write = NULL;
/*!
* \brief Refference of "ZipOutputStream" class method "flush".
* \sa FilterOutputStream::flush
*/
jmethodID TJniZipArchiver::clsZipOutStrm_flush = NULL;
/*!
* \brief Flag of load initialize data.
*/
bool TJniZipArchiver::loadFlag = false;
/*!
* \brief Global initialization.
* \param env [in] JNI environment object.
* \return Process is succeed, if value is true.<br>
* Process is failure, if value is false.
* \warning Please call only once from main thread.
*/
bool TJniZipArchiver::globalInitialize(JNIEnv *env) {
/* If already loaded data. */
if (loadFlag) {
logger->printWarnMsg("Already initialized jni archiver.");
return true;
}
loadFlag = true;
/* Search class and constructor method. */
/* Search class list. */
const struct {
jclass *pClass;
char className[255];
jmethodID *pClassInit;
char initArgs[255];
} loadClassList[] = {
{&clsBuffOutStrm, "Ljava/io/BufferedOutputStream;",
&clsBuffOutStrm_init, "(Ljava/io/OutputStream;)V"},
{&clsFileOutStrm, "Ljava/io/FileOutputStream;", &clsFileOutStrm_init,
"(Ljava/lang/String;)V"},
{&clsZipOutStrm, "Ljava/util/zip/ZipOutputStream;", &clsZipOutStrm_init,
"(Ljava/io/OutputStream;)V"},
{&clsZipEntry, "Ljava/util/zip/ZipEntry;", &clsZipEntry_init,
"(Ljava/lang/String;)V"},
{NULL, {0}, NULL, {0}} /* End flag. */
};
/* Search class and get global reference. */
for (int i = 0; loadClassList[i].pClass != NULL; i++) {
/* Find java class. */
jclass localRefClass = env->FindClass(loadClassList[i].className);
/* If not found common class. */
if (unlikely(localRefClass == NULL)) {
handlePendingException(env);
logger->printWarnMsg("Couldn't get common class.");
return false;
}
/* Get global reference. */
(*loadClassList[i].pClass) = (jclass)env->NewGlobalRef(localRefClass);
/* If failure getting global reference. */
if (unlikely((*loadClassList[i].pClass) == NULL)) {
handlePendingException(env);
env->DeleteLocalRef(localRefClass);
logger->printWarnMsg("Couldn't get global reference.");
return false;
}
/* Get class constructor. */
(*loadClassList[i].pClassInit) =
env->GetMethodID(localRefClass, "<init>", loadClassList[i].initArgs);
/* If failure getting constructor. */
if (unlikely((*loadClassList[i].pClassInit) == NULL)) {
handlePendingException(env);
env->DeleteLocalRef(localRefClass);
logger->printWarnMsg("Couldn't get constructor of common class.");
return false;
}
/* Clearup. */
env->DeleteLocalRef(localRefClass);
}
/* Search other method. */
/* Search method list. */
const struct {
jclass pClass;
jmethodID *pMethod;
char methodName[20];
char methodParam[50];
} methodList[] = {
{clsZipOutStrm, &clsZipOutStrm_close, "close", "()V"},
{clsZipOutStrm, &clsZipOutStrm_closeEntry, "closeEntry", "()V"},
{clsZipOutStrm, &clsZipOutStrm_putNextEntry, "putNextEntry",
"(Ljava/util/zip/ZipEntry;)V"},
{clsZipOutStrm, &clsZipOutStrm_write, "write", "([BII)V"},
{clsZipOutStrm, &clsZipOutStrm_flush, "flush", "()V"},
{NULL, NULL, {0}, {0}} /* End flag. */
};
/* Search class method. */
for (int i = 0; methodList[i].pMethod != NULL; i++) {
jmethodID methodID = NULL;
/* Search method in designated class. */
methodID = env->GetMethodID(methodList[i].pClass, methodList[i].methodName,
methodList[i].methodParam);
/* If failure getting function. */
if (unlikely(methodID == NULL)) {
handlePendingException(env);
logger->printWarnMsg("Couldn't get function of jni zip archive.");
return false;
}
(*methodList[i].pMethod) = methodID;
}
return true;
}
/*!
* \brief Global finalize.
* \param env [in] JNI environment object.
* \return Process is succeed, if value is true.<br>
* Process is failure, if value is false.
* \warning Please call only once from main thread.
*/
bool TJniZipArchiver::globalFinalize(JNIEnv *env) {
/* Sanity check. */
if (!loadFlag) {
logger->printWarnMsg("Didn't initialize jni archiver yet.");
return false;
}
loadFlag = false;
/* Delete common data's global reference. */
if (likely(clsBuffOutStrm != NULL)) {
env->DeleteGlobalRef(clsBuffOutStrm);
clsBuffOutStrm = NULL;
}
if (likely(clsFileOutStrm != NULL)) {
env->DeleteGlobalRef(clsFileOutStrm);
clsFileOutStrm = NULL;
}
if (likely(clsZipOutStrm != NULL)) {
env->DeleteGlobalRef(clsZipOutStrm);
clsZipOutStrm = NULL;
}
if (likely(clsZipEntry != NULL)) {
env->DeleteGlobalRef(clsZipEntry);
clsZipEntry = NULL;
}
return true;
}
/*!
* \brief TJniZipArchiver constructor.
*/
TJniZipArchiver::TJniZipArchiver(void) : TArchiveMaker() {
/* If don't loaded data yet. */
if (unlikely(!loadFlag)) {
throw "Didn't initialize jni archiver yet.";
}
}
/*!
* \brief TJniZipArchiver destructor.
*/
TJniZipArchiver::~TJniZipArchiver(void) { /* Do Nothing. */ }
/*!
* \brief Do file archive and create archive file.
* \param env [in] JNI environment object.
* \param archiveFile [in] archive file name.
* \return Response code of execute commad line.
*/
int TJniZipArchiver::doArchive(JNIEnv *env, char const *archiveFile) {
/* Sanity check. */
if (unlikely(strlen(this->getTarget()) == 0 || archiveFile == NULL ||
strlen(archiveFile) == 0)) {
logger->printWarnMsg("Illegal archive paramter.");
clear();
return -1;
}
/* Exec command. */
int result = execute(env, archiveFile);
/* Cleanup. */
clear();
/* Succeed. */
return result;
}
/*!
* \brief Execute archive.
* \param env [in] JNI environment object.
* \param archiveFile [in] archive file name.
* \return Response code of execute archive.
*/
int TJniZipArchiver::execute(JNIEnv *env, char const *archiveFile) {
/* Variable to store return code. */
int result = 0;
/* Variable to store java object. */
jstring jArcFile = NULL;
jobject jFileOutStrm = NULL;
jobject jBuffOutStrm = NULL;
jobject jZipOutStrm = NULL;
/* Create archive file name. */
jArcFile = env->NewStringUTF(archiveFile);
/* If failure any process. */
if (unlikely(jArcFile == NULL)) {
logger->printWarnMsg("Could not allocate jni zip archive name");
handlePendingException(env);
return -1;
}
/* Create java object to make archive file. */
jFileOutStrm = env->NewObject(clsFileOutStrm, clsFileOutStrm_init, jArcFile);
if (unlikely(jFileOutStrm == NULL)) {
result = -1;
} else {
jBuffOutStrm =
env->NewObject(clsBuffOutStrm, clsBuffOutStrm_init, jFileOutStrm);
if (unlikely(jBuffOutStrm == NULL)) {
result = -1;
} else {
jZipOutStrm =
env->NewObject(clsZipOutStrm, clsZipOutStrm_init, jBuffOutStrm);
if (unlikely(jZipOutStrm == NULL)) {
result = -1;
}
}
}
/* Cleanup. */
env->DeleteLocalRef(jArcFile);
/* If creation stream object is successe. */
if (unlikely(result == 0)) {
/* Write file data to java zip stream. */
result = writeFiles(env, jZipOutStrm);
/* Close zip stream. */
env->CallVoidMethod(jZipOutStrm, clsZipOutStrm_close);
if (unlikely(env->ExceptionOccurred() != NULL && result == 0)) {
result = (errno != 0) ? errno : -1;
logger->printWarnMsgWithErrno("Could not write to jni zip archive");
}
}
/* If failure create stream object. */
if (unlikely(result != 0)) {
env->ExceptionClear();
}
/* Cleanup. */
if (likely(jZipOutStrm != NULL)) {
env->DeleteLocalRef(jZipOutStrm);
}
if (likely(jBuffOutStrm != NULL)) {
env->DeleteLocalRef(jBuffOutStrm);
}
if (likely(jFileOutStrm != NULL)) {
env->DeleteLocalRef(jFileOutStrm);
}
/* If failure any process. */
if (unlikely(result != 0)) {
/* Remove file. Because it's maybe broken. */
unlink(archiveFile);
}
return result;
}
/*!
* \brief Write files to archive.
* \param env [in] JNI environment object.
* \param jZipStream [in] JNI zip archive stream object.
* \return Response code of execute archive.
*/
int TJniZipArchiver::writeFiles(JNIEnv *env, jobject jZipStream) {
/* Variable to store return code. */
int result = 0;
/* Variable to operate entry in directory. */
DIR *dir = NULL;
struct dirent *entry = NULL;
/* Variable for write file data. */
ssize_t readSize = 0;
char buff[255];
jbyteArray jByteArray = NULL;
/* Open directory. */
dir = opendir(this->getTarget());
/* Creaet byte array. */
jByteArray = env->NewByteArray(sizeof(buff));
/* If failure any process. */
if (unlikely(dir == NULL || jByteArray == NULL)) {
int raisedErrNum = errno;
if (likely(dir != NULL)) {
closedir(dir);
}
if (likely(jByteArray != NULL)) {
env->DeleteLocalRef(jByteArray);
}
return ((raisedErrNum != 0) ? raisedErrNum : -1);
}
int raisedErrNum = 0;
try {
/* Loop for file in designed working directory. */
while ((entry = readdir(dir)) != NULL) {
char *filePath = NULL;
jstring jTargetFile = NULL;
jobject jZipEntry = NULL;
int fd = -1;
/* Check file name. */
if (strcmp(entry->d_name, "..") == 0 || strcmp(entry->d_name, ".") == 0) {
continue;
}
/* Create source file path. */
filePath = createFilename(this->getTarget(), entry->d_name);
if (unlikely(filePath == NULL)) {
raisedErrNum = errno;
throw 1;
}
/* Create zip entry name without directory path. */
jTargetFile = env->NewStringUTF(entry->d_name);
if (unlikely(jTargetFile == NULL)) {
raisedErrNum = errno;
free(filePath);
throw 1;
}
/* Create zip entry and cleanup. */
jZipEntry = env->NewObject(clsZipEntry, clsZipEntry_init, jTargetFile);
raisedErrNum = errno;
env->DeleteLocalRef(jTargetFile);
/* If failure create zip entry. */
if (unlikely(jZipEntry == NULL)) {
free(filePath);
throw 1;
}
/* Setting zip entry and cleanup. */
env->CallVoidMethod(jZipStream, clsZipOutStrm_putNextEntry, jZipEntry);
raisedErrNum = errno;
env->DeleteLocalRef(jZipEntry);
/* If failure setting zip entry. */
if (unlikely(env->ExceptionOccurred() != NULL)) {
free(filePath);
throw 1;
}
/* Open source file. */
fd = open(filePath, O_RDONLY, S_IRUSR);
free(filePath);
if (unlikely(fd >= 0)) {
raisedErrNum = 0;
/* Write source file to zip archive. */
while ((readSize = read(fd, buff, sizeof(buff))) > 0) {
/* Copy native byte array to java byte array. */
env->SetByteArrayRegion(jByteArray, 0, readSize, (jbyte *)buff);
if (unlikely(env->ExceptionOccurred() != NULL)) {
raisedErrNum = errno;
break;
}
/* Write data. */
env->CallVoidMethod(jZipStream, clsZipOutStrm_write, jByteArray,
(jint)0, (jint)readSize);
if (unlikely(env->ExceptionOccurred() != NULL)) {
raisedErrNum = errno;
break;
}
}
if (unlikely(close(fd) < 0 || raisedErrNum != 0)) {
raisedErrNum = (raisedErrNum == 0) ? errno : raisedErrNum;
throw 1;
}
} else {
result = errno;
/* Open file process is Failed. */
logger->printWarnMsgWithErrno("Could not open jni zip source file");
break;
}
/* Close zip entry. */
env->CallVoidMethod(jZipStream, clsZipOutStrm_closeEntry);
if (unlikely(env->ExceptionOccurred() != NULL)) {
raisedErrNum = errno;
throw 1;
}
}
/* Flush zip data. */
env->CallVoidMethod(jZipStream, clsZipOutStrm_flush);
if (unlikely(env->ExceptionOccurred() != NULL)) {
raisedErrNum = errno;
throw 1;
}
} catch (...) {
result = (raisedErrNum != 0) ? raisedErrNum : -1;
logger->printWarnMsgWithErrno("Could not write to jni zip archive.");
env->ExceptionClear();
}
/* Cleanup. */
closedir(dir);
env->DeleteLocalRef(jByteArray);
return result;
}
| 14,879
|
C++
|
.cpp
| 446
| 28.656951
| 82
| 0.658287
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,001
|
deadlockDetector.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/deadlockDetector.cpp
|
/*!
* \file deadlockDetector.cpp
* \brief This file is used by find deadlock.
* Copyright (C) 2017-2019 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#include <jvmti.h>
#include <jni.h>
#include <pthread.h>
#include <sched.h>
#ifdef HAVE_ATOMIC
#include <atomic>
#else
#include <cstdatomic>
#endif
#include <map>
#include "globals.hpp"
#include "elapsedTimer.hpp"
#include "libmain.hpp"
#include "callbackRegister.hpp"
#include "deadlockDetector.hpp"
#define BUFFER_SZ 256
/*!
* \brief Processing flag.
*/
static std::atomic_int processing(0);
/*!
* \brief Monitor owner map.
*/
static std::map<jint, jint> monitor_owners;
/*!
* \brief Monitor waiters list.
*/
static std::map<jint, jint> waiter_list;
/*!
* \brief Mutex for maps
*/
static pthread_mutex_t mutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
namespace dldetector {
/*!
* \brief Send SNMP Trap which contains deadlock information.
* \param nowTime [in] The time of deadlock occurred.
* \param numThreads [in] Number of threads which are related to deadlock.
* \param name [in] Thread name of deadlock occurred.
*/
static void sendSNMPTrap(TMSecTime nowTime,
int numThreads, const char *name) {
/* OIDs */
char trapOID[50] = OID_DEADLOCKALERT;
oid OID_ALERT_DATE[] = {SNMP_OID_HEAPALERT, 1};
oid OID_DEAD_COUNT[] = {SNMP_OID_DEADLOCKALERT, 1};
oid OID_DEAD_NAME[] = {SNMP_OID_DEADLOCKALERT, 2};
char buf[BUFFER_SZ];
TTrapSender sender;
sender.setSysUpTime();
sender.setTrapOID(trapOID);
/* Set alert datetime. */
snprintf(buf, BUFFER_SZ - 1, "%llu", nowTime);
sender.addValue(OID_ALERT_DATE, OID_LENGTH(OID_ALERT_DATE), buf,
SNMP_VAR_TYPE_COUNTER64);
/* Set thread count. */
snprintf(buf, BUFFER_SZ - 1, "%d", numThreads);
sender.addValue(OID_DEAD_COUNT, OID_LENGTH(OID_DEAD_COUNT), buf,
SNMP_VAR_TYPE_COUNTER32);
/* Set thread name. */
sender.addValue(OID_DEAD_NAME, OID_LENGTH(OID_DEAD_NAME), name,
SNMP_VAR_TYPE_STRING);
/* Send trap. */
if (unlikely(sender.sendTrap() != SNMP_PROC_SUCCESS)) {
/* Ouput message and clean up. */
sender.clearValues();
logger->printWarnMsg("Could not send SNMP trap for deadlock!");
}
}
/*!
* \brief Notify deadlock occurrence via stdout/err and SNMP Trap.
* \param jvmti [in] JVMTI environment.
* \oaram env [in] JNI environment.
* \param thread [in] jthread object which deadlock triggered.
* \param monitor [in] Monitor object.
* \param numThreads [in] Number of threads which are related to deadlock.
*/
static void notifyDeadlockOccurrence(jvmtiEnv *jvmti, JNIEnv *env,
jthread thread, jobject monitor,
int numThreads) {
TProcessMark mark(processing);
TMSecTime nowTime = (TMSecTime)getNowTimeSec();
jvmtiThreadInfo threadInfo = {0};
jvmti->GetThreadInfo(thread, &threadInfo);
logger->printCritMsg(
"ALERT(DEADLOCK): Deadlock occurred! count: %d, thread: \"%s\"",
numThreads, threadInfo.name);
if (conf->SnmpSend()->get()) {
sendSNMPTrap(nowTime, numThreads, threadInfo.name);
}
jvmti->Deallocate((unsigned char *)threadInfo.name);
if (conf->TriggerOnLogLock()->get()) {
TElapsedTimer elapsedTime("Take LogInfo");
int result = logManager->collectLog(jvmti, env,
OccurredDeadlock, nowTime, "");
if (unlikely(result != 0)) {
logger->printWarnMsg("Could not collect log archive.");
}
}
if (unlikely(conf->KillOnError()->get())) {
forcedAbortJVM(jvmti, env, "deadlock occurred");
}
}
/*!
* \brief Event handler of JVMTI MonitorContendedEnter for finding deadlock.
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment of the event (current) thread.
* \param thread [in] JNI local reference to the thread attempting to enter
* the monitor.
* \param object [in] JNI local reference to the monitor.
*/
void JNICALL OnMonitorContendedEnter(
jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jobject object) {
/* Check owned monitors */
jint monitor_cnt;
jobject *owned_monitors;
if (isError(jvmti, jvmti->GetOwnedMonitorInfo(thread,
&monitor_cnt,
&owned_monitors))) {
logger->printWarnMsg("Could not get owned monitor info (%p)\n",
*(void **)thread);
return;
}
if (monitor_cnt == 0) { // This thread does not have a monitor.
jvmti->Deallocate((unsigned char *)owned_monitors);
return;
}
jint monitor_hash;
jint thread_hash;
jvmti->GetObjectHashCode(thread, &thread_hash);
jvmti->GetObjectHashCode(object, &monitor_hash);
{
TMutexLocker locker(&mutex);
/* Avoid JDK-8185164 */
bool canSkip = true;
/* Store all owned monitors to owner list */
for (int idx = 0; idx < monitor_cnt; idx++) {
jint current_monitor_hash;
jvmti->GetObjectHashCode(owned_monitors[idx], ¤t_monitor_hash);
if (current_monitor_hash == monitor_hash) {
continue;
}
monitor_owners[current_monitor_hash] = thread_hash;
canSkip = false;
}
jvmti->Deallocate((unsigned char *)owned_monitors);
if (!canSkip) {
/* Add to waiters list */
jvmti->GetObjectHashCode(object, &monitor_hash);
waiter_list[thread_hash] = monitor_hash;
/* Check deadlock */
int numThreads = 1;
while (true) {
numThreads++;
auto owner_itr = monitor_owners.find(monitor_hash);
if (owner_itr == monitor_owners.end()) {
break; // No deadlock
}
auto waiter_itr = waiter_list.find(owner_itr->second);
if (waiter_itr == waiter_list.end()) {
break; // No deadlock
}
owner_itr = monitor_owners.find(waiter_itr->second);
if (owner_itr == monitor_owners.end()) {
break; // No deadlock
}
if (owner_itr->second == thread_hash) {
// Deadlock!!
notifyDeadlockOccurrence(jvmti, env, thread, object, numThreads);
break;
}
monitor_hash = waiter_itr->second;
}
}
}
}
/*!
* \brief Event handler of JVMTI MonitorContendedEntered for finding deadlock.
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment of the event (current) thread.
* \param thread [in] JNI local reference to the thread attempting to enter
* the monitor.
* \param object [in] JNI local reference to the monitor.
*/
void JNICALL OnMonitorContendedEntered(
jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jobject object) {
/* Check owned monitors */
jint monitor_cnt;
jobject *owned_monitors;
if (isError(jvmti, jvmti->GetOwnedMonitorInfo(thread,
&monitor_cnt,
&owned_monitors))) {
logger->printWarnMsg("Could not get owned monitor info (%p)\n",
*(void **)thread);
return;
}
if (monitor_cnt <= 1) { // This thread does not have other monitor(s).
jvmti->Deallocate((unsigned char *)owned_monitors);
return;
}
{
TMutexLocker locker(&mutex);
/* Remove all owned monitors from owner list */
for (int idx = 0; idx < monitor_cnt; idx++) {
jint monitor_hash;
jvmti->GetObjectHashCode(owned_monitors[idx], &monitor_hash);
monitor_owners.erase(monitor_hash);
}
jvmti->Deallocate((unsigned char *)owned_monitors);
/* Remove thread from waiters list */
jint thread_hash;
jvmti->GetObjectHashCode(thread, &thread_hash);
waiter_list.erase(thread_hash);
}
}
/*!
* \brief Deadlock detector initializer.
* \param jvmti [in] JVMTI environment
* \parma isOnLoad [in] OnLoad phase or not (Live phase).
* \return Process result.
* \warning This function MUST be called only once.
*/
bool initialize(jvmtiEnv *jvmti, bool isOnLoad) {
jvmtiCapabilities capabilities = {0};
capabilities.can_get_monitor_info = 1;
if (isOnLoad) {
/*
* can_get_owned_monitor_info must be set at OnLoad phase.
*
* See also:
* hotspot/src/share/vm/prims/jvmtiManageCapabilities.cpp
*/
capabilities.can_get_owned_monitor_info = 1;
}
TMonitorContendedEnterCallback::mergeCapabilities(&capabilities);
if (isError(jvmti, jvmti->AddCapabilities(&capabilities))) {
logger->printCritMsg(
"Couldn't set event capabilities for deadlock detector.");
return false;
}
/*
* All JVMTI events are not fired at this point.
* So we need not to lock this operation.
*/
monitor_owners.clear();
waiter_list.clear();
TMonitorContendedEnterCallback::registerCallback(&OnMonitorContendedEnter);
TMonitorContendedEnterCallback::switchEventNotification(jvmti,
JVMTI_ENABLE);
TMonitorContendedEnteredCallback::registerCallback(
&OnMonitorContendedEntered);
TMonitorContendedEnteredCallback::switchEventNotification(jvmti,
JVMTI_ENABLE);
return true;
}
/*!
* \brief Deadlock detector finalizer.
* This function unregisters JVMTI callback for deadlock detection.
* \param jvmti [in] JVMTI environment
*/
void finalize(jvmtiEnv *jvmti) {
TMonitorContendedEnterCallback::unregisterCallback(
&OnMonitorContendedEnter);
TMonitorContendedEnteredCallback::unregisterCallback(
&OnMonitorContendedEntered);
/* Refresh JVMTI event callbacks */
registerJVMTICallbacks(jvmti);
while (processing > 0) {
sched_yield();
}
{
TMutexLocker locker(&mutex);
monitor_owners.clear();
waiter_list.clear();
}
}
}
| 11,224
|
C++
|
.cpp
| 297
| 30.026936
| 80
| 0.621895
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,002
|
overrider.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/overrider.cpp
|
/*!
* \file overrider.cpp
* \brief Controller of overriding functions in HotSpot VM.
* Copyright (C) 2014-2018 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <pthread.h>
#include <sys/mman.h>
#include "globals.hpp"
#include "vmVariables.hpp"
#include "vmFunctions.hpp"
#include "overrider.hpp"
#include "snapShotMain.hpp"
#if PROCESSOR_ARCH == X86
#include "arch/x86/x86BitMapMarker.hpp"
#ifdef AVX
#include "arch/x86/avx/avxBitMapMarker.hpp"
#endif
#if (defined SSE2) || (defined SSE4)
#include "arch/x86/sse2/sse2BitMapMarker.hpp"
#endif
#elif PROCESSOR_ARCH == ARM
#ifdef NEON
#include "arch/arm/neon/neonBitMapMarker.hpp"
#else
#include "arch/arm/armBitMapMarker.hpp"
#endif
#endif
/* These functions is defined in override.S. */
/*!
* \brief Override function for heap object on parallelGC.
*/
DEFINE_OVERRIDE_FUNC_4(par);
DEFINE_OVERRIDE_FUNC_5(par_6964458);
DEFINE_OVERRIDE_FUNC_5(par_jdk9);
DEFINE_OVERRIDE_FUNC_7(par_jdk10);
/*!
* \brief Override function for heap object on parallelOldGC.
*/
DEFINE_OVERRIDE_FUNC_4(parOld);
DEFINE_OVERRIDE_FUNC_5(parOld_6964458);
DEFINE_OVERRIDE_FUNC_5(parOld_jdk9);
/*!
* \brief Override function for sweep at old gen on CMSGC.
*/
DEFINE_OVERRIDE_FUNC_1(cms_sweep);
/*!
* \brief Override function for heap object at new gen on CMSGC.
*/
DEFINE_OVERRIDE_FUNC_4(cms_new);
DEFINE_OVERRIDE_FUNC_5(cms_new_6964458);
DEFINE_OVERRIDE_FUNC_5(cms_new_jdk9);
/*!
* \brief Override function for heap object on G1GC.
*/
DEFINE_OVERRIDE_FUNC_9(g1);
DEFINE_OVERRIDE_FUNC_11(g1_6964458);
DEFINE_OVERRIDE_FUNC_12(g1_jdk9);
DEFINE_OVERRIDE_FUNC_19(g1_jdk10);
/*!
* \brief Override function for cleanup and System.gc() event on G1GC.
*/
DEFINE_OVERRIDE_FUNC_3(g1Event);
/*!
* \brief Override function for adjust klassOop.
*/
DEFINE_OVERRIDE_FUNC_8(adj);
/*!
* \brief Override function for JVMTI function.
*/
DEFINE_OVERRIDE_FUNC_1(jvmti);
/*!
* \brief Override function for inner GC function.
*/
DEFINE_OVERRIDE_FUNC_3(innerStart);
/*!
* \brief Override function for WatcherThread.
*/
DEFINE_OVERRIDE_FUNC_1(watcherThread);
/*!
* \brief Bitmap object for CMS and G1 GC.
*/
TBitMapMarker *checkObjectMap = NULL;
/* Variables for override information. */
/*!
* \brief Pointer of hook information on parallelGC for default.
*/
THookFunctionInfo default_par_hook[] = {
HOOK_FUNC(par, 0, "_ZTV13instanceKlass",
"_ZN13instanceKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par, 1, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par, 2, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par, 3, "_ZTV16instanceRefKlass",
"_ZN16instanceRefKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on parallelGC for after CR6964458.
*/
THookFunctionInfo CR6964458_par_hook[] = {
HOOK_FUNC(par_6964458, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 1, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 2, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on parallelGC for after CR8000213.
*/
THookFunctionInfo CR8000213_par_hook[] = {
HOOK_FUNC(par_6964458, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 1, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 2, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC(par_6964458, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass19oop_follow_contentsEP7oopDesc",
&callbackForParallel),
HOOK_FUNC_END};
/*!
* \brief Pointers of hook information on parallelGC for several CRs.<br>
* These CRs have no impact on parallelGC, so refer to the last.
*/
#define CR8027746_par_hook CR8000213_par_hook
#define CR8049421_par_hook CR8000213_par_hook
/*!
* \brief Pointer of hook information on parallelGC for after jdk 9.
*/
THookFunctionInfo jdk9_par_hook[] = {
HOOK_FUNC(par_jdk9, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass22oop_ms_adjust_pointersEP7oopDesc",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk9, 1, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass22oop_ms_adjust_pointersEP7oopDesc",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk9, 2, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass22oop_ms_adjust_pointersEP7oopDesc",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk9, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass22oop_ms_adjust_pointersEP7oopDesc",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk9, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass22oop_ms_adjust_pointersEP7oopDesc",
&callbackForParallelWithMarkCheck),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on parallelGC for after jdk 10.
*/
THookFunctionInfo jdk10_par_hook[] = {
HOOK_FUNC(par_jdk10, 0, "_ZTV20AdjustPointerClosure",
"_ZN20AdjustPointerClosure6do_oopEPP7oopDesc",
&callbackForDoOopWithMarkCheck),
HOOK_FUNC(par_jdk10, 1, "_ZTV20AdjustPointerClosure",
"_ZN20AdjustPointerClosure6do_oopEPj",
&callbackForDoNarrowOopWithMarkCheck),
HOOK_FUNC(par_jdk10, 2, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP18MarkAndPushClosure",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk10, 3, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP18MarkAndPushClosure",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk10, 4, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass18oop_oop_iterate_nvEP7oopDescP18MarkAndPushClosure",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk10, 5, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP18MarkAndPushClosure",
&callbackForParallelWithMarkCheck),
HOOK_FUNC(par_jdk10, 6, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP18MarkAndPushClosure",
&callbackForParallelWithMarkCheck),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on parallelGC.
*/
THookFunctionInfo *par_hook = NULL;
/*!
* \brief Pointer of hook information on parallelOldGC for default.
*/
THookFunctionInfo default_parOld_hook[] = {
HOOK_FUNC(parOld, 0, "_ZTV13instanceKlass",
"_ZN13instanceKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld, 1, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld, 2, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld, 3, "_ZTV16instanceRefKlass",
"_ZN16instanceRefKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on parallelOldGC for after CR6964458.
*/
THookFunctionInfo CR6964458_parOld_hook[] = {
HOOK_FUNC(parOld_6964458, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 1, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 2, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on parallelOldGC for after CR8000213.
*/
THookFunctionInfo CR8000213_parOld_hook[] = {
HOOK_FUNC(parOld_6964458, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 1, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 2, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC(parOld_6964458, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass19oop_follow_"
"contentsEP20ParCompactionManagerP7oopDesc",
&callbackForParOld),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on parallelOldGC for after jdk 9.
*/
THookFunctionInfo jdk9_parOld_hook[] = {
HOOK_FUNC(parOld_jdk9, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass22oop_pc_follow_contentsEP7oopDescP20ParCompactionManager",
&callbackForParOld),
HOOK_FUNC(parOld_jdk9, 1, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass22oop_pc_follow_contentsEP7oopDescP20ParCompactionManager",
&callbackForParOld),
HOOK_FUNC(parOld_jdk9, 2, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass22oop_pc_follow_contentsEP7oopDescP20ParCompactionManager",
&callbackForParOld),
HOOK_FUNC(parOld_jdk9, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass22oop_pc_follow_contentsEP7oopDescP20ParCompactionManager",
&callbackForParOld),
HOOK_FUNC(parOld_jdk9, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass22oop_pc_follow_contentsEP7oopDescP20ParCompactionManager",
&callbackForParOld),
HOOK_FUNC_END};
/*!
* \brief Pointers of hook information on parallelOldGC for several CRs.<br>
* These CRs have no impact on parallelOldGC, so refer to the last.
*/
#define CR8027746_parOld_hook CR8000213_parOld_hook
#define CR8049421_parOld_hook CR8000213_parOld_hook
#define jdk10_parOld_hook jdk9_parOld_hook
/*!
* \brief Pointer of hook information on parallelOldGC.
*/
THookFunctionInfo *parOld_hook = NULL;
/*!
* \brief Pointer of hook information on CMSGC for default.
*/
THookFunctionInfo default_cms_sweep_hook[] = {
HOOK_FUNC(cms_sweep, 0, "_ZTV12SweepClosure",
"_ZN12SweepClosure14do_blk_carefulEP8HeapWord",
&callbackForSweep),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on CMSGC.
*/
THookFunctionInfo *cms_sweep_hook = default_cms_sweep_hook;
/*!
* \brief Pointer of hook information on CMSGC for default.
*/
THookFunctionInfo default_cms_new_hook[] = {
HOOK_FUNC(cms_new, 0, "_ZTV13instanceKlass",
"_ZN13instanceKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(cms_new, 1, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(cms_new, 2, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass15oop_oop_iterateEP7oopDescP10OopClosure",
&callbackForIterate),
HOOK_FUNC(cms_new, 3, "_ZTV16instanceRefKlass",
"_ZN16instanceRefKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on CMSGC for after CR6964458.
*/
THookFunctionInfo CR6964458_cms_new_hook[] = {
HOOK_FUNC(cms_new_6964458, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_6964458, 1, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(
cms_new_6964458, 2, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass15oop_oop_iterateEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_6964458, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_6964458, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP30"
"Par_MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on CMSGC for after CR8000213.
*/
THookFunctionInfo CR8000213_cms_new_hook[] = {
HOOK_FUNC(cms_new_6964458, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_6964458, 1, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(
cms_new_6964458, 2, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass15oop_oop_iterateEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_6964458, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP30Par_"
"MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_6964458, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP30"
"Par_MarkRefsIntoAndScanClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on CMSGC for JDK 9.
*/
THookFunctionInfo jdk9_cms_new_hook[] = {
HOOK_FUNC(cms_new_jdk9, 0, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass17oop_oop_iterate_vEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_jdk9, 1, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass17oop_oop_iterate_vEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(
cms_new_jdk9, 2, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass17oop_oop_iterate_vEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_jdk9, 3, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass17oop_oop_iterate_vEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(cms_new_jdk9, 4, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass17oop_oop_iterate_vEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointers of hook information on CMSGC for several CRs.<br>
* These CRs have no impact on CMSGC, so refer to the last.
*/
#define CR8027746_cms_new_hook CR8000213_cms_new_hook
#define CR8049421_cms_new_hook CR8000213_cms_new_hook
#define jdk10_cms_new_hook jdk9_cms_new_hook
/*!
* \brief Pointer of hook information on CMSGC.
*/
THookFunctionInfo *cms_new_hook = NULL;
/*!
* \brief Pointer of hook information on G1GC for default.
*/
THookFunctionInfo default_g1_hook[] = {
HOOK_FUNC(g1, 0, "_ZTV16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(g1, 1, "_ZTV16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(g1, 2, "_ZTV13instanceKlass",
"_ZN13instanceKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1, 3, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1, 4, "_ZTV16instanceRefKlass",
"_ZN16instanceRefKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1, 5, "_ZTV13instanceKlass",
"_ZN13instanceKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1, 6, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(g1, 7, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass15oop_oop_iterateEP7oopDescP10OopClosure",
&callbackForIterate),
HOOK_FUNC(
g1, 8, "_ZTV16instanceRefKlass",
"_ZN16instanceRefKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC for after CR6964458.
*/
THookFunctionInfo CR6964458_g1_hook[] = {
HOOK_FUNC(g1_6964458, 0, "_ZTV16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(g1_6964458, 1, "_ZTV16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(g1_6964458, 2, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 3, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 4, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 5, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 6, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 7, "_ZTV13objArrayKlass",
"_ZN13objArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 8, "_ZTV14typeArrayKlass",
"_ZN14typeArrayKlass15oop_oop_iterateEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 9, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 10, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC for after CR8000213.
*/
THookFunctionInfo CR8000213_g1_hook[] = {
HOOK_FUNC(g1_6964458, 0, "_ZTV16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(g1_6964458, 1, "_ZTV16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureILb0EL9G1Barrier0ELb1EE6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(g1_6964458, 2, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 3, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 4, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 5, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 6, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 7, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 8, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass15oop_oop_iterateEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 9, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 10, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC for after CR8027746.
*/
THookFunctionInfo CR8027746_g1_hook[] = {
HOOK_FUNC(g1_6964458, 0, "_ZTV16G1ParCopyClosureIL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0ELb1EE6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(g1_6964458, 1, "_ZTV16G1ParCopyClosureIL9G1Barrier0ELb1EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0ELb1EE6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(g1_6964458, 2, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 3, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 4, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 5, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 6, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 7, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 8, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass15oop_oop_iterateEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 9, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 10, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC for after JDK-8049421.
*/
THookFunctionInfo CR8049421_g1_hook[] = {
HOOK_FUNC(
g1_6964458, 0, "_ZTV16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1EE6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(g1_6964458, 1, "_ZTV16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1EE6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(g1_6964458, 2, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 3, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 4, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_"
"nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(g1_6964458, 5, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 6, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 7, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 8, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass15oop_oop_iterateEP7oopDescP18ExtendedOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 9, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_6964458, 10, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7"
"oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC for after JDK 9.
*/
THookFunctionInfo jdk9_g1_hook[] = {
HOOK_FUNC(
g1_jdk9, 0, "_ZTV16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(
g1_jdk9, 1, "_ZTV16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(
g1_jdk9, 2, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 3, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 4, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 5, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 6, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 7, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 8, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 9, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 10, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk9, 11, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC for after JDK 10.
*/
THookFunctionInfo jdk10_g1_hook[] = {
HOOK_FUNC(
g1_jdk10, 0, "_ZTV16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(
g1_jdk10, 1, "_ZTV16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE",
"_ZN16G1ParCopyClosureIL9G1Barrier0EL6G1Mark1ELb0EE6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(
g1_jdk10, 2, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 3, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 4, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 5, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 6, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP23G1RootRegionScanClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 7, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 8, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 9, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 10, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 11, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP14G1CMOopClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 12, "_ZTV20G1MarkAndPushClosure",
"_ZN20G1MarkAndPushClosure6do_oopEPP7oopDesc",
&callbackForDoOop),
HOOK_FUNC(
g1_jdk10, 13, "_ZTV20G1MarkAndPushClosure",
"_ZN20G1MarkAndPushClosure6do_oopEPj",
&callbackForDoNarrowOop),
HOOK_FUNC(
g1_jdk10, 14, "_ZTV13InstanceKlass",
"_ZN13InstanceKlass18oop_oop_iterate_nvEP7oopDescP20G1MarkAndPushClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 15, "_ZTV13ObjArrayKlass",
"_ZN13ObjArrayKlass18oop_oop_iterate_nvEP7oopDescP20G1MarkAndPushClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 16, "_ZTV14TypeArrayKlass",
"_ZN14TypeArrayKlass18oop_oop_iterate_nvEP7oopDescP20G1MarkAndPushClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 17, "_ZTV16InstanceRefKlass",
"_ZN16InstanceRefKlass18oop_oop_iterate_nvEP7oopDescP20G1MarkAndPushClosure",
&callbackForIterate),
HOOK_FUNC(
g1_jdk10, 18, "_ZTV24InstanceClassLoaderKlass",
"_ZN24InstanceClassLoaderKlass18oop_oop_iterate_nvEP7oopDescP20G1MarkAndPushClosure",
&callbackForIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC.
*/
THookFunctionInfo *g1_hook = NULL;
/*!
* \brief Pointer of hook information on G1GC cleanup event for default.
*/
THookFunctionInfo default_g1Event_hook[] = {
HOOK_FUNC(g1Event, 0, "_ZTV9CMCleanUp", "_ZN9CMCleanUp7do_voidEv",
&callbackForG1Cleanup),
HOOK_FUNC(g1Event, 1, "_ZTV16VM_G1CollectFull",
"_ZN15VM_GC_Operation13doit_prologueEv", &callbackForG1Full),
HOOK_FUNC(g1Event, 2, "_ZTV16VM_G1CollectFull",
"_ZN15VM_GC_Operation13doit_epilogueEv", &callbackForG1FullReturn),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook information on G1GC cleanup event.
*/
THookFunctionInfo *g1Event_hook = default_g1Event_hook;
/*!
* \brief Pointer of hook change and adjust oop with GC for default.
*/
THookFunctionInfo default_adj_hook[] = {
HOOK_FUNC(adj, 0, "_ZTV18instanceKlassKlass",
"_ZN18instanceKlassKlass19oop_adjust_pointersEP7oopDesc",
&callbackForAdjustPtr),
HOOK_FUNC(adj, 1, "_ZTV18objArrayKlassKlass",
"_ZN18objArrayKlassKlass19oop_adjust_pointersEP7oopDesc",
&callbackForAdjustPtr),
HOOK_FUNC(adj, 2, "_ZTV15arrayKlassKlass",
"_ZN15arrayKlassKlass19oop_adjust_pointersEP7oopDesc",
&callbackForAdjustPtr),
HOOK_FUNC(adj, 3, "_ZTV20MoveAndUpdateClosure",
#ifdef __LP64__
"_ZN20MoveAndUpdateClosure7do_addrEP8HeapWordm",
#else
"_ZN20MoveAndUpdateClosure7do_addrEP8HeapWordj",
#endif
&callbackForDoAddr),
HOOK_FUNC(adj, 4, "_ZTV17UpdateOnlyClosure",
#ifdef __LP64__
"_ZN17UpdateOnlyClosure7do_addrEP8HeapWordm",
#else
"_ZN17UpdateOnlyClosure7do_addrEP8HeapWordj",
#endif
&callbackForDoAddr),
HOOK_FUNC(adj, 5, "_ZTV18instanceKlassKlass",
"_ZN18instanceKlassKlass19oop_update_"
"pointersEP20ParCompactionManagerP7oopDesc",
&callbackForUpdatePtr),
HOOK_FUNC(adj, 6, "_ZTV18objArrayKlassKlass",
"_ZN18objArrayKlassKlass19oop_update_"
"pointersEP20ParCompactionManagerP7oopDesc",
&callbackForUpdatePtr),
HOOK_FUNC(adj, 7, "_ZTV15arrayKlassKlass",
"_ZN15arrayKlassKlass19oop_update_"
"pointersEP20ParCompactionManagerP7oopDesc",
&callbackForUpdatePtr),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook change and adjust oop with GC.
*/
THookFunctionInfo *adj_hook = default_adj_hook;
/*!
* \brief Pointer of hook oop iterate with JVMTI HeapOverIterate for default.
*/
THookFunctionInfo default_jvmti_hook[] = {
HOOK_FUNC(jvmti, 0, "_ZTV28IterateOverHeapObjectClosure",
"_ZN28IterateOverHeapObjectClosure9do_objectEP7oopDesc",
&callbackForJvmtiIterate),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook oop iterate with JVMTI HeapOverIterate.
*/
THookFunctionInfo *jvmti_hook = default_jvmti_hook;
/*!
* \brief Pointer of hook inner GC function for default.
*/
THookFunctionInfo default_innerStart_hook[] = {
HOOK_FUNC(innerStart, 0, "_ZTV20ParallelScavengeHeap",
"_ZN20ParallelScavengeHeap31accumulate_statistics_all_tlabsEv",
&callbackForInnerGCStart),
HOOK_FUNC(innerStart, 1, "_ZTV13CollectedHeap",
"_ZN13CollectedHeap31accumulate_statistics_all_tlabsEv",
&callbackForInnerGCStart),
HOOK_FUNC(innerStart, 2, "_ZTV16GenCollectedHeap",
"_ZN16GenCollectedHeap11gc_prologueEb", &callbackForInnerGCStart),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook inner GC function.
*/
THookFunctionInfo *innerStart_hook = default_innerStart_hook;
/*!
* \brief Pointer of WatcherThread hook.
*/
THookFunctionInfo default_watcherThread_hook[] = {
HOOK_FUNC(watcherThread, 0, "_ZTV13WatcherThread",
"_ZN13WatcherThread3runEv", &callbackForWatcherThreadRun),
HOOK_FUNC_END};
/*!
* \brief Pointer of hook WatcherThread.
*/
THookFunctionInfo *watcherThread_hook = default_watcherThread_hook;
/* Event callback for outter. */
/*!
* \brief Callback function for general GC function hooking.
*/
THeapObjectCallback gcCallbackFunc = NULL;
/*!
* \brief Callback function for CMSGC function hooking.
*/
THeapObjectCallback cmsCallbackFunc = NULL;
/*!
* \brief Callback function for JVMTI iterate hooking.
*/
THeapObjectCallback jvmtiIteCallbackFunc = NULL;
/*!
* \brief Callback function for adjust oop function hooking.
*/
TKlassAdjustCallback adjustCallbackFunc = NULL;
/*!
* \brief Callback function for finished G1GC.
*/
TCommonCallback g1FinishCallbackFunc = NULL;
/*!
* \brief Callback function for interrupt GC.
*/
TCommonCallback gcInterruptCallbackFunc = NULL;
/* Variable for inner work. */
/*!
* \brief flag of snapshot with CMS phase.
*/
bool needSnapShotByCMSPhase = false;
/*!
* \brief flag of GC hooking enable.
*/
bool isEnableGCHooking = false;
/*!
* \brief flag of JVMTI hooking enable.
*/
bool isEnableJvmtiHooking = false;
/*!
* \brief Pthread key to store old klassOop.
*/
pthread_key_t oldKlassOopKey;
/*!
* \brief flag of inner GC function is called many times.
*/
bool isInvokeGCManyTimes = false;
/*!
* \brief Flag of called parallel gc on using CMS gc.
*/
bool isInvokedParallelGC = false;
/* Function prototypes */
/****************************************************************/
void pThreadKeyDestructor(void *data);
bool setupForParallel(void);
bool setupForParallelOld(void);
bool setupForCMS(void);
bool setupForG1(size_t maxMemSize);
/* Utility functions for overriding */
/****************************************************************/
/*!
* \brief Initialize override functions.
* \return Process result.
*/
bool initOverrider(void) {
bool result = true;
try {
if (TVMVariables::getInstance()->getUseG1()) {
if (unlikely(!jvmInfo->isAfterCR7046558())) {
/* Heapstats agent is unsupported G1GC on JDK6. */
logger->printCritMsg("G1GC isn't supported in this version.");
logger->printCritMsg("You should use HotSpot >= 22.0-b03");
throw 1;
}
if (conf->TimerInterval()->get() > 0) {
logger->printWarnMsg(
"Interval SnapShot is not supported with G1GC. Turn off.");
conf->TimerInterval()->set(0);
}
if (conf->TriggerOnDump()->get()) {
logger->printWarnMsg(
"SnapShot trigger on dump request is not supported with G1GC. "
"Turn off.");
conf->TriggerOnDump()->set(false);
}
}
/* Create pthred key for klassOop. */
if (unlikely(pthread_key_create(&oldKlassOopKey, pThreadKeyDestructor) !=
0)) {
logger->printCritMsg("Cannot create pthread key.");
throw 2;
}
} catch (...) {
result = false;
}
return result;
}
/*!
* \brief Cleanup override functions.
*/
void cleanupOverrider(void) {
/* Cleanup. */
TVMVariables *vmVal = TVMVariables::getInstance();
if (vmVal->getUseCMS() || vmVal->getUseG1()) {
delete checkObjectMap;
checkObjectMap = NULL;
}
symFinder = NULL;
pthread_key_delete(oldKlassOopKey);
}
/*!
* \brief Callback for pthread key destructor.
* \param data [in] Data related to pthread key.
*/
void pThreadKeyDestructor(void *data) {
if (likely(data != NULL)) {
/* Cleanup allocated memory on "callbackForDoAddr". */
free(data);
}
}
/*!
* \brief Check CMS garbage collector state.
* \param state [in] State of CMS garbage collector.
* \param needSnapShot [out] Is need snapshot now.
* \return CMS collector state.
* \warning Please don't forget call on JVM death.
*/
int checkCMSState(TGCState state, bool *needSnapShot) {
/* Sanity check. */
if (unlikely(needSnapShot == NULL)) {
logger->printCritMsg("Illegal paramter!");
return -1;
}
TVMVariables *vmVal = TVMVariables::getInstance();
static int cmsStateAtStart;
*needSnapShot = false;
switch (state) {
case gcStart:
/* Call on JVMTI GC start. */
if (vmVal->getCMS_collectorState() <= CMS_INITIALMARKING) {
/* Set stored flag of passed sweep phase. */
*needSnapShot = needSnapShotByCMSPhase;
needSnapShotByCMSPhase = false;
} else if (vmVal->getCMS_collectorState() == CMS_FINALMARKING) {
checkObjectMap->clear();
/* switch hooking for CMS new generation. */
switchOverrideFunction(cms_new_hook, true);
}
cmsStateAtStart = vmVal->getCMS_collectorState();
isInvokedParallelGC = false;
break;
case gcFinish:
/* Call on JVMTI GC finished. */
switch (vmVal->getCMS_collectorState()) {
case CMS_MARKING:
/* CMS marking phase. */
break;
case CMS_SWEEPING:
/* CMS sweep phase. */
needSnapShotByCMSPhase = true;
break;
default:
/* If called parallel gc. */
if (isInvokedParallelGC) {
/* GC invoke by user or service without CMS. */
(*needSnapShot) = true;
needSnapShotByCMSPhase = false;
break;
}
}
/* If enable cms new gen hook. */
if (cmsStateAtStart == CMS_FINALMARKING) {
/* switch hooking for CMS new generation. */
switchOverrideFunction(cms_new_hook, false);
}
break;
case gcLast:
/* Call on JVM is terminating. */
/* Set stored flag of passed sweep phase. */
*needSnapShot = needSnapShotByCMSPhase;
needSnapShotByCMSPhase = false;
break;
default:
/* Not reached here. */
logger->printWarnMsg("Illegal GC state.");
}
return vmVal->getCMS_collectorState();
}
/*!
* \brief Is marked object on CMS bitmap.
* \param oop [in] Java heap object(Inner class format).
* \return Value is true, if object is marked.
*/
inline bool isMarkedObject(void *oop) {
TVMVariables *vmVal = TVMVariables::getInstance();
size_t idx = (((ptrdiff_t)oop - (ptrdiff_t)vmVal->getCmsBitMap_startWord()) >>
((unsigned)vmVal->getLogHeapWordSize() +
(unsigned)vmVal->getCmsBitMap_shifter()));
size_t mask = (size_t)1 << (idx & vmVal->getBitsPerWordMask());
return (((size_t *)vmVal->getCmsBitMap_startAddr())[(
idx >> vmVal->getLogBitsPerWord())] &
mask) != 0;
}
/*!
* \brief Callback function for klassOop.
* \param oldOop [in] Old java class object.
* \param newOop [in] New java class object.
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
inline void callbackForAdjustKlass(void *oldOop, void *newOop) {
if (likely(adjustCallbackFunc != NULL)) {
adjustCallbackFunc(oldOop, newOop);
}
}
/* Override controller. */
/****************************************************************/
/*!
* \brief Setup hooking.
* \warning Please this function call at after Agent_OnLoad.
* \param funcOnGC [in] Pointer of GC callback function.
* \param funcOnCMS [in] Pointer of CMSGC callback function.
* \param funcOnJVMTI [in] Pointer of JVMTI callback function.
* \param funcOnAdjust [in] Pointer of adjust class callback function.
* \param funcOnG1GC [in] Pointer of event callback on G1GC finished.
* \param maxMemSize [in] Allocatable maximum memory size of JVM.
* \return Process result.
*/
bool setupHook(THeapObjectCallback funcOnGC, THeapObjectCallback funcOnCMS,
THeapObjectCallback funcOnJVMTI,
TKlassAdjustCallback funcOnAdjust, TCommonCallback funcOnG1GC,
size_t maxMemSize) {
/* Set function. */
gcCallbackFunc = funcOnGC;
cmsCallbackFunc = funcOnCMS;
jvmtiIteCallbackFunc = funcOnJVMTI;
adjustCallbackFunc = funcOnAdjust;
g1FinishCallbackFunc = funcOnG1GC;
/* Setup for WatcherThread. */
if (unlikely(!setupOverrideFunction(watcherThread_hook))) {
logger->printWarnMsg("Cannot setup to override WatcherThread");
return false;
}
switchOverrideFunction(watcherThread_hook, true);
/* Setup for JVMTI. */
if (unlikely(!setupOverrideFunction(jvmti_hook))) {
logger->printWarnMsg("Cannot setup to override JVMTI GC");
return false;
}
/* Setup for pointer adjustment. */
if (!jvmInfo->isAfterCR6964458()) {
if (unlikely(!setupOverrideFunction(adj_hook))) {
logger->printWarnMsg("Cannot setup to override Class adjuster");
return false;
}
}
/* Setup by using GC type. */
/* Setup parallel GC and GC by user. */
if (unlikely(!setupForParallel())) {
return false;
}
/* Setup for inner GC function. */
if (unlikely(!setupOverrideFunction(innerStart_hook))) {
logger->printWarnMsg("Cannot setup to override innner-hook functions.");
return false;
}
TVMVariables *vmVal = TVMVariables::getInstance();
/* Setup each GC type. */
bool result = vmVal->getUseParallel();
if (vmVal->getUseParOld()) {
result &= setupForParallelOld();
} else if (vmVal->getUseCMS()) {
result &= setupForCMS();
} else if (vmVal->getUseG1()) {
result &= setupForG1(maxMemSize);
}
return result;
}
/*!
* \brief Setup override funtion.
* \param list [in] List of hooking information.
* \return Process result.
*/
bool setupOverrideFunction(THookFunctionInfo *list) {
/* Variable for list pointer. */
THookFunctionInfo *arr = list;
/* Search class and function symbol. */
for (int i = 0; arr->vtableSymbol != NULL; i++) {
/* Search class(vtable) symbol. */
arr->vtable = (void **)symFinder->findSymbol(arr->vtableSymbol);
if (unlikely(arr->vtable == NULL)) {
logger->printCritMsg("%s not found.", arr->vtableSymbol);
return false;
}
/* Search function symbol. */
arr->originalFunc = symFinder->findSymbol(arr->funcSymbol);
if (unlikely(arr->originalFunc == NULL)) {
logger->printCritMsg("%s not found.", arr->funcSymbol);
return false;
}
/* Set function pointers to gobal variables through THookFunctionInfo. */
*arr->originalFuncPtr = arr->originalFunc;
*arr->enterFuncPtr = arr->enterFunc;
/* Move next list item. */
arr++;
}
return true;
}
/*!
* \brief Setup GC hooking for parallel.
* \return Process result.
*/
bool setupForParallel(void) {
SELECT_HOOK_FUNCS(par);
if (unlikely(!setupOverrideFunction(par_hook))) {
logger->printCritMsg("Cannot setup to override ParallelGC.");
return false;
}
return true;
}
/*!
* \brief Setup GC hooking for parallel old GC.
* \return Process result.
*/
bool setupForParallelOld(void) {
SELECT_HOOK_FUNCS(parOld);
if (unlikely(!setupOverrideFunction(parOld_hook))) {
logger->printCritMsg("Cannot setup to override ParallelOldGC.");
return false;
}
return true;
}
/*!
* \brief Setup GC hooking for CMSGC.
* \return Process result.
*/
bool setupForCMS(void) {
SELECT_HOOK_FUNCS(cms_new);
TVMVariables *vmVal = TVMVariables::getInstance();
const void *startAddr = vmVal->getYoungGenStartAddr();
const size_t youngSize = vmVal->getYoungGenSize();
/* Create bitmap to check object collected flag. */
#ifdef AVX
checkObjectMap = new TAVXBitMapMarker(startAddr, youngSize);
#elif(defined SSE2) || (defined SSE4)
checkObjectMap = new TSSE2BitMapMarker(startAddr, youngSize);
#elif PROCESSOR_ARCH == X86
checkObjectMap = new TX86BitMapMarker(startAddr, youngSize);
#elif PROCESSOR_ARCH == ARM
#ifdef NEON
checkObjectMap = new TNeonBitMapMarker(startAddr, youngSize);
#else
checkObjectMap = new TARMBitMapMarker(startAddr, youngSize);
#endif
#endif
if (unlikely(!setupOverrideFunction(cms_new_hook))) {
logger->printCritMsg("Cannot setup to override CMS_new (ParNew GC).");
return false;
}
if (unlikely(!setupOverrideFunction(cms_sweep_hook))) {
logger->printCritMsg(
"Cannot setup to override CMS_sweep (concurrent sweep).");
return false;
}
return true;
}
/*!
* \brief Setup GC hooking for G1GC
* \return Process result.
*/
bool setupForG1(size_t maxMemSize) {
TVMVariables *vmVal = TVMVariables::getInstance();
SELECT_HOOK_FUNCS(g1);
try {
/* Sanity check. */
if (unlikely(maxMemSize <= 0)) {
logger->printCritMsg("G1 memory size should be > 1.");
throw 1;
}
/* Create bitmap to check object collected flag. */
#ifdef AVX
checkObjectMap = new TAVXBitMapMarker(vmVal->getG1StartAddr(), maxMemSize);
#elif(defined SSE2) || (defined SSE4)
checkObjectMap = new TSSE2BitMapMarker(vmVal->getG1StartAddr(), maxMemSize);
#elif PROCESSOR_ARCH == X86
checkObjectMap = new TX86BitMapMarker(vmVal->getG1StartAddr(), maxMemSize);
#elif PROCESSOR_ARCH == ARM
#ifdef NEON
checkObjectMap = new TNeonBitMapMarker(vmVal->getG1StartAddr(), maxMemSize);
#else
checkObjectMap = new TARMBitMapMarker(vmVal->getG1StartAddr(), maxMemSize);
#endif
#endif
} catch (...) {
logger->printCritMsg("Cannot create object marker bitmap for G1.");
return false;
}
/* If failure getting function information. */
if (unlikely(!setupOverrideFunction(g1_hook) ||
!setupOverrideFunction(g1Event_hook))) {
logger->printCritMsg("Cannot setup to override G1GC.");
return false;
}
return true;
}
/*!
* \brief Setup hooking for inner GC event.
* \warning Please this function call at after Agent_OnLoad.
* \param enableHook [in] Flag of enable hooking to function.
* \param interruptEvent [in] Event callback on many times GC interupt.
* \return Process result.
*/
bool setupHookForInnerGCEvent(bool enableHook, TCommonCallback interruptEvent) {
isInvokeGCManyTimes = false;
gcInterruptCallbackFunc = interruptEvent;
return switchOverrideFunction(innerStart_hook, enableHook);
}
/*!
* \brief Setting GC hooking enable.
* \param enable [in] Is GC hook enable.
* \return Process result.
*/
bool setGCHookState(bool enable) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* Sanity check. */
if (unlikely(isEnableGCHooking == enable)) {
/* Already set state. */
return true;
}
/* Change state. */
isEnableGCHooking = enable;
/* Setting hooking target. */
THookFunctionInfo *list = NULL;
if (vmVal->getUseParOld()) {
list = parOld_hook;
} else if (vmVal->getUseCMS()) {
/* Switch CMS hooking at new generation. */
switchOverrideFunction(cms_new_hook, enable);
list = cms_sweep_hook;
checkObjectMap->clear();
} else if (vmVal->getUseG1()) {
/* Switch G1GC event hooking. */
switchOverrideFunction(g1Event_hook, enable);
list = g1_hook;
checkObjectMap->clear();
}
/* Switch common hooking. */
if (unlikely(!switchOverrideFunction(par_hook, enable))) {
logger->printCritMsg("Cannot switch override (ParallelGC)");
return false;
}
/* Switch adjust pointer hooking. */
if (!jvmInfo->isAfterCR6964458()) {
if (unlikely(!switchOverrideFunction(adj_hook, enable))) {
logger->printCritMsg("Cannot switch override (Class adjuster)");
return false;
}
}
if (list != NULL) {
/* Switch hooking for each GC type. */
if (unlikely(!switchOverrideFunction(list, enable))) {
logger->printCritMsg("Cannot switch override GC");
return false;
}
}
return true;
}
/*!
* \brief Setting JVMTI hooking enable.
* \param enable [in] Is JVMTI hook enable.
* \return Process result.
*/
bool setJvmtiHookState(bool enable) {
/* Sanity check. */
if (unlikely(isEnableJvmtiHooking == enable)) {
/* Already set state. */
return true;
}
/* Change state. */
isEnableJvmtiHooking = enable;
/* Switch JVMTI hooking. */
if (unlikely(!switchOverrideFunction(jvmti_hook, enable))) {
logger->printCritMsg("Cannot switch override JVMTI GC");
return false;
}
return true;
}
/*!
* \brief Switching override function enable state.
* \param list [in] List of hooking information.
* \param enable [in] Enable of override function.
* \return Process result.
*/
bool switchOverrideFunction(THookFunctionInfo *list, bool enable) {
/* Variable for list pointer. */
THookFunctionInfo *arr = list;
/* Variable for list item count. */
int listCnt = 0;
/* Variable for succeed count. */
int doneCnt = 0;
/* Search class and function symbol. */
for (; arr->originalFunc != NULL; listCnt++) {
/* Variable for store vtable. */
void **vtable = arr->vtable;
/* Variable for store function pointer. */
void *targetFunc = NULL;
void *destFunc = NULL;
/* Setting swap target and swap dest. */
if (enable) {
targetFunc = arr->originalFunc;
destFunc = arr->overrideFunc;
} else {
targetFunc = arr->overrideFunc;
destFunc = arr->originalFunc;
}
if (unlikely(vtable == NULL || targetFunc == NULL || destFunc == NULL)) {
/* Skip illegal. */
arr++;
continue;
}
const int VTABLE_SKIP_LIMIT = 1000;
for (int i = 0; i < VTABLE_SKIP_LIMIT && *vtable == NULL; i++) {
/* Skip null entry. */
vtable++;
}
while (*vtable != NULL) {
/* If target function. */
if (*vtable == targetFunc) {
if (unlikely(!arr->isVTableWritable)) {
/* Avoid memory protection for vtable
* libstdc++ may remove write permission from vtable
* http://gcc.gnu.org/ml/gcc-patches/2012-11/txt00001.txt
*/
ptrdiff_t start_page = (ptrdiff_t)vtable & ~(systemPageSize - 1);
ptrdiff_t end_page =
((ptrdiff_t)vtable + sizeof(void *)) & ~(systemPageSize - 1);
size_t len = systemPageSize + (end_page - start_page);
mprotect((void *)start_page, len, PROT_READ | PROT_WRITE);
arr->isVTableWritable = true;
}
*vtable = destFunc;
doneCnt++;
break;
}
/* Move next vtable entry. */
vtable++;
}
/* Move next list item. */
arr++;
}
return (listCnt == doneCnt);
}
/* Callback functions. */
/****************************************************************/
/*!
* \brief Callback function for parallel GC and user's GC.<br>
* E.g. System.gc() in java code, JVMTI and etc..
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
inline void callbackForParallelInternal(void *oop) {
/* Invoke callback by GC. */
gcCallbackFunc(oop, NULL);
isInvokedParallelGC = true;
}
/*!
* \brief Callback function for parallel GC and user's GC.<br>
* E.g. System.gc() in java code, JVMTI and etc..
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForParallel(void *oop) {
callbackForParallelInternal(oop);
}
/*!
* \brief Callback function for parallel GC and user's GC.<br>
* E.g. System.gc() in java code, JVMTI and etc..
* This function checks markOop value.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForParallelWithMarkCheck(void *oop) {
TVMVariables *vmVal = TVMVariables::getInstance();
unsigned long markOop = *(ptrdiff_t *)incAddress(oop,
vmVal->getOfsMarkAtOop());
uint64_t markValue = markOop & vmVal->getLockMaskInPlaceMarkOop();
if (markValue == vmVal->getMarkedValue()) {
callbackForParallelInternal(oop);
}
}
/*!
* \brief Callback function for parallel Old GC.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForParOld(void *oop) {
/* Invoke callback by GC. */
gcCallbackFunc(oop, NULL);
isInvokedParallelGC = true;
}
/*!
* \brief Callback function for OopClosure::do_oop(oop *).<br>
* This function is targeted for G1ParScanAndMarkExtRootClosure.
* (initial-mark for G1)
* \param oop [in] Java heap object(OopDesc format).
*/
void callbackForDoOop(void **oop) {
if ((oop == NULL) || (*oop == NULL) || is_in_permanent(collectedHeap, *oop)) {
return;
}
if ((checkObjectMap != NULL) && checkObjectMap->checkAndMark(*oop)) {
/* Object is already collected by G1GC collector. */
return;
}
/* Invoke snapshot callback. */
gcCallbackFunc(*oop, NULL);
}
/*!
* \brief Callback function for OopClosure::do_oop(oop *).<br>
* This function checks whether the oop is marked.
* \param oop [in] Java heap object(OopDesc format).
*/
void callbackForDoOopWithMarkCheck(void **oop) {
if ((oop == NULL) || (*oop == NULL) || is_in_permanent(collectedHeap, *oop)) {
return;
}
TVMVariables *vmVal = TVMVariables::getInstance();
unsigned long markOop = *(ptrdiff_t *)incAddress(oop,
vmVal->getOfsMarkAtOop());
uint64_t markValue = markOop & vmVal->getLockMaskInPlaceMarkOop();
if (markValue == vmVal->getMarkedValue()) {
gcCallbackFunc(*oop, NULL);
}
}
/*!
* \brief Callback function for OopClosure::do_oop(narrowOop *).<br>
* This function is targeted for G1ParScanAndMarkExtRootClosure.
* (initial-mark for G1)
* \param oop [in] Java heap object(OopDesc format).
*/
void callbackForDoNarrowOop(unsigned int *narrowOop) {
void *oop = getWideOop(*narrowOop);
callbackForDoOop(&oop);
}
/*!
* \brief Callback function for OopClosure::do_oop(narrowOop *).<br>
* This function checks whether the oop is marked.
* \param oop [in] Java heap object(OopDesc format).
*/
void callbackForDoNarrowOopWithMarkCheck(unsigned int *narrowOop) {
void *oop = getWideOop(*narrowOop);
callbackForDoOopWithMarkCheck(&oop);
}
/*!
* \brief Callback function for CMS GC and G1 GC.<br>
* This function is targeted for Young Gen only.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
* \sa CMSParRemarkTask::do_young_space_rescan()<br>
* ContiguousSpace::par_oop_iterate()
*/
void callbackForIterate(void *oop) {
TVMVariables *vmVal = TVMVariables::getInstance();
if (vmVal->getUseCMS()) {
/* If object is in CMS gen. */
if ((ptrdiff_t)oop >= (ptrdiff_t)vmVal->getCmsBitMap_startWord()) {
/* Skip. because collect object in CMS gen by callbackForSweep. */
return;
}
if (checkObjectMap->checkAndMark(oop)) {
/* Object is in young gen and already marked. */
return;
}
/* Invoke callback by CMS GC. */
cmsCallbackFunc(oop, NULL);
} else if (vmVal->getUseG1()) {
if (checkObjectMap->checkAndMark(oop)) {
/* Object is already collected by G1GC collector. */
return;
}
/* Invoke callback by GC. */
gcCallbackFunc(oop, NULL);
isInvokedParallelGC = true;
}
}
/*!
* \brief Callback function for CMS sweep.<br>
* This function is targeted for CMS Gen only.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForSweep(void *oop) {
/* If object isn't GC target. */
if (likely(isMarkedObject(oop))) {
/* Invoke callback by CMS GC. */
cmsCallbackFunc(oop, NULL);
}
}
/*!
* \brief Callback function for oop_adjust_pointers.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForAdjustPtr(void *oop) {
/* Get new class oop. */
void *newOop = getForwardAddr(oop);
if (newOop != NULL) {
/* Invoke callback. */
callbackForAdjustKlass(oop, newOop);
}
}
/*!
* \brief Callback function for do_addr.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForDoAddr(void *oop) {
/* Get store memory. */
void **oldOop = (void **)pthread_getspecific(oldKlassOopKey);
if (unlikely(oldOop == NULL)) {
/* Allocate and set store memory. */
oldOop = (void **)malloc(sizeof(void *));
pthread_setspecific(oldKlassOopKey, oldOop);
}
/* Store old klassOop. */
if (likely(oldOop != NULL)) {
(*oldOop) = oop;
}
}
/*!
* \brief Callback function for oop_update_pointers.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForUpdatePtr(void *oop) {
/* Get old class oop. */
void **oldOop = (void **)pthread_getspecific(oldKlassOopKey);
if (likely(oldOop != NULL && (*oldOop) != NULL)) {
/* Invoke callback. */
callbackForAdjustKlass((*oldOop), oop);
/* Cleanup old data. */
(*oldOop) = NULL;
}
}
/*!
* \brief Callback function for snapshot with data dump or interval.
* \param oop [in] Java heap object(OopDesc format).
* \warning Param "oop" isn't usable for JVMTI and JNI.
*/
void callbackForJvmtiIterate(void *oop) {
/* Invoke callback by JVMTI. */
jvmtiIteCallbackFunc(oop, NULL);
}
/*!
* \brief Callback function for before G1 GC cleanup.
* \param thisptr [in] this pointer of caller C++ instance.
*/
void callbackForG1Cleanup(void *thisptr) {
if (likely(g1FinishCallbackFunc != NULL)) {
/* Invoke callback. */
g1FinishCallbackFunc();
}
/* Clear bitmap. */
checkObjectMap->clear();
}
/*!
* \brief Callback function for before System.gc() on using G1GC.
* \param thisptr [in] this pointer of caller C++ instance.
*/
void callbackForG1Full(void *thisptr) {
/*
* Disable G1 callback function:
* OopClosure for typeArrayKlass is called by G1 FullCollection.
*/
if (!jvmInfo->isAfterJDK10()) {
switchOverrideFunction(g1_hook, false);
}
/* Discard existed snapshot data */
clearCurrentSnapShot();
checkObjectMap->clear();
}
/*!
* \brief Callback function for after System.gc() on using G1GC.
* \param thisptr [in] this pointer of caller C++ instance.
*/
void callbackForG1FullReturn(void *thisptr) {
/* Restore G1 callback. */
if (!jvmInfo->isAfterJDK10()) {
switchOverrideFunction(g1_hook, true);
}
if (likely(g1FinishCallbackFunc != NULL)) {
/* Invoke callback. */
g1FinishCallbackFunc();
}
/* Clear bitmap. */
checkObjectMap->clear();
}
/*!
* \brief Callback function for starting inner GC.
*/
void callbackForInnerGCStart(void) {
/* If call GC function more one. */
if (unlikely(isInvokeGCManyTimes)) {
/* Invoke GC interrupt callback. */
if (likely(gcInterruptCallbackFunc != NULL)) {
gcInterruptCallbackFunc();
}
} else {
/* Update state. */
isInvokeGCManyTimes = true;
}
/* Get current GCCause. */
jvmInfo->loadGCCause();
}
/*!
* \brief Callback function for WatcherThread.
*/
void callbackForWatcherThreadRun(void) { jvmInfo->detectDelayInfoAddress(); }
| 65,189
|
C++
|
.cpp
| 1,711
| 32.19287
| 103
| 0.688826
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,003
|
classContainer.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/classContainer.cpp
|
/*!
* \file classContainer.cpp
* \brief This file is used to add up using size every class.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <fcntl.h>
#include "globals.hpp"
#include "vmFunctions.hpp"
#include "classContainer.hpp"
/*!
* \brief SNMP variable Identifier of raise heap-alert date.
*/
static oid OID_ALERT_DATE[] = {SNMP_OID_HEAPALERT, 1};
/*!
* \brief SNMP variable Identifier of class-name is cause of heap-alert.
*/
static oid OID_ALERT_CLS_NAME[] = {SNMP_OID_HEAPALERT, 2};
/*!
* \brief SNMP variable Identifier of kind of class-size.
*/
static oid OID_ALERT_SIZE_KIND[] = {SNMP_OID_HEAPALERT, 3};
/*!
* \brief SNMP variable Identifier of class-size.
*/
static oid OID_ALERT_CLS_SIZE[] = {SNMP_OID_HEAPALERT, 4};
/*!
* \brief SNMP variable Identifier of instance count.
*/
static oid OID_ALERT_CLS_COUNT[] = {SNMP_OID_HEAPALERT, 5};
/*!
* \brief SNMP variable Identifier of raise Java heap alert date.
*/
static oid OID_JAVAHEAPALERT_DATE[] = {SNMP_OID_JAVAHEAPALERT, 1};
/*!
* \brief SNMP variable Identifier of Java heap usage.
*/
static oid OID_JAVAHEAPALERT_USAGE[] = {SNMP_OID_JAVAHEAPALERT, 2};
/*!
* \brief SNMP variable Identifier of Java heap max capacity.
*/
static oid OID_JAVAHEAPALERT_MAX_CAPACITY[] = {SNMP_OID_JAVAHEAPALERT, 3};
/*!
* \brief SNMP variable Identifier of raise metaspace alert date.
*/
static oid OID_METASPACEALERT_DATE[] = {SNMP_OID_METASPACEALERT, 1};
/*!
* \brief SNMP variable Identifier of Java metaspace usage.
*/
static oid OID_METASPACEALERT_USAGE[] = {SNMP_OID_METASPACEALERT, 2};
/*!
* \brief SNMP variable Identifier of Java heap max capacity.
*/
static oid OID_METASPACEALERT_MAX_CAPACITY[] = {SNMP_OID_METASPACEALERT, 3};
/*!
* \brief String of USAGE order.
*/
static char ORDER_USAGE[6] = "USAGE";
static TClassInfoSet unloadedList;
/*!
* \briefString of DELTA order.
*/
static char ORDER_DELTA[6] = "DELTA";
/*!
* \brief TClassContainer constructor.
*/
TClassContainer::TClassContainer(void) : classMap(), updatedClassList() {
/* Create trap sender. */
pSender = conf->SnmpSend()->get() ? new TTrapSender() : NULL;
}
/*!
* \brief TClassContainer destructor.
*/
TClassContainer::~TClassContainer(void) {
/* Cleanup class information. */
this->allClear();
/* Cleanup instances. */
delete pSender;
}
/*!
* \brief Append new-class to container.
* \param klassOop [in] New class oop.
* \return New-class data.
*/
TObjectData *TClassContainer::pushNewClass(void *klassOop) {
TObjectData *cur = NULL;
/* Class info setting. */
cur = (TObjectData *)calloc(1, sizeof(TObjectData));
/* If failure allocate. */
if (unlikely(cur == NULL)) {
/* Adding empty to list is deny. */
logger->printWarnMsg("Couldn't allocate counter memory!");
return NULL;
}
cur->tag = (uintptr_t)cur;
cur->className = getClassName(getKlassFromKlassOop(klassOop));
/* If failure getting class name. */
if (unlikely(cur->className == NULL)) {
/* Adding empty to list is deny. */
logger->printWarnMsg("Couldn't get class name!");
free(cur);
return NULL;
}
cur->classNameLen = strlen(cur->className);
cur->oopType = getClassType(cur->className);
void *clsLoader = getClassLoader(klassOop, cur->oopType);
TObjectData *clsLoaderData = NULL;
/* If class loader isn't system bootstrap class loader. */
if (clsLoader != NULL) {
void *clsLoaderKlsOop = getKlassOopFromOop(clsLoader);
if (clsLoaderKlsOop != NULL) {
/* Search classloader's class. */
clsLoaderData = this->findClass(clsLoaderKlsOop);
if (unlikely(clsLoaderData == NULL)) {
/* Register classloader's class. */
clsLoaderData = this->pushNewClass(clsLoaderKlsOop);
}
}
}
cur->clsLoaderTag = (clsLoaderData != NULL) ? clsLoaderData->tag : 0;
cur->clsLoaderId = (uintptr_t)clsLoader;
/* Chain setting. */
cur->klassOop = klassOop;
TObjectData *result = this->pushNewClass(klassOop, cur);
if (unlikely(result != cur)) {
free(cur->className);
free(cur);
}
return result;
}
/*!
* \brief Append new-class to container.
* \param klassOop [in] New class oop.
* \param objData [in] Add new class data.
* \return New-class data.<br />
* This value isn't equal param "objData",
* if already registered equivalence class.
*/
TObjectData *TClassContainer::pushNewClass(void *klassOop,
TObjectData *objData) {
/*
* Jvmti extension event "classUnload" is loose once in a while.
* The event forget callback occasionally when class unloading.
* So we need to check klassOop that was doubling.
*/
TClassMap::accessor acc;
if (!classMap.insert(acc, std::make_pair(klassOop, objData))) {
TObjectData *expectData = acc->second;
if (likely(expectData != NULL)) {
/* If adding class data for another class is already exists. */
if (unlikely((expectData->className == NULL) ||
(strcmp(objData->className, expectData->className) != 0) ||
(objData->clsLoaderId != expectData->clsLoaderId))) {
acc->second = objData;
unloadedList.push(expectData);
}
}
}
return acc->second;
}
/*!
* \brief Remove class from container.
* \param target [in] Remove class data.
*/
void TClassContainer::removeClass(TObjectData *target) {
classMap.erase(target->klassOop);
}
/*!
* \brief Remove all-class from container.
* This function will be called from d'tor of TClassContainer.
*/
void TClassContainer::allClear(void) {
/* Add all TObjectData pointers in container map to unloadedList */
for (auto cur = classMap.begin(); cur != classMap.end(); cur++) {
TObjectData *objData = cur->second;
free(objData->className);
free(objData);
}
}
/*!
* \brief Comparator for sort by usage order.
* \param *arg1 [in] Compare target A.
* \param *arg2 [in] Compare target B.
* \return Compare result.
*/
int HeapUsageCmp(const void *arg1, const void *arg2) {
jlong cmp = ((THeapDelta *)arg2)->usage - ((THeapDelta *)arg1)->usage;
if (cmp > 0) {
/* arg2 is bigger than arg1. */
return -1;
} else if (cmp < 0) {
/* arg1 is bigger than arg2. */
return 1;
} else {
/* arg2 is equal arg1. */
return 0;
}
}
/*!
* \brief Comparator for sort by delta order.
* \param *arg1 [in] Compare target A.
* \param *arg2 [in] Compare target B.
* \return Compare result.
*/
int HeapDeltaCmp(const void *arg1, const void *arg2) {
jlong cmp = ((THeapDelta *)arg2)->delta - ((THeapDelta *)arg1)->delta;
if (cmp > 0) {
/* arg2 is bigger than arg1. */
return -1;
} else if (cmp < 0) {
/* arg1 is bigger than arg2. */
return 1;
} else {
/* arg2 is equal arg1. */
return 0;
}
}
/*!
* \brief Output snapshot header information to file.
* \param fd [in] Target file descriptor.
* \param header [in] Snapshot file information.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
inline int writeHeader(const int fd, TSnapShotFileHeader header) {
int result = 0;
try {
/* Write header param before GC-cause. */
if (unlikely(write(fd, &header, offsetof(TSnapShotFileHeader, gcCause)) <
0)) {
throw 1;
}
/* Write GC-cause. */
if (unlikely(write(fd, header.gcCause, header.gcCauseLen) < 0)) {
throw 1;
}
/* Write header param after gccause. */
if (unlikely(write(fd, &header.FGCCount,
sizeof(TSnapShotFileHeader) -
offsetof(TSnapShotFileHeader, FGCCount)) < 0)) {
throw 1;
}
} catch (...) {
result = errno;
}
return result;
}
/*!
* \brief Send memory usage information by SNMP trap.
* \param pSender [in] SNMP trap sender.
* \param type [in] This alert type.
* \param occurred_time [in] Datetime of this alert is occurred.
* \param usage [in] Java heap usage.
* \param maxCapacity [in] Max capacity of Java heap.
* \return Process result.
*/
inline bool sendMemoryUsageAlertTrap(TTrapSender *pSender,
TMemoryUsageAlertType type,
jlong occurred_time, jlong usage,
jlong maxCapacity) {
/* Setting trap information. */
char paramStr[256];
const char *trapOID;
oid *alert_date;
oid *alert_usage;
oid *alert_capacity;
int oid_len = 0;
switch (type) {
case ALERT_JAVA_HEAP:
trapOID = OID_JAVAHEAPALERT;
alert_date = OID_JAVAHEAPALERT_DATE;
alert_usage = OID_JAVAHEAPALERT_USAGE;
alert_capacity = OID_JAVAHEAPALERT_MAX_CAPACITY;
oid_len = OID_LENGTH(OID_JAVAHEAPALERT_DATE);
break;
case ALERT_METASPACE:
trapOID = OID_METASPACEALERT;
alert_date = OID_METASPACEALERT_DATE;
alert_usage = OID_METASPACEALERT_USAGE;
alert_capacity = OID_METASPACEALERT_MAX_CAPACITY;
oid_len = OID_LENGTH(OID_METASPACEALERT_DATE);
break;
default:
logger->printCritMsg("Unknown alert type!");
return false;
}
bool result = true;
try {
/* Setting sysUpTime */
pSender->setSysUpTime();
/* Setting trapOID. */
pSender->setTrapOID(trapOID);
/* Set time of occurring this alert. */
sprintf(paramStr, JLONG_FORMAT_STR, occurred_time);
pSender->addValue(alert_date, oid_len, paramStr, SNMP_VAR_TYPE_COUNTER64);
/* Set java heap usage. */
sprintf(paramStr, JLONG_FORMAT_STR, usage);
pSender->addValue(alert_usage, oid_len, paramStr, SNMP_VAR_TYPE_COUNTER64);
/* Set max capacity of java heap. */
sprintf(paramStr, JLONG_FORMAT_STR, maxCapacity);
pSender->addValue(alert_capacity, oid_len, paramStr,
SNMP_VAR_TYPE_COUNTER64);
/* Send trap. */
if (unlikely(pSender->sendTrap() != SNMP_PROC_SUCCESS)) {
/* Clean up. */
pSender->clearValues();
throw 1;
}
} catch (...) {
result = false;
}
return result;
}
/*!
* \brief Send class information by SNMP trap.
* \param pSender [in] SNMP trap sender.
* \param heapUsage [in] Heap usage information of sending target class.
* \param className [in] Name of sending target class(JNI format string).
* \param instanceCount [in] Number of instance of sending target class.
* \return Process result.
*/
inline bool sendHeapAlertTrap(TTrapSender *pSender, THeapDelta heapUsage,
char *className, jlong instanceCount) {
/* Setting trap information. */
char paramStr[256];
/* Trap OID. */
char trapOID[50] = OID_HEAPALERT;
bool result = true;
try {
/* Setting sysUpTime */
pSender->setSysUpTime();
/* Setting trapOID. */
pSender->setTrapOID(trapOID);
if (conf->Order()->get() == USAGE) {
/* Set size kind. */
pSender->addValue(OID_ALERT_SIZE_KIND, OID_LENGTH(OID_ALERT_SIZE_KIND),
ORDER_USAGE, SNMP_VAR_TYPE_STRING);
sprintf(paramStr, JLONG_FORMAT_STR, heapUsage.usage);
} else {
/* Set size kind. */
pSender->addValue(OID_ALERT_SIZE_KIND, OID_LENGTH(OID_ALERT_SIZE_KIND),
ORDER_DELTA, SNMP_VAR_TYPE_STRING);
sprintf(paramStr, JLONG_FORMAT_STR, heapUsage.delta);
}
/* Set alert size. */
pSender->addValue(OID_ALERT_CLS_SIZE, OID_LENGTH(OID_ALERT_CLS_SIZE),
paramStr, SNMP_VAR_TYPE_COUNTER64);
/* Set now time. */
sprintf(paramStr, JLONG_FORMAT_STR, getNowTimeSec());
pSender->addValue(OID_ALERT_DATE, OID_LENGTH(OID_ALERT_DATE), paramStr,
SNMP_VAR_TYPE_COUNTER64);
/* Set class-name. */
pSender->addValue(OID_ALERT_CLS_NAME, OID_LENGTH(OID_ALERT_CLS_NAME),
className, SNMP_VAR_TYPE_STRING);
/* Set instance count. */
sprintf(paramStr, JLONG_FORMAT_STR, instanceCount);
pSender->addValue(OID_ALERT_CLS_COUNT, OID_LENGTH(OID_ALERT_CLS_COUNT),
paramStr, SNMP_VAR_TYPE_COUNTER64);
/* Send trap. */
if (unlikely(pSender->sendTrap() != SNMP_PROC_SUCCESS)) {
/* Clean up. */
pSender->clearValues();
throw 1;
}
} catch (...) {
result = false;
}
return result;
}
/*!
* \brief Output class information to file.
* \param fd [in] Target file descriptor.
* \param objData [in] The class information.
* \param cur [in] The class size counter.
* \param snapshot[in] SnapShot container.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
inline int writeClassData(const int fd, const TObjectData *objData,
TClassCounter *cur, TSnapShotContainer *snapshot) {
int result = 0;
/* Output class-information. */
try {
/* Output TObjectData.tag & TObjectData.classNameLen. */
if (unlikely(write(fd, objData, sizeof(jlong) << 1) < 0)) {
throw 1;
}
/* Output class name. */
if (unlikely(write(fd, objData->className, objData->classNameLen) < 0)) {
throw 1;
}
/* Output class loader's instance id and class tag. */
if (unlikely(write(fd, &objData->clsLoaderId, sizeof(jlong) << 1) < 0)) {
throw 1;
}
/* Output class instance count and heap usage. */
if (unlikely(write(fd, cur->counter, sizeof(TObjectCounter)) < 0)) {
throw 1;
}
/* Output children-class-information. */
if (conf->CollectRefTree()->get()) {
TChildClassCounter *childCounter = cur->child;
while (childCounter != NULL) {
/* If do output child class. */
if (likely(!conf->ReduceSnapShot()->get() ||
(childCounter->counter->total_size > 0))) {
/* Output child class tag. */
jlong childClsTag = (uintptr_t)childCounter->objData;
if (unlikely(write(fd, &childClsTag, sizeof(jlong)) < 0)) {
throw 1;
}
/* Output child class instance count and heap usage. */
if (unlikely(
write(fd, childCounter->counter, sizeof(TObjectCounter)) < 0)) {
throw 1;
}
}
/* Move next child class. */
childCounter = childCounter->next;
}
/* Output end-marker of children-class-information. */
const jlong childClsEndMarker[] = {-1, -1, -1};
if (unlikely(
write(fd, childClsEndMarker, sizeof(childClsEndMarker)) < 0)) {
throw 1;
}
}
} catch (...) {
result = errno;
}
return result;
}
/*!
* \brief Output all-class information to file.
* \param snapshot [in] Snapshot instance.
* \param rank [out] Sorted-class information.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TClassContainer::afterTakeSnapShot(TSnapShotContainer *snapshot,
TSorter<THeapDelta> **rank) {
/* Sanity check. */
if (unlikely(snapshot == NULL || rank == NULL)) {
return 0;
}
/* Copy header. */
TSnapShotFileHeader hdr;
memcpy(&hdr, (const void *)snapshot->getHeader(),
sizeof(TSnapShotFileHeader));
/* Set safepoint time. */
hdr.safepointTime = jvmInfo->getSafepointTime();
hdr.magicNumber |= EXTENDED_SAFEPOINT_TIME;
/* If java heap usage alert is enable. */
if (conf->getHeapAlertThreshold() > 0) {
jlong usage = hdr.newAreaSize + hdr.oldAreaSize;
if (usage > conf->getHeapAlertThreshold()) {
/* Raise alert. */
logger->printWarnMsg(
"ALERT: Java heap usage exceeded the threshold (%ld MB)",
usage / 1024 / 1024);
/* If need send trap. */
if (conf->SnmpSend()->get()) {
if (unlikely(!sendMemoryUsageAlertTrap(pSender, ALERT_JAVA_HEAP,
hdr.snapShotTime, usage,
jvmInfo->getMaxMemory()))) {
logger->printWarnMsg("SNMP trap send failed!");
}
}
}
}
/* If metaspace usage alert is enable. */
if ((conf->MetaspaceThreshold()->get() > 0) &&
((conf->MetaspaceThreshold()->get() * 1024 * 1024) <
hdr.metaspaceUsage)) {
const char *label = jvmInfo->isAfterCR6964458() ? "Metaspace" : "PermGen";
/* Raise alert. */
logger->printWarnMsg("ALERT: %s usage exceeded the threshold (%ld MB)",
label, hdr.metaspaceUsage / 1024 / 1024);
/* If need send trap. */
if (conf->SnmpSend()->get()) {
if (unlikely(!sendMemoryUsageAlertTrap(
pSender, ALERT_METASPACE, hdr.snapShotTime,
hdr.metaspaceUsage, hdr.metaspaceCapacity))) {
logger->printWarnMsg("SNMP trap send failed!");
}
}
}
/* Class map used snapshot output. */
auto workClsMap(classMap);
/* Allocate return array. */
jlong rankCnt = workClsMap.size();
rankCnt =
(rankCnt < conf->RankLevel()->get()) ? rankCnt : conf->RankLevel()->get();
/* Make controller to sort. */
register TRankOrder order = conf->Order()->get();
TSorter<THeapDelta> *sortArray;
try {
sortArray = new TSorter<THeapDelta>(
rankCnt,
(TComparator)((order == DELTA) ? &HeapDeltaCmp : &HeapUsageCmp));
} catch (...) {
int raisedErrNum = errno;
logger->printWarnMsgWithErrno("Couldn't allocate working memory!");
return raisedErrNum;
}
/* Open file and seek EOF. */
int fd = open(conf->FileName()->get(), O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
/* If failure open file. */
if (unlikely(fd < 0)) {
int raisedErrNum = errno;
logger->printWarnMsgWithErrno("Could not open %s", conf->FileName()->get());
delete sortArray;
return raisedErrNum;
}
off_t oldFileOffset = -1;
try {
/* Move position to EOF. */
oldFileOffset = lseek(fd, 0, SEEK_END);
/* If failure seek. */
if (unlikely(oldFileOffset < 0)) {
throw 1;
}
/* Frist, Output each classes information. Secondly output header. */
if (unlikely(lseek(fd, sizeof(TSnapShotFileHeader) - sizeof(char[80]) +
hdr.gcCauseLen,
SEEK_CUR) < 0)) {
throw 1;
}
} catch (...) {
int raisedErrNum = errno;
logger->printWarnMsg("Could not write snapshot");
close(fd);
delete sortArray;
return raisedErrNum;
}
/* Output class information. */
THeapDelta result;
jlong numEntries = 0L;
int raiseErrorCode = 0;
register jlong AlertThreshold = conf->getAlertThreshold();
/* Loop each class. */
for (auto it = workClsMap.begin(); it != workClsMap.end(); it++) {
TObjectData *objData = it->second;
TClassCounter *cur = snapshot->findClass(objData);
/* If don't registed class yet. */
if (unlikely(cur == NULL)) {
cur = snapshot->pushNewClass(objData);
if (unlikely(cur == NULL)) {
raiseErrorCode = errno;
logger->printWarnMsgWithErrno("Couldn't allocate working memory!");
delete sortArray;
sortArray = NULL;
break;
}
}
/* Calculate uasge and delta size. */
result.usage = cur->counter->total_size;
result.delta = cur->counter->total_size - objData->oldTotalSize;
result.tag = objData->tag;
objData->oldTotalSize = result.usage;
/* If do output class. */
if (!conf->ReduceSnapShot()->get() || (result.usage > 0)) {
/* Output class-information. */
if (likely(raiseErrorCode == 0)) {
raiseErrorCode = writeClassData(fd, objData, cur, snapshot);
}
numEntries++;
}
/* Ranking sort. */
sortArray->push(result);
/* If alert is enable. */
if (AlertThreshold > 0) {
/* Variable for send trap. */
int sendFlag = 0;
/* If size is bigger more limit size. */
if ((order == DELTA) && (AlertThreshold <= result.delta)) {
/* Raise alert. */
logger->printWarnMsg(
"ALERT(DELTA): \"%s\" exceeded the threshold (%ld bytes)",
objData->className, result.delta);
/* Set need send trap flag. */
sendFlag = 1;
} else if ((order == USAGE) && (AlertThreshold <= result.usage)) {
/* Raise alert. */
logger->printWarnMsg(
"ALERT(USAGE): \"%s\" exceeded the threshold (%ld bytes)",
objData->className, result.usage);
/* Set need send trap flag. */
sendFlag = 1;
}
/* If need send trap. */
if (conf->SnmpSend()->get() && sendFlag != 0) {
if (unlikely(!sendHeapAlertTrap(pSender, result, objData->className,
cur->counter->count))) {
logger->printWarnMsg("Send SNMP trap failed!");
}
}
}
}
/* Set output entry count. */
hdr.size = numEntries;
/* Stored error number to avoid overwriting by "truncate" and etc.. */
int raisedErrNum = 0;
try {
/* If already failed in processing to write snapshot. */
if (unlikely(raiseErrorCode != 0)) {
errno = raiseErrorCode;
raisedErrNum = raiseErrorCode;
throw 1;
}
/* If fail seeking to header position. */
if (unlikely(lseek(fd, oldFileOffset, SEEK_SET) < 0)) {
raisedErrNum = errno;
throw 2;
}
raisedErrNum = writeHeader(fd, hdr);
/* If failed to write a snapshot header. */
if (unlikely(raisedErrNum != 0)) {
throw 3;
}
} catch (...) {
; /* Failed to write file. */
}
/* Clean up. */
if (unlikely(close(fd) != 0 && raisedErrNum == 0)) {
errno = raisedErrNum;
logger->printWarnMsgWithErrno("Could not write snapshot");
}
/* If need rollback snapshot. */
if (unlikely(raisedErrNum != 0)) {
if (unlikely(truncate(conf->FileName()->get(), oldFileOffset) < 0)) {
logger->printWarnMsgWithErrno("Could not rollback snapshot");
}
}
/* Cleanup. */
(*rank) = sortArray;
return raisedErrNum;
}
/*!
* \brief Class unload event. Unloaded class will be added to unloaded list.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param thread [in] Java thread object.
* \param klass [in] Unload class object.
* \sa from: hotspot/src/share/vm/prims/jvmti.xml
*/
void JNICALL
OnClassUnload(jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jclass klass) {
/*
* This function does not require to check whether at safepoint because
* Class Unloading always executes at safepoint.
*/
/* Get klassOop. */
void *mirror = *(void **)klass;
void *klassOop = TVMFunctions::getInstance()->AsKlassOop(mirror);
if (likely(klassOop != NULL)) {
/* Search class. */
TObjectData *counter = clsContainer->findClass(klassOop);
if (likely(counter != NULL)) {
/*
* This function will be called at safepoint and be called by VMThread
* because class unloading is single-threaded process.
* So we can lock-free access.
*/
unloadedList.push(counter);
}
}
}
/*!
* \brief GarbageCollectionFinish JVMTI event to release memory for unloaded
* TObjectData.
* This function will be called at safepoint.
* All GC worker and JVMTI agent threads for HeapStats will not work
* at this point.
* So we can lock-free access.
*/
void JNICALL OnGarbageCollectionFinishForUnload(jvmtiEnv *jvmti) {
if (!unloadedList.empty()) {
/* Remove targets from snapshot container. */
TSnapShotContainer::removeObjectDataFromAllSnapShots(unloadedList);
/* Remove targets from class container. */
TObjectData *objData;
while (unloadedList.try_pop(objData)) {
clsContainer->removeClass(objData);
free(objData->className);
free(objData);
}
}
/* Clear updated data */
clsContainer->removeBeforeUpdatedData();
}
| 24,627
|
C++
|
.cpp
| 705
| 29.609929
| 82
| 0.639856
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,004
|
fsUtil.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/fsUtil.cpp
|
/*!
* \file fsUtil.cpp
* \brief This file is utilities to access file system.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <fcntl.h>
#include <sys/sendfile.h>
#include <dirent.h>
#include "globals.hpp"
#include "fsUtil.hpp"
/*!
* \brief Mutex of working directory.
*/
pthread_mutex_t directoryMutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
/*!
* \brief Copy data as avoid overwriting.
* \param sourceFile [in] Path of source file.
* \param destPath [in] Path of directory put duplicated file.
* \param destName [in] Name of duplicated file.<br>
* Don't rename, if value is null.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int copyFile(char const *sourceFile, char const *destPath,
char const *destName) {
char rpath[PATH_MAX];
if (unlikely(!isCopiablePath(sourceFile, rpath))) {
return EINVAL;
}
int result = 0;
/* Make file name. */
char *newFile = destName == NULL
? createFilename(destPath, (char *)sourceFile)
: createFilename(destPath, (char *)destName);
/* Failure make filename. */
if (unlikely(newFile == NULL)) {
logger->printWarnMsg("Couldn't allocate copy source file path.");
/*
* Because exist below two pattern when "createFilename" return NULL.
* 1, Illegal argument. "errno" don't change.
* 2, No usable memory. "errno" maybe "ENOMEM".
*/
return (errno != 0) ? errno : EINVAL;
}
/* Get uniq file name. */
char *destFile = createUniquePath(newFile, false);
if (unlikely(destFile == NULL)) {
logger->printWarnMsg("Couldn't allocate unique destination file name.");
free(newFile);
return ENOMEM;
}
/* Open copy source file. */
int sourceFd = open(sourceFile, O_RDONLY);
if (unlikely(sourceFd < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Couldn't open copy source file.");
free(newFile);
free(destFile);
return result;
}
/* Get source file size */
struct stat st;
if (unlikely(fstat(sourceFd, &st) != 0)) {
result = errno;
logger->printWarnMsgWithErrno("Couldn't open copy destination file.");
free(newFile);
free(destFile);
close(sourceFd);
return result;
}
/* Open destination file. */
int destFd = open(destFile, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR);
if (unlikely(destFd < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Couldn't open copy destination file.");
free(newFile);
free(destFile);
close(sourceFd);
return result;
}
/* Copy data */
if (st.st_size > 0) {
if (unlikely(sendfile64(destFd, sourceFd, NULL, st.st_size) == -1)) {
result = errno;
logger->printWarnMsgWithErrno("Couldn't copy file.");
}
} else { /* This route is for files in procfs */
char buf[1024];
ssize_t read_size;
while ((read_size = read(sourceFd, buf, 1024)) > 0) {
if (write(destFd, buf, (size_t)read_size) == -1) {
read_size = -1;
break;
}
}
if (read_size == -1) {
result = errno;
logger->printWarnMsgWithErrno("Couldn't copy file.");
}
}
/* Clean up */
close(sourceFd);
if (unlikely((close(destFd) != 0) && (result == 0))) {
result = errno;
logger->printWarnMsgWithErrno("Couldn't write copy file data.");
}
free(newFile);
free(destFile);
return result;
}
/*!
* \brief Create filename in expected path.
* \param basePath [in] Path of directory.
* \param filename [in] filename.
* \return Create string.<br>
* Process is failure, if return is null.<br>
* Need call "free", if return is not null.
*/
char *createFilename(char const *basePath, char const *filename) {
/* Path separator. */
const char PATH_SEP = '/';
/* Sanity check. */
if (unlikely(basePath == NULL || filename == NULL || strlen(basePath) == 0 ||
strlen(filename) == 0)) {
return NULL;
}
/* Find file name head. so exclude path. */
char *headPos = strrchr((char *)filename, PATH_SEP);
/* If not found separator. */
if (headPos == NULL) {
/* Copy all. */
headPos = (char *)filename;
} else {
/* Skip separator. */
headPos++;
}
/* Check separator existing. */
bool needSeparator = (basePath[strlen(basePath) - 1] != PATH_SEP);
size_t strSize = strlen(basePath) + strlen(headPos) + 1;
if (needSeparator) {
strSize += 1;
}
char *newPath = (char *)malloc(strSize);
/* If failure allocate result string. */
if (unlikely(newPath == NULL)) {
return NULL;
}
/* Add base directory path. */
strcpy(newPath, basePath);
/* Insert separator. */
if (needSeparator) {
strcat(newPath, "/");
}
/* Add file name. */
strcat(newPath, headPos);
/* Return generate file path. */
return newPath;
}
/*!
* \brief Resolve canonicalized path path and check regular file or not.
* \param path [in] Path of the target file.
* \param rpath [out] Real path which is pointed at "path".
* Buffer size must be enough to store path (we recommend PATH_MAX).
* \return If "path" is copiable, this function returns true.
*/
bool isCopiablePath(const char *path, char *rpath) {
realpath(path, rpath);
struct stat st;
if (unlikely(stat(rpath, &st) != 0)) {
/* Failure get file information. */
logger->printWarnMsgWithErrno("Failure get file information (stat).");
return false;
}
if ((st.st_mode & S_IFMT) != S_IFREG) {
/* File isn't regular file. This route is not error. */
logger->printDebugMsg("Couldn't copy file. Not a regular file: %s", path);
return false;
}
return true;
}
/*!
* \brief Create temporary directory in designated directory.
* \param basePath [out] Path of temporary directory.<br>
* Process is failure, if return is null.<br>
* Need call "free", if return is not null.
* \param wishesName [in] Name of one's wishes directory name.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int createTempDir(char **basePath, char const *wishesName) {
char *uniqName = NULL;
/* Sanity check. */
if (unlikely(basePath == NULL || wishesName == NULL)) {
logger->printWarnMsg("Illegal directory path.");
return -1;
}
int raisedErrNum = -1;
{
TMutexLocker locker(&directoryMutex);
/* Create unique directory path. */
uniqName = createUniquePath((char *)wishesName, true);
if (unlikely(uniqName == NULL)) {
raisedErrNum = errno;
} else {
/* If failed to create temporary directory. */
if (unlikely(mkdir(uniqName, S_IRUSR | S_IWUSR | S_IXUSR) != 0)) {
raisedErrNum = errno;
} else {
raisedErrNum = 0;
}
}
}
/* If failed to create temporary directory. */
if (unlikely(raisedErrNum != 0)) {
free(uniqName);
uniqName = NULL;
}
/* Copy directory path. */
(*basePath) = uniqName;
return raisedErrNum;
}
/*!
* \brief Remove temporary directory.
* \param basePath [in] Path of temporary directory.
*/
void removeTempDir(char const *basePath) {
/* If failure open directory. */
if (unlikely(basePath == NULL)) {
logger->printWarnMsg("Illegal directory path.");
return;
}
/* Open directory. */
DIR *dir = opendir(basePath);
/* If failure open directory. */
if (unlikely(dir == NULL)) {
logger->printWarnMsgWithErrno("Couldn't open directory.");
return;
}
/* Store error number. */
int oldErrNum = errno;
/* Read file in directory. */
struct dirent *entry = NULL;
while ((entry = readdir(dir)) != NULL) {
/* Check file name. */
if (strcmp(entry->d_name, "..") == 0 || strcmp(entry->d_name, ".") == 0) {
continue;
}
/* Get remove file's full path. */
char *removePath = createFilename(basePath, entry->d_name);
/* All file need remove. */
if (unlikely(removePath == NULL || unlink(removePath) != 0)) {
/* Skip file remove. */
if (removePath == NULL) {
errno = ENOMEM; // This error may be caused by ENOMEM because malloc()
// failed.
}
char *printPath = (removePath != NULL) ? removePath : entry->d_name;
logger->printWarnMsgWithErrno("Failure remove file. path: \"%s\"",
printPath);
}
/* Cleanup. */
free(removePath);
oldErrNum = errno;
}
/* If failure in read directory. */
if (unlikely(errno != oldErrNum)) {
logger->printWarnMsgWithErrno("Failure search file in directory.");
}
/* Cleanup. */
closedir(dir);
{
TMutexLocker locker(&directoryMutex);
/* Remove directory. */
if (unlikely(rmdir(basePath) != 0)) {
/* Skip directory remove. */
logger->printWarnMsgWithErrno("Failure remove directory.");
}
}
}
/*!
* \brief Create unique path.
* \param path [in] Path.
* \param isDirectory [in] Path is directory.
* \return Unique path.<br>Don't forget deallocate.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
char *createUniquePath(char *path, bool isDirectory) {
/* Variable for temporary path. */
char tempPath[PATH_MAX] = {0};
/* Variables for file system. */
FILE *file = NULL;
DIR *dir = NULL;
/* Variable for file path and extensition. */
char ext[PATH_MAX] = {0};
char tempName[PATH_MAX] = {0};
/* Sanity check. */
if (unlikely(path == NULL || strlen(path) == 0)) {
logger->printWarnMsg("Illegal unique path paramters.");
return NULL;
}
/* Search extension. */
char *extPos = strrchr(path, '.');
/* If create path for file and exists extension. */
if (!isDirectory && extPos != NULL) {
int pathSize = (extPos - path);
pathSize = (pathSize > PATH_MAX) ? PATH_MAX : pathSize;
/* Path and extension store each other. */
strncpy(ext, extPos, PATH_MAX);
strncpy(tempName, path, pathSize);
} else {
/* Ignore extension if exists. */
strncpy(tempName, path, PATH_MAX);
}
/* Copy default path. */
strncpy(tempPath, path, PATH_MAX);
/* Try make unique path loop. */
const unsigned long int MAX_RETRY_COUNT = 1000000;
unsigned long int loopCount = 0;
for (; loopCount <= MAX_RETRY_COUNT; loopCount++) {
/* Usable path flag. */
bool noExist = false;
/* Reset error number. */
errno = 0;
/* Open and check exists. */
if (isDirectory) {
/* Check directory. */
dir = opendir(tempPath);
noExist = (dir == NULL && errno == ENOENT);
if (dir != NULL) {
closedir(dir);
}
} else {
/* Check file. */
file = fopen(tempPath, "r");
noExist = (file == NULL && errno == ENOENT);
if (file != NULL) {
fclose(file);
}
}
/* If path is usable. */
if (noExist) {
break;
}
/* Make new path insert sequence number between 000000 and 999999. */
int ret = snprintf(tempPath, PATH_MAX, "%s_%06lu%s",
tempName, loopCount, ext);
if (ret >= PATH_MAX) {
logger->printCritMsg("Temp path is too long: %s", tempPath);
return NULL;
}
}
/* If give up to try unique naming by number. */
if (unlikely(loopCount > MAX_RETRY_COUNT)) {
/* Get random value. */
long int rand = random();
const int randSize = 6;
char randStr[randSize + 1] = {0};
for (int i = 0; i < randSize; i++) {
randStr[i] = (rand % 26) + 'A';
rand /= 26;
}
/* Uniquely naming by random string. */
int ret = snprintf(tempPath, PATH_MAX, "%s_%6s%s", tempName, randStr, ext);
if (ret >= PATH_MAX) {
logger->printCritMsg("Temp path is too long: %s", tempPath);
return NULL;
}
logger->printWarnMsg("Not found unique name. So used random string.");
}
/* Copy path. */
char *result = strdup(tempPath);
if (unlikely(result == NULL)) {
logger->printWarnMsg("Couldn't copy unique path.");
}
return result;
}
#pragma GCC diagnostic pop
/*!
* \brief Get parent directory path.
* \param path [in] Path which file or directory.
* \return Parent directory path.<br>Don't forget deallocate.
*/
char *getParentDirectoryPath(char const *path) {
char *sepPos = NULL;
char *result = NULL;
/* Search last separator. */
sepPos = strrchr((char *)path, '/');
if (sepPos == NULL) {
/* Path is current directory. */
result = strdup("./");
} else if (unlikely(sepPos == path)) {
/* Path is root. */
result = strdup("/");
} else {
/* Copy path exclude last entry. */
result = (char *)calloc(1, sepPos - path + 1);
if (likely(result != NULL)) {
strncpy(result, path, sepPos - path);
}
}
/* If failure allocate path. */
if (unlikely(result == NULL)) {
logger->printWarnMsg("Couldn't copy parent directory path.");
}
return result;
}
/*!
* \brief Get accessible of directory.
* \param path [in] Directory path.
* \param needRead [in] Accessible flag about file read.
* \param needWrite [in] Accessible flag about file write.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int isAccessibleDirectory(char const *path, bool needRead, bool needWrite) {
struct stat st = {0};
/* Sanity check. */
if (unlikely(path == NULL || strlen(path) == 0 ||
(!needRead && !needWrite))) {
logger->printWarnMsg("Illegal accessible paramter.");
return -1;
}
/* If failure get directory information. */
if (unlikely(stat(path, &st) != 0)) {
int raisedErrNum = errno;
logger->printWarnMsgWithErrno("Failure get directory information.");
return raisedErrNum;
}
/* if path isn't directory. */
if (unlikely(!S_ISDIR(st.st_mode))) {
logger->printWarnMsg("Illegal directory path.");
return ENOTDIR;
}
/* if execute by administrator. */
if (unlikely(geteuid() == 0)) {
return 0;
}
bool result = false;
bool isDirOwner = (st.st_uid == geteuid());
bool isGroupUser = (st.st_gid == getegid());
/* Check access permition as file owner. */
if (isDirOwner) {
result |= (!needRead || (st.st_mode & S_IRUSR) > 0) &&
(!needWrite || (st.st_mode & S_IWUSR) > 0);
}
/* Check access permition as group user. */
if (!result && isGroupUser) {
result |= (!needRead || (st.st_mode & S_IRGRP) > 0) &&
(!needWrite || (st.st_mode & S_IWGRP) > 0);
}
/* Check access permition as other. */
if (!result) {
result |= (!needRead || (st.st_mode & S_IROTH) > 0) &&
(!needWrite || (st.st_mode & S_IWOTH) > 0);
}
return (result) ? 0 : EACCES;
}
/*!
* \brief Check that path is accessible.
* \param path [in] A path to file.
* \return Path is accessible.
*/
bool isValidPath(const char *path) {
/* Check archive file path. */
if (strlen(path) == 0) {
throw "Invalid file path";
}
char *dir = getParentDirectoryPath(path);
if (dir == NULL) {
throw "Cannot get parent directory";
}
errno = 0;
int ret = isAccessibleDirectory(dir, true, true);
free(dir);
if (ret == -1) {
throw "Illegal parameter was passed to isAccessibleDirectory()";
} else if (errno != 0) {
return false;
}
struct stat st;
if (stat(path, &st) == -1) {
if (errno == ENOENT) {
return true;
} else {
throw errno;
}
}
bool result = false;
bool isOwner = (st.st_uid == geteuid());
bool isGroupUser = (st.st_gid == getegid());
/* Check access permition as file owner. */
if (isOwner) {
result |= (st.st_mode & S_IRUSR) && (st.st_mode & S_IWUSR);
}
/* Check access permition as group user. */
if (!result && isGroupUser) {
result |= (st.st_mode & S_IRGRP) && (st.st_mode & S_IWGRP);
}
/* Check access permition as other. */
if (!result) {
result |= (st.st_mode & S_IROTH) && (st.st_mode & S_IWOTH);
}
if (!result) {
errno = EPERM;
}
return result;
}
| 16,816
|
C++
|
.cpp
| 523
| 27.944551
| 82
| 0.629822
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,005
|
libmain.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/libmain.cpp
|
/*!
* \file libmain.cpp
* \brief This file is used to common works.<br>
* e.g. initialization, finalization, etc...
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <jni.h>
#include <jvmti.h>
#include <unistd.h>
#include <signal.h>
#include "globals.hpp"
#include "elapsedTimer.hpp"
#include "snapShotMain.hpp"
#include "logMain.hpp"
#include "deadlockDetector.hpp"
#include "callbackRegister.hpp"
#include "threadRecorder.hpp"
#include "heapstatsMBean.hpp"
#include "libmain.hpp"
/* Variables. */
/*!
* \brief JVM running performance information.
*/
TJvmInfo *jvmInfo;
/*!
* \brief Signal manager to reload configuration by signal.
*/
TSignalManager *reloadSigMngr = NULL;
/*!
* \brief Reload configuration timer thread.
*/
TTimer *intervalSigTimer;
/*!
* \brief Logger instance.
*/
TLogger *logger;
/*!
* \brief HeapStats configuration.
*/
TConfiguration *conf;
/*!
* \brief Flag of reload configuration for signal.
*/
volatile sig_atomic_t flagReloadConfig;
/*!
* \brief Running flag.
*/
int flagRunning = 0;
/*!
* \brief CPU clock ticks.
*/
long TElapsedTimer::clock_ticks = sysconf(_SC_CLK_TCK);
/*!
* \brief Path of load configuration file at agent initialization.
*/
char *loadConfigPath = NULL;
/* Macros. */
/*!
* \brief Check memory duplication macro.<br>
* If load a library any number of times,<br>
* Then the plural agents use single memory area.<br>
* E.g. "java -agentlib:A -agentlib:A -jar X.jar"
*/
#define CHECK_DOUBLING_RUN \
if (flagRunning != 0) { \
/* Already running another heapstats agent. */ \
logger->printWarnMsg( \
"HeapStats agent already run on this JVM." \
" This agent is disabled."); \
return SUCCESS; \
} \
/* Setting running flag. */ \
flagRunning = 1;
/* Functions. */
/*!
* \brief Handle signal express user wanna reload config.
* \param signo [in] Number of received signal.
* \param siginfo [in] Information of received signal.
* \param data [in] Data of received signal.
*/
void ReloadSigProc(int signo, siginfo_t *siginfo, void *data) {
/* Enable flag. */
flagReloadConfig = 1;
NOTIFY_CATCH_SIGNAL;
}
/*!
* \brief Setting enable of JVMTI and extension events.
* \param jvmti [in] JVMTI environment object.
* \param enable [in] Event notification is enable.
* \return Setting process result.
*/
jint SetEventEnable(jvmtiEnv *jvmti, bool enable) {
jint result = SUCCESS;
/* Set snapshot component enable. */
result = setEventEnableForSnapShot(jvmti, enable);
if (result == SUCCESS) {
/* Set logging component enable. */
result = setEventEnableForLog(jvmti, enable);
}
return result;
}
/*!
* \brief Setting enable of agent each threads.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param enable [in] Event notification is enable.
*/
void SetThreadEnable(jvmtiEnv *jvmti, JNIEnv *env, bool enable) {
/* Change thread enable for snapshot. */
setThreadEnableForSnapShot(jvmti, env, enable);
/* Change thread enable for log. */
setThreadEnableForLog(jvmti, env, enable);
}
/*!
* \brief Interval watching for reload config signal.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void ReloadConfigProc(jvmtiEnv *jvmti, JNIEnv *env) {
/* If catch reload config signal. */
if (unlikely(flagReloadConfig != 0)) {
/* Reload configuration. */
/* If agent is attaching now. */
if (likely(conf->Attach()->get())) {
/* Suspend events. */
SetEventEnable(jvmti, false);
/* Suspend threads. */
SetThreadEnable(jvmti, env, false);
/* Suspend deadlock detector. */
if (conf->CheckDeadlock()->get()) {
dldetector::finalize(jvmti);
}
/* Suspend thread status logging. */
if (conf->ThreadRecordEnable()->get()) {
TThreadRecorder::finalize(jvmti, env,
conf->ThreadRecordFileName()->get());
}
}
/* If config file is designated at initialization. */
if (unlikely(loadConfigPath == NULL)) {
/* Make default configuration path. */
char confPath[PATH_MAX + 1] = {0};
snprintf(confPath, PATH_MAX, "%s/heapstats.conf", DEFAULT_CONF_DIR);
/* Load default config file. */
conf->loadConfiguration(confPath);
} else {
/* Reload designated config file. */
conf->loadConfiguration(loadConfigPath);
}
if (!conf->validate()) {
logger->printCritMsg(
"Given configuration is invalid. Use default value.");
delete conf;
conf = new TConfiguration(jvmInfo);
conf->validate();
}
/* If agent is attaching now. */
if (likely(conf->Attach()->get())) {
/* Ignore perfomance information during agent dettached. */
jvmInfo->resumeGCinfo();
/* Restart threads. */
SetThreadEnable(jvmti, env, true);
/* Start deadlock detector. */
if (conf->CheckDeadlock()->get()) {
jvmtiCapabilities capabilities = {0};
dldetector::initialize(jvmti, false);
if (isError(jvmti, jvmti->AddCapabilities(&capabilities))) {
logger->printCritMsg(
"Couldn't set event capabilities for deadlock detector.");
}
}
/* Start thread status logging. */
if (conf->ThreadRecordEnable()->get()) {
TThreadRecorder::initialize(
jvmti, env, conf->ThreadRecordBufferSize()->get() * 1024 * 1024);
}
}
logger->printInfoMsg("Reloaded configuration file.");
/* Show setting information. */
conf->printSetting();
logger->flush();
/* If agent is attaching now. */
if (likely(conf->Attach()->get())) {
/* Restart events. */
SetEventEnable(jvmti, true);
}
/* Reset signal flag. */
flagReloadConfig = 0;
}
}
/*!
* \brief Interval watching for signals.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Cause of Invoking.<br>
* This value is always Interval.
*/
void intervalSigProc(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause) {
ReloadConfigProc(jvmti, env);
/* If agent is attaching now and enable log signal. */
if (likely(conf->Attach()->get() && conf->TriggerOnLogSignal()->get())) {
intervalSigProcForLog(jvmti, env);
}
}
/*!
* \brief JVM initialization event.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param thread [in] Java thread object.
*/
void JNICALL OnVMInit(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
/* Get GC information address. */
#ifdef USE_VMSTRUCTS
jvmInfo->detectInfoAddress();
#else
jvmInfo->detectInfoAddress(env);
#endif
/* Get all values from HotSpot VM */
if (!TVMVariables::getInstance()->getValuesAfterVMInit()) {
logger->printCritMsg(
"Cannot gather all values from HotSpot to work HeapStats");
return;
}
if (!conf->validate()) {
logger->printCritMsg("Given configuration is invalid. Use default value.");
delete conf;
conf = new TConfiguration(jvmInfo);
conf->validate();
}
/* Initialize signal flag. */
flagReloadConfig = 0;
/* Start HeapStats agent threads. */
if (conf->ReloadSignal()->get() != NULL) {
try {
reloadSigMngr = new TSignalManager(conf->ReloadSignal()->get());
if (!reloadSigMngr->addHandler(&ReloadSigProc)) {
logger->printWarnMsg("Reload signal handler setup is failed.");
conf->ReloadSignal()->set(NULL);
}
} catch (const char *errMsg) {
logger->printWarnMsg(errMsg);
conf->ReloadSignal()->set(NULL);
} catch (...) {
logger->printWarnMsg("Reload signal handler setup is failed.");
conf->ReloadSignal()->set(NULL);
}
}
/* Calculate alert limit. */
jlong MaxMemory = jvmInfo->getMaxMemory();
if (MaxMemory == -1) {
conf->setAlertThreshold(-1);
conf->setHeapAlertThreshold(-1);
} else {
conf->setAlertThreshold(MaxMemory * conf->AlertPercentage()->get() / 100);
conf->setHeapAlertThreshold(MaxMemory * conf->HeapAlertPercentage()->get() /
100);
}
/* Invoke JVM initialize event of snapshot function. */
onVMInitForSnapShot(jvmti, env);
/* Invoke JVM initialize event of log function. */
onVMInitForLog(jvmti, env);
/* If agent is attaching now. */
if (likely(conf->Attach()->get())) {
/* Start and enable each agent threads. */
SetThreadEnable(jvmti, env, true);
/* Set event enable in each function. */
SetEventEnable(jvmti, true);
/* Start thread status logging. */
if (conf->ThreadRecordEnable()->get()) {
TThreadRecorder::initialize(
jvmti, env, conf->ThreadRecordBufferSize()->get() * 1024 * 1024);
}
}
/* Getting class prepare events. */
if (TClassPrepareCallback::switchEventNotification(jvmti, JVMTI_ENABLE)) {
logger->printWarnMsg("HeapStats will be turned off.");
SetEventEnable(jvmti, false);
SetThreadEnable(jvmti, env, false);
logger->flush();
return;
}
/* Show setting information. */
conf->printSetting();
logger->flush();
/* Start reload signal watcher. */
try {
intervalSigTimer->start(jvmti, env, SIG_WATCHER_INTERVAL);
} catch (const char *errMsg) {
logger->printWarnMsg(errMsg);
}
/* Set JNI function to register MBean native function. */
jniNativeInterface *jniFuncs = NULL;
if (isError(jvmti, jvmti->GetJNIFunctionTable(&jniFuncs))) {
logger->printWarnMsg("Could not get JNI Function table.");
} else if (jniFuncs->reserved0 != NULL) {
logger->printWarnMsg("JNI Function table #0 is already set.");
} else {
jniFuncs->reserved0 = (void *)RegisterHeapStatsNative;
if (isError(jvmti, jvmti->SetJNIFunctionTable(jniFuncs))) {
logger->printWarnMsg("Could not set JNI Function table.");
}
}
if (jniFuncs != NULL) {
jvmti->Deallocate((unsigned char *)jniFuncs);
}
}
/*!
* \brief JVM finalization event.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void JNICALL OnVMDeath(jvmtiEnv *jvmti, JNIEnv *env) {
/* If agent is attaching now. */
if (likely(conf->Attach()->get())) {
/* Stop and disable event notify. */
SetEventEnable(jvmti, false);
}
/*
* Terminate signal watcher thread.
* This thread is used by collect log and reload configuration.
* So that, need to this thread stop before other all thread stopped.
*/
intervalSigTimer->terminate();
/* If reload log signal is enabled. */
if (likely(reloadSigMngr != NULL)) {
delete reloadSigMngr;
reloadSigMngr = NULL;
}
/* If agent is attaching now. */
if (likely(conf->Attach()->get())) {
/* Stop and disable each thread. */
SetThreadEnable(jvmti, env, false);
if (conf->CheckDeadlock()->get()) {
dldetector::finalize(jvmti);
}
if (conf->ThreadRecordEnable()->get()) {
TThreadRecorder::finalize(jvmti, env,
conf->ThreadRecordFileName()->get());
}
}
/* Invoke JVM finalize event of snapshot function. */
onVMDeathForSnapShot(jvmti, env);
/* Invoke JVM finalize event of log function. */
onVMDeathForLog(jvmti, env);
/* Unregister native functions for HeapStats MBean */
UnregisterHeapStatsNatives(env);
}
/*!
* \brief Abort JVM by force on illegal status.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param causeMsg [in] Message about cause of aborting JVM.
* \warning This function is always no return.
*/
void forcedAbortJVM(jvmtiEnv *jvmti, JNIEnv *env, const char *causeMsg) {
/* Output last message. */
logger->printCritMsg("Aborting JVM by HeapStats. cause: %s", causeMsg);
logger->flush();
abort();
}
/*!
* \brief Setting JVMTI and extension events.
* \param jvmti [in] JVMTI environment object.
* \param isOnLoad [in] OnLoad phase or not (Live phase).
* \return Setting process result.
*/
jint InitEventSetting(jvmtiEnv *jvmti, bool isOnLoad) {
jvmtiCapabilities capabilities = {0};
/* Set capability for object tagging. */
capabilities.can_tag_objects = 1;
/* Set capabilities for Thread Recording. */
TThreadRecorder::setCapabilities(&capabilities);
/* Setup GarbageCollectionFinish callback for class unloading. */
TGarbageCollectionFinishCallback::mergeCapabilities(&capabilities);
TGarbageCollectionFinishCallback::registerCallback(
&OnGarbageCollectionFinishForUnload);
/* Setup ClassPrepare event. */
TClassPrepareCallback::mergeCapabilities(&capabilities);
TClassPrepareCallback::registerCallback(&OnClassPrepare);
/* Setup DataDumpRequest event. */
TDataDumpRequestCallback::mergeCapabilities(&capabilities);
TDataDumpRequestCallback::registerCallback(&OnDataDumpRequestForSnapShot);
/* Setup garbage collection event. */
if (conf->TriggerOnFullGC()->get()) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* FullGC on G1, we handle it at callbackForG1Full() */
if (!vmVal->getUseG1()) {
TGarbageCollectionStartCallback::mergeCapabilities(&capabilities);
if (vmVal->getUseCMS()) {
TGarbageCollectionStartCallback::registerCallback(&OnCMSGCStart);
TGarbageCollectionFinishCallback::registerCallback(&OnCMSGCFinish);
} else { // for Parallel GC
TGarbageCollectionStartCallback::registerCallback(
&OnGarbageCollectionStart);
TGarbageCollectionFinishCallback::registerCallback(
&OnGarbageCollectionFinish);
}
}
}
/* Setup ResourceExhausted event. */
if (conf->TriggerOnLogError()->get()) {
TResourceExhaustedCallback::mergeCapabilities(&capabilities);
TResourceExhaustedCallback::registerCallback(&OnResourceExhausted);
}
/* Setup MonitorContendedEnter event. */
if (conf->CheckDeadlock()->get()) {
if (!dldetector::initialize(jvmti, isOnLoad)) {
return DLDETECTOR_SETUP_FAILED;
}
}
/* Setup VMInit event. */
TVMInitCallback::mergeCapabilities(&capabilities);
TVMInitCallback::registerCallback(&OnVMInit);
/* Setup VMDeath event. */
TVMDeathCallback::mergeCapabilities(&capabilities);
TVMDeathCallback::registerCallback(&OnVMDeath);
/* Set JVMTI event capabilities. */
if (isError(jvmti, jvmti->AddCapabilities(&capabilities))) {
logger->printCritMsg("Couldn't set event capabilities.");
return CAPABILITIES_SETTING_FAILED;
}
/* Set JVMTI event callbacks. */
if (registerJVMTICallbacks(jvmti)) {
logger->printCritMsg("Couldn't register normal event.");
return CALLBACKS_SETTING_FAILED;
}
/* Enable VMInit and VMDeath. */
TVMInitCallback::switchEventNotification(jvmti, JVMTI_ENABLE);
TVMDeathCallback::switchEventNotification(jvmti, JVMTI_ENABLE);
return SUCCESS;
}
/*!
* \brief Common initialization function.
* \param vm [in] JavaVM object.
* \param jvmti [out] JVMTI environment object.
* \param options [in] Option string which is passed through
* -agentpath/-agentlib.
* \return Initialize process result.
*/
jint CommonInitialization(JavaVM *vm, jvmtiEnv **jvmti, char *options) {
/* Initialize logger */
logger = new TLogger();
/* Get JVMTI environment object. */
if (vm->GetEnv((void **)jvmti, JVMTI_VERSION_1) != JNI_OK) {
logger->printCritMsg("Get JVMTI environment information failed!");
return GET_ENVIRONMENT_FAILED;
}
/* Setup TJvmInfo */
try {
jvmInfo = new TJvmInfo();
} catch (const char *errMsg) {
logger->printCritMsg(errMsg);
return GET_LOW_LEVEL_INFO_FAILED;
}
/* Initialize configuration */
conf = new TConfiguration(jvmInfo);
/* Parse arguments. */
if (options == NULL || strlen(options) == 0) {
/* Make default configuration path. */
char confPath[PATH_MAX + 1] = {0};
snprintf(confPath, PATH_MAX, "%s/heapstats.conf", DEFAULT_CONF_DIR);
conf->loadConfiguration(confPath);
} else {
conf->loadConfiguration(options);
loadConfigPath = strdup(options);
}
logger->setLogLevel(conf->LogLevel()->get());
logger->setLogFile(conf->LogFile()->get());
/* Parse JDK Version */
if (!jvmInfo->setHSVersion(*jvmti)) {
return GET_LOW_LEVEL_INFO_FAILED;
}
/* Show package information. */
logger->printInfoMsg(PACKAGE_STRING);
logger->printInfoMsg(
"Supported processor features:"
#ifdef SSE2
" SSE2"
#endif
#ifdef SSE4
" SSE4"
#endif
#ifdef AVX
" AVX"
#endif
#ifdef NEON
" NEON"
#endif
#if (!defined NEON) && (!defined AVX) && (!defined SSE4) && (!defined SSE2)
" None"
#endif
);
logger->flush();
if (conf->SnmpSend()->get() &&
!TTrapSender::initialize(SNMP_VERSION_2c, conf->SnmpTarget()->get(),
conf->SnmpComName()->get(), 162)) {
return SNMP_SETUP_FAILED;
}
/* Create thread instances that controlled snapshot trigger. */
try {
intervalSigTimer = new TTimer(&intervalSigProc, "HeapStats Signal Watcher");
} catch (const char *errMsg) {
logger->printCritMsg(errMsg);
return AGENT_THREAD_INITIALIZE_FAILED;
} catch (...) {
logger->printCritMsg("AgentThread initialize failed!");
return AGENT_THREAD_INITIALIZE_FAILED;
}
/* Invoke agent initialize of each function. */
jint result;
result = onAgentInitForSnapShot(*jvmti);
if (result == SUCCESS) {
result = onAgentInitForLog();
}
return result;
}
/*!
* \brief Agent attach entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Attach initialization result code.
*/
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) {
/* Check memory duplication run. */
CHECK_DOUBLING_RUN;
/* JVMTI Event Setup. */
jvmtiEnv *jvmti;
int result = CommonInitialization(vm, &jvmti, options);
if (result != SUCCESS) {
/* Failure event setup. */
return result;
}
/* Call common initialize. */
return InitEventSetting(jvmti, true);
}
/*!
* \brief Common agent unload entry points.
* \param vm [in] JavaVM object.
*/
JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm) {
JNIEnv *env = NULL;
/* Get JNI environment object. */
vm->GetEnv((void **)&env, JNI_VERSION_1_6);
/* Invoke agent finalize of snapshot function. */
onAgentFinalForSnapShot(env);
/* Invoke agent finalize of log function. */
onAgentFinalForLog(env);
/* Destroy object is JVM running informations. */
delete jvmInfo;
jvmInfo = NULL;
/* Destroy object reload signal watcher timer. */
delete intervalSigTimer;
intervalSigTimer = NULL;
/* Delete logger */
delete logger;
/* Free allocated configuration file path string. */
free(loadConfigPath);
loadConfigPath = NULL;
/* Cleanup TTrapSender. */
if (conf->SnmpSend()->get()) {
TTrapSender::finalize();
}
/* Delete configuration */
delete conf;
}
/*!
* \brief Ondemand attach's entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Ondemand-attach initialization result code.
*/
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM *vm, char *options, void *reserved) {
/* Check memory duplication run. */
CHECK_DOUBLING_RUN;
/* Call common process. */
jvmtiEnv *jvmti;
jint result = CommonInitialization(vm, &jvmti, options);
if (result != SUCCESS) {
return result;
}
/* JVMTI Event Setup. */
InitEventSetting(jvmti, false);
/* Get JNI environment object. */
JNIEnv *env;
if (vm->GetEnv((void **)&env, JNI_VERSION_1_6) != JNI_OK) {
logger->printCritMsg("Get JNI environment information failed!");
return GET_ENVIRONMENT_FAILED;
}
/* Call live step initialization. */
OnVMInit(jvmti, env, NULL);
jvmInfo->detectDelayInfoAddress();
return SUCCESS;
}
| 20,913
|
C++
|
.cpp
| 611
| 30.240589
| 82
| 0.679939
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,006
|
util.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/util.cpp
|
/*!
* \file util.cpp
* \brief This file is utilities.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "util.hpp"
/* Extern variables. */
/*!
* \brief Page size got from sysconf.
*/
long systemPageSize =
#ifdef _SC_PAGESIZE
sysconf(_SC_PAGESIZE);
#else
#ifdef _SC_PAGE_SIZE
sysconf(_SC_PAGE_SIZE);
#else
/* Suppose system page size to be 4KiByte. */
4 * 1024;
#endif
#endif
/* Functions. */
/*!
* \brief JVMTI error detector.
* \param jvmti [in] JVMTI envrionment object.
* \param error [in] JVMTI error code.
* \return Param "error" is error code?(true/false)
*/
bool isError(jvmtiEnv *jvmti, jvmtiError error) {
/* If param "error" is error code. */
if (unlikely(error != JVMTI_ERROR_NONE)) {
/* Get and output error message. */
char *errStr = NULL;
jvmti->GetErrorName(error, &errStr);
logger->printWarnMsg(errStr);
jvmti->Deallocate((unsigned char *)errStr);
return true;
}
return false;
}
/*!
* \brief Get system information.
* \param env [in] JNI envrionment.
* \param key [in] System property key.
* \return String of system property.
*/
char *GetSystemProperty(JNIEnv *env, const char *key) {
/* Convert string. */
jstring key_str = env->NewStringUTF(key);
/* Search class. */
jclass sysClass = env->FindClass("Ljava/lang/System;");
/* if raised exception. */
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
env->ExceptionClear();
logger->printWarnMsg("Get system class failed !");
return NULL;
}
/* Search method. */
jmethodID System_getProperty = env->GetStaticMethodID(
sysClass, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
/* If raised exception. */
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
env->ExceptionClear();
logger->printWarnMsg("Get system method failed !");
return NULL;
}
/* Call method in find class. */
jstring ret_str = (jstring)env->CallStaticObjectMethod(
sysClass, System_getProperty, key_str);
/* If got nothing or raised exception. */
if ((ret_str == NULL) || env->ExceptionOccurred()) {
env->ExceptionDescribe();
env->ExceptionClear();
logger->printWarnMsg("Get system properties failed !");
return NULL;
}
/* Get result and clean up. */
const char *ret_utf8 = env->GetStringUTFChars(ret_str, NULL);
char *ret = NULL;
/* If raised exception. */
if (env->ExceptionOccurred()) {
env->ExceptionDescribe();
env->ExceptionClear();
} else if (ret_utf8 != NULL) {
/* Copy and free if got samething. */
ret = strdup(ret_utf8);
env->ReleaseStringUTFChars(ret_str, ret_utf8);
}
/* Cleanup. */
env->DeleteLocalRef(key_str);
return ret;
}
/*!
* \brief Get ClassUnload event index.
* \param jvmti [in] JVMTI envrionment object.
* \return ClassUnload event index.
* \sa hotspot/src/share/vm/prims/jvmtiExport.cpp<br>
* hotspot/src/share/vm/prims/jvmtiEventController.cpp<br>
* hotspot/src/share/vm/prims/jvmti.xml<br>
* in JDK.
*/
jint GetClassUnloadingExtEventIndex(jvmtiEnv *jvmti) {
jint count, ret = -1;
jvmtiExtensionEventInfo *events;
/* Get extension events. */
if (isError(jvmti, jvmti->GetExtensionEvents(&count, &events))) {
/* Failure get extension events. */
logger->printWarnMsg("Get JVMTI Extension Event failed!");
return -1;
} else if (count <= 0) {
/* If extension event is none. */
logger->printWarnMsg("VM has no JVMTI Extension Event!");
if (events != NULL) {
jvmti->Deallocate((unsigned char *)events);
}
return -1;
}
/* Check extension events. */
for (int Cnt = 0; Cnt < count; Cnt++) {
if (strcmp(events[Cnt].id, "com.sun.hotspot.events.ClassUnload") == 0) {
ret = events[Cnt].extension_event_index;
break;
}
}
/* Clean up. */
for (int Cnt = 0; Cnt < count; Cnt++) {
jvmti->Deallocate((unsigned char *)events[Cnt].id);
jvmti->Deallocate((unsigned char *)events[Cnt].short_description);
for (int Cnt2 = 0; Cnt2 < events[Cnt].param_count; Cnt2++) {
jvmti->Deallocate((unsigned char *)events[Cnt].params[Cnt2].name);
}
jvmti->Deallocate((unsigned char *)events[Cnt].params);
}
jvmti->Deallocate((unsigned char *)events);
return ret;
}
/*!
* \brief Replace old string in new string on string.
* \param str [in] Process target string.
* \param oldStr [in] Targer of replacing.
* \param newStr [in] A string will replace existing string.
* \return String invoked replace.<br>Don't forget deallocate.
*/
char *strReplase(char const *str, char const *oldStr, char const *newStr) {
char *strPos = NULL;
char *chrPos = NULL;
int oldStrCnt = 0;
int oldStrLen = 0;
char *newString = NULL;
int newStrLen = 0;
/* Sanity check. */
if (unlikely(str == NULL || oldStr == NULL || newStr == NULL ||
strlen(str) == 0 || strlen(oldStr) == 0)) {
logger->printWarnMsg("Illegal string replacing paramters.");
return NULL;
}
oldStrLen = strlen(oldStr);
strPos = (char *)str;
/* Counting oldStr */
while (true) {
/* Find old string. */
chrPos = strstr(strPos, oldStr);
if (chrPos == NULL) {
/* All old string is already found. */
break;
}
/* Counting. */
oldStrCnt++;
/* Move next. */
strPos = chrPos + oldStrLen;
}
newStrLen = strlen(newStr);
/* Allocate result string memory. */
newString = (char *)calloc(
1, strlen(str) + (newStrLen * oldStrCnt) - (oldStrLen * oldStrCnt) + 1);
/* If failure allocate result string. */
if (unlikely(newString == NULL)) {
logger->printWarnMsg("Failure allocate replaced string.");
return NULL;
}
strPos = (char *)str;
while (true) {
/* Find old string. */
chrPos = strstr(strPos, oldStr);
if (unlikely(chrPos == NULL)) {
/* all old string is replaced. */
strcat(newString, strPos);
break;
}
/* Copy from string exclude old string. */
strncat(newString, strPos, (chrPos - strPos));
/* Copy from new string. */
strcat(newString, newStr);
/* Move next. */
strPos = chrPos + oldStrLen;
}
/* Succeed. */
return newString;
}
/*!
* \brief Get now date and time.
* \return Mili-second elapsed time from 1970/1/1 0:00:00.
*/
jlong getNowTimeSec(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
return (jlong)tv.tv_sec * 1000 + (jlong)tv.tv_usec / 1000;
}
/*!
* \brief A little sleep.
* \param sec [in] Second of sleep range.
* \param nsec [in] Nano second of sleep range.
*/
void littleSleep(const long int sec, const long int nsec) {
/* Timer setting variables. */
int result = 0;
struct timespec buf1;
struct timespec buf2 = {sec, nsec};
struct timespec *req = &buf1;
struct timespec *rem = &buf2;
/* Wait loop. */
do {
/* Reset and exchange time. */
memset(req, 0, sizeof(timespec));
struct timespec *tmp = req;
req = rem;
rem = tmp;
errno = 0;
/* Sleep. */
result = nanosleep(req, rem);
} while (result != 0 && errno == EINTR);
}
/*!
* \brief Get thread information.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param thread [in] Thread object in java.
* \param info [out] Record stored thread information.
*/
void getThreadDetailInfo(jvmtiEnv *jvmti, JNIEnv *env, jthread thread,
TJavaThreadInfo *info) {
/* Get thread basic information. */
jvmtiThreadInfo threadInfo = {0};
if (unlikely(isError(jvmti, jvmti->GetThreadInfo(thread, &threadInfo)))) {
/* Setting dummy information. */
info->name = strdup("Unknown-Thread");
info->isDaemon = false;
info->priority = 0;
} else {
/* Setting information. */
info->name = strdup(threadInfo.name);
info->isDaemon = (threadInfo.is_daemon == JNI_TRUE);
info->priority = threadInfo.priority;
/* Cleanup. */
jvmti->Deallocate((unsigned char *)threadInfo.name);
env->DeleteLocalRef(threadInfo.thread_group);
env->DeleteLocalRef(threadInfo.context_class_loader);
}
/* Get thread state. */
jint state = 0;
jvmti->GetThreadState(thread, &state);
/* Set thread state. */
switch (state & JVMTI_JAVA_LANG_THREAD_STATE_MASK) {
case JVMTI_JAVA_LANG_THREAD_STATE_NEW:
info->state = strdup("NEW");
break;
case JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED:
info->state = strdup("TERMINATED");
break;
case JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE:
info->state = strdup("RUNNABLE");
break;
case JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED:
info->state = strdup("BLOCKED");
break;
case JVMTI_JAVA_LANG_THREAD_STATE_WAITING:
info->state = strdup("WAITING");
break;
case JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING:
info->state = strdup("TIMED_WAITING");
break;
default:
info->state = NULL;
}
}
/*!
* \brief Get method information in designed stack frame.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param frame [in] method stack frame.
* \param info [out] Record stored method information in stack frame.
*/
void getMethodFrameInfo(jvmtiEnv *jvmti, JNIEnv *env, jvmtiFrameInfo frame,
TJavaStackMethodInfo *info) {
char *tempStr = NULL;
jclass declareClass = NULL;
/* Get method class. */
if (unlikely(isError(jvmti, jvmti->GetMethodDeclaringClass(frame.method,
&declareClass)))) {
info->className = NULL;
info->sourceFile = NULL;
} else {
/* Get class signature. */
if (unlikely(isError(
jvmti, jvmti->GetClassSignature(declareClass, &tempStr, NULL)))) {
info->className = NULL;
} else {
info->className = strdup(tempStr);
jvmti->Deallocate((unsigned char *)tempStr);
}
/* Get source filename. */
if (unlikely(
isError(jvmti, jvmti->GetSourceFileName(declareClass, &tempStr)))) {
info->sourceFile = NULL;
} else {
info->sourceFile = strdup(tempStr);
jvmti->Deallocate((unsigned char *)tempStr);
}
env->DeleteLocalRef(declareClass);
}
/* Get method name. */
if (unlikely(isError(
jvmti, jvmti->GetMethodName(frame.method, &tempStr, NULL, NULL)))) {
info->methodName = NULL;
} else {
info->methodName = strdup(tempStr);
jvmti->Deallocate((unsigned char *)tempStr);
}
/* Check method is native. */
jboolean isNativeMethod = JNI_TRUE;
jvmti->IsMethodNative(frame.method, &isNativeMethod);
if (unlikely(isNativeMethod == JNI_TRUE)) {
/* method is native. */
info->isNative = true;
info->lineNumber = -1;
} else {
/* method is java method. */
info->isNative = false;
/* Get source code line number. */
jint entriyCount = 0;
jvmtiLineNumberEntry *entries = NULL;
if (unlikely(isError(jvmti, jvmti->GetLineNumberTable(
frame.method, &entriyCount, &entries)))) {
/* Method location is unknown. */
info->lineNumber = -1;
} else {
/* Search running line. */
jint lineIdx = 0;
entriyCount--;
for (; lineIdx < entriyCount; lineIdx++) {
if (frame.location <= entries[lineIdx].start_location) {
break;
}
}
info->lineNumber = entries[lineIdx].line_number;
jvmti->Deallocate((unsigned char *)entries);
}
}
}
| 12,254
|
C++
|
.cpp
| 377
| 28.153846
| 82
| 0.654682
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,007
|
snapShotMain.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/snapShotMain.cpp
|
/*!
* \file snapShotMain.cpp
* \brief This file is used to take snapshot.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <sched.h>
#ifdef HAVE_ATOMIC
#include <atomic>
#else
#include <cstdatomic>
#endif
#include "globals.hpp"
#include "vmFunctions.hpp"
#include "elapsedTimer.hpp"
#include "util.hpp"
#include "callbackRegister.hpp"
#include "snapShotMain.hpp"
/* Struct defines. */
/*!
* \brief This structure is stored snapshot and class heap usage.
*/
typedef struct {
TSnapShotContainer *snapshot; /*!< Container of taking snapshot. */
TClassCounter *counter; /*!< Counter of class heap usage. */
} TCollectContainers;
/* Variable defines. */
/*!
* \brief ClassData Container.
*/
TClassContainer *clsContainer = NULL;
/*!
* \brief SnapShot Processor.
*/
TSnapShotProcessor *snapShotProcessor = NULL;
/*!
* \brief GC Watcher.
*/
TGCWatcher *gcWatcher = NULL;
/*!
* \brief Timer Thread.
*/
TTimer *timer = NULL;
/*!
* \brief Pthread mutex for user data dump request.<br>
* E.g. continue pushing dump key.<br>
* <br>
* This mutex used in below process.<br>
* - OnDataDumpRequest @ snapShotMain.cpp<br>
* To avoid a lot of data dump request parallel processing.<br>
*/
pthread_mutex_t dumpMutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
/*!
* \brief Pthread mutex for JVMTI IterateOverHeap calling.<br>
* <br>
* This mutex used in below process.<br>
* - TakeSnapShot @ snapShotMain.cpp<br>
* To avoid taking double snapshot use JVMTI.<br>
* Because agent cann't distinguish called from where in hook function.<br>
*/
pthread_mutex_t jvmtiMutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
/*!
* \brief Snapshot container instance queue to waiting output.
*/
TSnapShotQueue snapStockQueue;
/*!
* \brief Container instance stored got snapshot by GC.
*/
TSnapShotContainer *snapshotByGC = NULL;
/*!
* \brief Container instance stored got snapshot by CMSGC.
*/
TSnapShotContainer *snapshotByCMS = NULL;
/*!
* \brief Container instance stored got snapshot by interval or dump request.
*/
TSnapShotContainer *snapshotByJvmti = NULL;
/*!
* \brief Index of JVM class unloading event.
*/
int classUnloadEventIdx = -1;
/*!
* \brief processing flag
*/
static std::atomic_int processing(0);
/* Function defines. */
/*!
* \brief Count object size in Heap.
* \param clsTag [in] Tag of object's class.
* \param size [in] Object size.
* \param objTag [in,out] Object's tag.
* \param userData [in,out] User's data.
*/
jvmtiIterationControl JNICALL HeapObjectCallBack(jlong clsTag, jlong size,
jlong *objTag,
void *userData) {
/* This callback is dummy. */
return JVMTI_ITERATION_ABORT;
}
/*!
* \brief New class loaded event.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param thread [in] Java thread object.
* \param klass [in] Newly loaded class object.
*/
void JNICALL
OnClassPrepare(jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jclass klass) {
TProcessMark mark(processing);
/*
* Wait if VM is at a safepoint which includes safepoint synchronizing,
* because jclass (oop in JNIHandle) might be relocated.
*/
while (!isAtNormalExecution()) {
sched_yield();
}
/* Get klassOop. */
void *mirror = *(void **)klass;
void *klassOop = TVMFunctions::getInstance()->AsKlassOop(mirror);
if (likely(klassOop != NULL)) {
/* Push new loaded class. */
clsContainer->pushNewClass(klassOop);
}
}
/*!
* \brief Setting JVM information to snapshot.
* \param snapshot [in] Snapshot instance.
* \param cause [in] Cause of taking a snapshot.<br>
* e.g. GC, DumpRequest or Interval.
*/
inline void setSnapShotInfo(TInvokeCause cause, TSnapShotContainer *snapshot) {
/* Get now date and time. */
struct timeval tv;
gettimeofday(&tv, NULL);
/* Set snapshot information. */
snapshot->setSnapShotTime((jlong)tv.tv_sec * 1000 + (jlong)tv.tv_usec / 1000);
snapshot->setSnapShotCause(cause);
snapshot->setJvmInfo(jvmInfo);
}
/*!
* \brief Add snapshot to outputing wait queue.
* \param snapshot [in] Snapshot instance.
* \return Process result.<br>
* Maybe failed to add snapshot to queue, if value is false.<br>
* So that, you should be additionally handling snapshot instance.
*/
inline bool addSnapShotQueue(TSnapShotContainer *snapshot) {
snapStockQueue.push(snapshot);
return true;
}
/*!
* \brief Pop snapshot from wait queue for output.
* \return Snapshot instance.<br>
* Maybe queue is empty, if value is NULL.
*/
inline TSnapShotContainer *popSnapShotQueue(void) {
TSnapShotContainer *snapshot = NULL;
bool succeeded = snapStockQueue.try_pop(snapshot);
return succeeded ? snapshot : NULL;
}
/*!
* \brief Notify to processor for output snapshot to file.
* \param snapshot [in] Snapshot instance.
* \warning After this function has called, Don't use a param "snapshot" again.
*/
inline void notifySnapShot(TSnapShotContainer *snapshot) {
try {
/* Sending notification means able to output file. */
snapShotProcessor->notify(snapshot);
} catch (...) {
logger->printWarnMsg("Snapshot processeor notify failed!.");
TSnapShotContainer::releaseInstance(snapshot);
}
}
/*!
* \brief Set information and push waiting queue.
* \param snapshot [in] Snapshot instance.
*/
inline void outputSnapShotByGC(TSnapShotContainer *snapshot) {
setSnapShotInfo(GC, snapshot);
/* Standby for next GC. */
jvmInfo->resumeGCinfo();
/* If failed to push waiting queue. */
if (unlikely(!addSnapShotQueue(snapshot))) {
TSnapShotContainer::releaseInstance(snapshot);
}
/* Send notification. */
gcWatcher->notify();
}
/*!
* \brief Interrupt inner garbage collection event.
* Call this function when JVM invoke many times of GC process
* during single JVMTI event of GC start and GC finish.
*/
void onInnerGarbageCollectionInterrupt(void) {
/* Standby for next GC. */
jvmInfo->resumeGCinfo();
/* Clear unfinished snapshot data. */
snapshotByGC->clear(false);
}
/*!
* \brief Before garbage collection event.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnGarbageCollectionStart(jvmtiEnv *jvmti) {
TProcessMark mark(processing);
snapshotByGC = TSnapShotContainer::getInstance();
/* Enable inner GC event. */
setupHookForInnerGCEvent(true, &onInnerGarbageCollectionInterrupt);
}
/*!
* \brief After garbage collection event.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnGarbageCollectionFinish(jvmtiEnv *jvmti) {
TProcessMark mark(processing);
/* Disable inner GC event. */
setupHookForInnerGCEvent(false, NULL);
/* If need getting snapshot. */
if (gcWatcher->needToStartGCTrigger()) {
/* Set information and push waiting queue. */
outputSnapShotByGC(snapshotByGC);
} else {
TSnapShotContainer::releaseInstance(snapshotByGC);
}
snapshotByGC = NULL;
}
/*!
* \brief After G1 garbage collection event.
*/
void OnG1GarbageCollectionFinish(void) {
// jvmInfo->loadGCCause();
jvmInfo->SetUnknownGCCause();
/* Set information and push waiting queue. */
outputSnapShotByGC(snapshotByGC);
snapshotByGC = TSnapShotContainer::getInstance();
}
/*!
* \brief Get class information.
* \param klassOop [in] Pointer of child java class object(KlassOopDesc).
* \return Pointer of information of expceted class by klassOop.
*/
inline TObjectData *getObjectDataFromKlassOop(void *klassOop) {
TObjectData *clsData = clsContainer->findClass(klassOop);
if (unlikely(clsData == NULL)) {
/* Push new loaded class to root class container. */
clsData = clsContainer->pushNewClass(klassOop);
}
return clsData;
}
/*!
* \brief Iterate oop field object callback for GC and JVMTI snapshot.
* \param oop [in] Java heap object(Inner class format).
* \param data [in] User expected data.
*/
void iterateFieldObjectCallBack(void *oop, void *data) {
TCollectContainers *containerInfo = (TCollectContainers *)data;
void *klassOop = getKlassOopFromOop(oop);
/* Sanity check. */
if (unlikely(klassOop == NULL || containerInfo == NULL)) {
return;
}
TSnapShotContainer *snapshot = containerInfo->snapshot;
TClassCounter *parentCounter = containerInfo->counter;
TChildClassCounter *clsCounter = NULL;
/* Search child class. */
clsCounter = snapshot->findChildClass(parentCounter, klassOop);
if (unlikely(clsCounter == NULL)) {
/* Get child class information. */
TObjectData *clsData = getObjectDataFromKlassOop(klassOop);
/* Push new child loaded class. */
clsCounter = snapshot->pushNewChildClass(parentCounter, clsData);
}
if (unlikely(clsCounter == NULL)) {
logger->printCritMsg("Couldn't get class counter!");
return;
}
TVMFunctions *vmFunc = TVMFunctions::getInstance();
jlong size = 0;
if (clsCounter->objData->oopType == otInstance) {
if (likely(clsCounter->objData->instanceSize != 0)) {
size = clsCounter->objData->instanceSize;
} else {
vmFunc->GetObjectSize(NULL, (jobject)&oop, &size);
clsCounter->objData->instanceSize = size;
}
} else {
vmFunc->GetObjectSize(NULL, (jobject)&oop, &size);
}
/* Count perent class size and instance count. */
snapshot->FastInc(clsCounter->counter, size);
}
/*!
* \brief Calculate size of object and iterate child-class in heap.
* \param snapshot [in] Snapshot instance.
* \param oop [in] Java heap object(Inner class format).
*/
inline void calculateObjectUsage(TSnapShotContainer *snapshot, void *oop) {
void *klassOop = getKlassOopFromOop(oop);
/* Sanity check. */
if (unlikely(snapshot == NULL || klassOop == NULL)) {
return;
}
snapshot->setIsCleared(false);
TClassCounter *clsCounter = NULL;
TObjectData *clsData = NULL;
/* Get class information. */
clsData = getObjectDataFromKlassOop(klassOop);
if (unlikely(clsData == NULL)) {
logger->printCritMsg("Couldn't get ObjectData!");
return;
}
/* Search class. */
clsCounter = snapshot->findClass(clsData);
if (unlikely(clsCounter == NULL)) {
/* Push new loaded class. */
clsCounter = snapshot->pushNewClass(clsData);
}
if (unlikely(clsCounter == NULL)) {
logger->printCritMsg("Couldn't get class counter!");
return;
}
TVMFunctions *vmFunc = TVMFunctions::getInstance();
TOopType oopType = clsData->oopType;
jlong size = 0;
if (oopType == otInstance) {
if (likely(clsData->instanceSize != 0)) {
size = clsData->instanceSize;
} else {
vmFunc->GetObjectSize(NULL, (jobject)&oop, &size);
clsData->instanceSize = size;
}
} else {
vmFunc->GetObjectSize(NULL, (jobject)&oop, &size);
}
/* Count perent class size and instance count. */
snapshot->FastInc(clsCounter->counter, size);
/* If we should not collect reftree or oop has no field. */
if (!conf->CollectRefTree()->get() || !hasOopField(oopType)) {
return;
}
TCollectContainers containerInfo;
containerInfo.snapshot = snapshot;
containerInfo.counter = clsCounter;
TOopMapBlock *offsets = NULL;
int offsetCount = 0;
offsets = clsCounter->offsets;
offsetCount = clsCounter->offsetCount;
/* If offset list is unused yet. */
if (unlikely(offsets == NULL && offsetCount < 0)) {
/* Generate offset list. */
generateIterateFieldOffsets(klassOop, oopType, &offsets, &offsetCount);
clsCounter->offsets = offsets;
clsCounter->offsetCount = offsetCount;
}
/* Iterate non-static field objects. */
iterateFieldObject(&iterateFieldObjectCallBack, oop, oopType, &offsets,
&offsetCount, &containerInfo);
}
/*!
* \brief Count object size in heap by GC.
* \param oop [in] Java heap object(Inner class format).
* \param data [in] User expected data. Always this value is NULL.
*/
void HeapObjectCallbackOnGC(void *oop, void *data) {
/* Calculate and merge to GC snapshot. */
calculateObjectUsage(snapshotByGC, oop);
}
/*!
* \brief Count object size in heap by CMSGC.
* \param oop [in] Java heap object(Inner class format).
* \param data [in] User expected data. Always this value is NULL.
*/
void HeapObjectCallbackOnCMS(void *oop, void *data) {
/* Calculate and merge to CMSGC snapshot. */
calculateObjectUsage(snapshotByCMS, oop);
}
/*!
* \brief Count object size in heap by JVMTI iterateOverHeap.
* \param oop [in] Java heap object(Inner class format).
* \param data [in] User expected data. Always this value is NULL.
*/
void HeapObjectCallbackOnJvmti(void *oop, void *data) {
/* Calculate and merge to JVMTI snapshot. */
calculateObjectUsage(snapshotByJvmti, oop);
}
/*!
* \brief This function is for class oop adjust callback by GC.
* \param oldOop [in] Old pointer of java class object(KlassOopDesc).
* \param newOop [in] New pointer of java class object(KlassOopDesc).
*/
void HeapKlassAdjustCallback(void *oldOop, void *newOop) {
/* Class information update. */
clsContainer->updateClass(oldOop, newOop);
}
/*!
* \brief Event of before garbage collection by CMS collector.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnCMSGCStart(jvmtiEnv *jvmti) {
TProcessMark mark(processing);
/* Get CMS state. */
bool needShapShot = false;
int cmsState = checkCMSState(gcStart, &needShapShot);
/* If occurred snapshot target GC. */
if (needShapShot) {
/* If need getting snapshot. */
if (gcWatcher->needToStartGCTrigger()) {
/* Set information and push waiting queue. */
outputSnapShotByGC(snapshotByCMS);
snapshotByCMS = NULL;
}
}
if (likely(snapshotByGC == NULL)) {
snapshotByGC = TSnapShotContainer::getInstance();
} else {
snapshotByGC->clear(false);
}
if (likely(snapshotByCMS == NULL)) {
snapshotByCMS = TSnapShotContainer::getInstance();
} else if (cmsState == CMS_FINALMARKING) {
snapshotByCMS->clear(false);
}
/* Enable inner GC event. */
setupHookForInnerGCEvent(true, &onInnerGarbageCollectionInterrupt);
}
/*!
* \brief Event of after garbage collection by CMS collector.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnCMSGCFinish(jvmtiEnv *jvmti) {
TProcessMark mark(processing);
/* Disable inner GC event. */
setupHookForInnerGCEvent(false, NULL);
/* Get CMS state. */
bool needShapShot = false;
checkCMSState(gcFinish, &needShapShot);
/* If occurred snapshot target GC. */
if (needShapShot) {
/* If need getting snapshot. */
if (gcWatcher->needToStartGCTrigger()) {
/* Set information and push waiting queue. */
outputSnapShotByGC(snapshotByGC);
snapshotByGC = NULL;
snapshotByCMS->clear(false);
}
}
}
/*!
* \brief Data dump request event for snapshot.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnDataDumpRequestForSnapShot(jvmtiEnv *jvmti) {
TProcessMark mark(processing);
TMutexLocker locker(&dumpMutex);
/* Avoid the plural simultaneous take snapshot by dump-request. */
/* E.g. keeping pushed dump key. */
/* Because classContainer register a redundancy class in TakeSnapShot. */
TakeSnapShot(jvmti, NULL, DataDumpRequest);
}
/*!
* \brief Take a heap information snapshot.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Cause of taking a snapshot.<br>
* e.g. GC, DumpRequest or Interval.
*/
void TakeSnapShot(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause) {
TProcessMark mark(processing);
TVMVariables *vmVal = TVMVariables::getInstance();
/*
* Initial Mark is 1st phase in CMS.
* So we can process the SnapShot in SnapShot queue.
*/
if (vmVal->getUseCMS() &&
(vmVal->getCMS_collectorState() > CMS_INITIALMARKING)) {
logger->printWarnMsg("CMS GC is working. Skip to take a SnapShot.");
TSnapShotContainer *snapshot = popSnapShotQueue();
if (likely(snapshot != NULL)) {
TSnapShotContainer::releaseInstance(snapshot);
}
return;
}
/* Count working time. */
static const char *label = "Take SnapShot";
TElapsedTimer elapsedTime(label);
/* Phase1: Heap Walking. */
jvmtiError error = JVMTI_ERROR_INTERNAL;
if (cause != GC) {
TSnapShotContainer *snapshot = TSnapShotContainer::getInstance();
if (likely(snapshot != NULL)) {
/* Lock to avoid doubling call JVMTI. */
TMutexLocker locker(&jvmtiMutex);
snapshotByJvmti = snapshot;
/* Enable JVMTI hooking. */
if (likely(setJvmtiHookState(true))) {
/* Count object size on heap. */
error = jvmti->IterateOverHeap(JVMTI_HEAP_OBJECT_EITHER,
&HeapObjectCallBack, NULL);
/* Disable JVMTI hooking. */
setJvmtiHookState(false);
}
snapshotByJvmti = NULL;
}
if (likely(error == JVMTI_ERROR_NONE)) {
setSnapShotInfo(cause, snapshot);
/* If failed to push waiting queue. */
if (unlikely(!addSnapShotQueue(snapshot))) {
error = JVMTI_ERROR_OUT_OF_MEMORY;
}
}
if (unlikely(error != JVMTI_ERROR_NONE)) {
/* Process failure. So data is junk. */
TSnapShotContainer::releaseInstance(snapshot);
}
} else {
/*
* If cause is "GC", then we already collect heap object to snapshot
* by override functions exist in "overrideBody.S".
*/
error = JVMTI_ERROR_NONE;
}
/* Phase2: Output snapshot. */
/* If failure count object size. */
if (unlikely(isError(jvmti, error))) {
logger->printWarnMsg("Heap snapshot failed!");
} else {
/* Pop snapshot. */
TSnapShotContainer *snapshot = popSnapShotQueue();
if (likely(snapshot != NULL)) {
/* Set total memory. */
snapshot->setTotalSize(jvmInfo->getTotalMemory());
/* Notify to processor. */
notifySnapShot(snapshot);
}
}
/* Phase3: Reset Timer. */
if (conf->TimerInterval()->get() > 0) {
/* Sending notification means reset timer. */
timer->notify();
}
}
/*!
* \brief Setting enable of JVMTI and extension events for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param enable [in] Event notification is enable.
* \return Setting process result.
*/
jint setEventEnableForSnapShot(jvmtiEnv *jvmti, bool enable) {
jvmtiEventMode mode = enable ? JVMTI_ENABLE : JVMTI_DISABLE;
/* Switch date dump event. */
if (conf->TriggerOnDump()->get()) {
TDataDumpRequestCallback::switchEventNotification(jvmti, mode);
}
/* Switch gc events. */
if (conf->TriggerOnFullGC()->get() &&
!TVMVariables::getInstance()->getUseG1()) {
/* Switch JVMTI GC events. */
TGarbageCollectionStartCallback::switchEventNotification(jvmti, mode);
TGarbageCollectionFinishCallback::switchEventNotification(jvmti, mode);
}
return SUCCESS;
}
/*!
* \brief Setting enable of agent each threads for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param enable [in] Event notification is enable.
*/
void setThreadEnableForSnapShot(jvmtiEnv *jvmti, JNIEnv *env, bool enable) {
/* Start or suspend HeapStats agent threads. */
try {
/* Switch GC watcher state. */
if (conf->TriggerOnFullGC()->get()) {
if (enable) {
gcWatcher->start(jvmti, env);
} else {
gcWatcher->stop();
}
if (TVMVariables::getInstance()->getUseG1()) {
if (snapshotByGC == NULL) {
snapshotByGC = TSnapShotContainer::getInstance();
} else {
snapshotByGC->clear(false);
}
}
/* Switch GC hooking state. */
setGCHookState(enable);
}
/* Switch interval snapshot timer state. */
if (conf->TimerInterval()->get() > 0) {
if (enable) {
/* MS to Sec */
timer->start(jvmti, env, conf->TimerInterval()->get() * 1000);
} else {
timer->stop();
}
}
/* Switch snapshot processor state. */
if (enable) {
snapShotProcessor->start(jvmti, env);
} else {
snapShotProcessor->stop();
}
} catch (const char *errMsg) {
logger->printWarnMsg(errMsg);
}
}
/*!
* \brief Clear current SnapShot.
*/
void clearCurrentSnapShot() {
snapshotByGC->clear(false);
}
/*!
* \brief JVM initialization event for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMInitForSnapShot(jvmtiEnv *jvmti, JNIEnv *env) {
size_t maxMemSize = jvmInfo->getMaxMemory();
/* Setup for hooking. */
setupHook(&HeapObjectCallbackOnGC, &HeapObjectCallbackOnCMS,
&HeapObjectCallbackOnJvmti, &HeapKlassAdjustCallback,
&OnG1GarbageCollectionFinish, maxMemSize);
/* JVMTI Extension Event Setup. */
int eventIdx = GetClassUnloadingExtEventIndex(jvmti);
/*
* JVMTI extension event is influenced by JVM's implementation.
* Extension event may no exist , if JVM was a little updated.
* This is JVMTI's Specifications.
* So result is disregard, even if failure processed extension event.
*/
if (eventIdx < 0) {
/* Miss get extension event list. */
logger->printWarnMsg("Couldn't get ClassUnload event.");
} else {
/* if failed to set onClassUnload event. */
if (isError(jvmti, jvmti->SetExtensionEventCallback(
eventIdx, (jvmtiExtensionEvent)&OnClassUnload))) {
/* Failure setting extension event. */
logger->printWarnMsg("Couldn't register ClassUnload event.");
} else {
classUnloadEventIdx = eventIdx;
}
}
}
/*!
* \brief JVM finalization event for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMDeathForSnapShot(jvmtiEnv *jvmti, JNIEnv *env) {
if (TVMVariables::getInstance()->getUseCMS()) {
/* Disable inner GC event. */
setupHookForInnerGCEvent(false, NULL);
/* Get CMS state. */
bool needShapShot = false;
checkCMSState(gcLast, &needShapShot);
/* If occurred snapshot target GC. */
if (needShapShot && snapshotByCMS != NULL) {
/* Output snapshot. */
outputSnapShotByGC(snapshotByCMS);
snapshotByCMS = NULL;
}
}
TSnapShotContainer *snapshot = popSnapShotQueue();
/* Output all waiting snapshot. */
while (snapshot != NULL) {
snapshot->setTotalSize(jvmInfo->getTotalMemory());
notifySnapShot(snapshot);
snapshot = popSnapShotQueue();
}
/* Disable class prepare/unload events. */
TClassPrepareCallback::switchEventNotification(jvmti, JVMTI_DISABLE);
if (likely(classUnloadEventIdx >= 0)) {
jvmti->SetExtensionEventCallback(classUnloadEventIdx, NULL);
}
/* Wait until all tasks are finished. */
while (processing > 0) {
sched_yield();
}
/* Destroy object that is each snapshot trigger. */
delete gcWatcher;
gcWatcher = NULL;
delete timer;
timer = NULL;
}
/*!
* \brief Agent initialization for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \return Initialize process result.
*/
jint onAgentInitForSnapShot(jvmtiEnv *jvmti) {
/* Initialize oop util. */
if (unlikely(!oopUtilInitialize(jvmti))) {
logger->printCritMsg(
"Please check installation and version of java and debuginfo "
"packages.");
return GET_LOW_LEVEL_INFO_FAILED;
}
/* Initialize snapshot containers. */
if (unlikely(!TSnapShotContainer::globalInitialize())) {
logger->printCritMsg("TSnapshotContainer initialize failed!");
return CLASSCONTAINER_INITIALIZE_FAILED;
}
/* Initialize TClassContainer. */
try {
clsContainer = new TClassContainer();
} catch (...) {
logger->printCritMsg("TClassContainer initialize failed!");
return CLASSCONTAINER_INITIALIZE_FAILED;
}
/* Create thread instances that controlled snapshot trigger. */
try {
gcWatcher = new TGCWatcher(&TakeSnapShot, jvmInfo);
snapShotProcessor = new TSnapShotProcessor(clsContainer, jvmInfo);
timer = new TTimer(&TakeSnapShot, "HeapStats Snapshot Timer");
} catch (const char *errMsg) {
logger->printCritMsg(errMsg);
return AGENT_THREAD_INITIALIZE_FAILED;
} catch (...) {
logger->printCritMsg("AgentThread initialize failed!");
return AGENT_THREAD_INITIALIZE_FAILED;
}
return SUCCESS;
}
/*!
* \brief Agent finalization for snapshot function.
* \param env [in] JNI environment object.
*/
void onAgentFinalForSnapShot(JNIEnv *env) {
/* Destroy SnapShot Processor instance. */
delete snapShotProcessor;
snapShotProcessor = NULL;
/*
* Delete snapshot instances
*/
if (snapshotByCMS != NULL) {
TSnapShotContainer::releaseInstance(snapshotByCMS);
}
if (snapshotByGC != NULL) {
TSnapShotContainer::releaseInstance(snapshotByGC);
}
/* Finalize and deallocate old snapshot containers. */
TSnapShotContainer::globalFinalize();
/* Destroy object that is for snapshot. */
delete clsContainer;
clsContainer = NULL;
/* Finalize oop util. */
oopUtilFinalize();
}
| 25,900
|
C++
|
.cpp
| 766
| 30.191906
| 82
| 0.701828
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,008
|
gcWatcher.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/gcWatcher.cpp
|
/*!
* \file gcWatcher.cpp
* \brief This file is used to take snapshot when finish garbage collection.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "gcWatcher.hpp"
/*!
* \brief TGCWatcher constructor.
* \param postGCFunc [in] Callback is called after GC.
* \param info [in] JVM running performance information.
*/
TGCWatcher::TGCWatcher(TPostGCFunc postGCFunc, TJvmInfo *info)
: TAgentThread("HeapStats GC Watcher") {
/* Sanity check. */
if (postGCFunc == NULL) {
throw "Event callback is NULL.";
}
if (info == NULL) {
throw "TJvmInfo is NULL.";
}
/* Setting parameter. */
this->_postGCFunc = postGCFunc;
this->pJvmInfo = info;
this->_FGC = 0;
}
/*!
* \brief TGCWatcher destructor.
*/
TGCWatcher::~TGCWatcher(void) { /* Do nothing. */ }
/*!
* \brief JThread entry point.
* \param jvmti [in] JVMTI environment object.
* \param jni [in] JNI environment object.
* \param data [in] Pointer of user data.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-label"
void JNICALL TGCWatcher::entryPoint(jvmtiEnv *jvmti, JNIEnv *jni, void *data) {
/* Get self. */
TGCWatcher *controller = (TGCWatcher *)data;
/* Change running state. */
controller->_isRunning = true;
/* Loop for agent run. */
while (true) {
/* Variable for notification flag. */
bool needProcess = false;
{
TMutexLocker locker(&controller->mutex);
if (controller->_terminateRequest) {
break;
}
/* If no exists request. */
if (likely(controller->_numRequests == 0)) {
/* Wait for notification or termination. */
pthread_cond_wait(&controller->mutexCond, &controller->mutex);
}
RACE_COND_DEBUG_POINT:
/* If waiting finished by notification. */
if (likely(controller->_numRequests > 0)) {
controller->_numRequests--;
needProcess = true;
}
}
/* If waiting finished by notification. */
if (needProcess) {
/* Call event callback. */
(*controller->_postGCFunc)(jvmti, jni, GC);
}
}
/* Change running state. */
controller->_isRunning = false;
}
#pragma GCC diagnostic pop
/*!
* \brief Make and begin Jthread.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void TGCWatcher::start(jvmtiEnv *jvmti, JNIEnv *env) {
/* Check JVM information. */
if (this->pJvmInfo->getFGCCount() < 0) {
logger->printWarnMsg("All GC accept as youngGC.");
} else {
/* Reset now full gc count. */
this->_FGC = this->pJvmInfo->getFGCCount();
}
/* Start jThread. */
TAgentThread::start(jvmti, env, TGCWatcher::entryPoint, this,
JVMTI_THREAD_MAX_PRIORITY);
}
| 3,502
|
C++
|
.cpp
| 106
| 29.424528
| 82
| 0.682047
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,009
|
vmStructScanner.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/vmStructScanner.cpp
|
/*!
* \file vmStructScanner.cpp
* \brief This file is used to getting JVM structure information.<br>
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <dlfcn.h>
#include "vmStructScanner.hpp"
/* Macros. */
/*!
* \brief Symbol of VMStruct entry macro.
*/
#define SYMBOL_VMSTRUCTS "gHotSpotVMStructs"
/*!
* \brief Symbol of VMTypes entry macro.
*/
#define SYMBOL_VMTYPES "gHotSpotVMTypes"
/*!
* \brief Symbol of VMIntConstants entry macro.
*/
#define SYMBOL_VMINTCONSTANTS "gHotSpotVMIntConstants"
/*!
* \brief Symbol of VMLongConstants entry macro.
*/
#define SYMBOL_VMLONGCONSTANTS "gHotSpotVMLongConstants"
/* Hotspot JVM information. */
/*!
* \brief Pointer of Hotspot JVM information.
*/
VMStructEntry **TVMStructScanner::vmStructEntries = NULL;
/*!
* \brief Pointer of hotspot's inner class information.
*/
VMTypeEntry **TVMStructScanner::vmTypeEntries = NULL;
/*!
* \brief Pointer of hotspot constant integer information.
*/
VMIntConstantEntry **TVMStructScanner::vmIntConstEntries = NULL;
/*!
* \brief Pointer of hotspot constant long integer information.
*/
VMLongConstantEntry **TVMStructScanner::vmLongConstEntries = NULL;
/* Class function. */
/*!
* \brief TVMStructScanner constructor.
* \param finder [in] Symbol search object.
*/
TVMStructScanner::TVMStructScanner(TSymbolFinder *finder) {
if (unlikely(vmStructEntries == NULL)) {
/* Get VMStructs. */
vmStructEntries = (VMStructEntry **)dlsym(RTLD_DEFAULT, SYMBOL_VMSTRUCTS);
if (unlikely(vmStructEntries == NULL)) {
vmStructEntries = (VMStructEntry **)finder->findSymbol(SYMBOL_VMSTRUCTS);
}
if (unlikely(vmStructEntries == NULL)) {
throw "Not found java symbol. symbol:" SYMBOL_VMSTRUCTS;
}
}
if (unlikely(vmTypeEntries == NULL)) {
/* Get VMTypes. */
vmTypeEntries = (VMTypeEntry **)dlsym(RTLD_DEFAULT, SYMBOL_VMTYPES);
if (unlikely(vmTypeEntries == NULL)) {
vmTypeEntries = (VMTypeEntry **)finder->findSymbol(SYMBOL_VMTYPES);
}
if (unlikely(vmTypeEntries == NULL)) {
throw "Not found java symbol. symbol:" SYMBOL_VMTYPES;
}
}
if (unlikely(vmIntConstEntries == NULL)) {
/* Get VMIntConstants. */
vmIntConstEntries =
(VMIntConstantEntry **)dlsym(RTLD_DEFAULT, SYMBOL_VMINTCONSTANTS);
if (unlikely(vmIntConstEntries == NULL)) {
vmIntConstEntries =
(VMIntConstantEntry **)finder->findSymbol(SYMBOL_VMINTCONSTANTS);
}
if (unlikely(vmIntConstEntries == NULL)) {
throw "Not found java symbol. symbol:" SYMBOL_VMINTCONSTANTS;
}
}
if (unlikely(vmLongConstEntries == NULL)) {
/* Get VMLongConstants. */
vmLongConstEntries =
(VMLongConstantEntry **)dlsym(RTLD_DEFAULT, SYMBOL_VMLONGCONSTANTS);
if (unlikely(vmLongConstEntries == NULL)) {
vmLongConstEntries =
(VMLongConstantEntry **)finder->findSymbol(SYMBOL_VMLONGCONSTANTS);
}
if (unlikely(vmLongConstEntries == NULL)) {
throw "Not found java symbol. symbol:" SYMBOL_VMLONGCONSTANTS;
}
}
}
/*!
* \brief Get offset data from JVM inner struct.
* \param ofsMap [out] Map of search offset target.
*/
void TVMStructScanner::GetDataFromVMStructs(TOffsetNameMap *ofsMap) {
/* Sanity check. */
if (unlikely((ofsMap == NULL) || (this->vmStructEntries == NULL))) {
return;
}
/* Check map entry. */
for (TOffsetNameMap *ofs = ofsMap; ofs->className != NULL; ofs++) {
/* Search JVM inner struct entry. */
for (VMStructEntry *entry = *this->vmStructEntries; entry->typeName != NULL;
entry++) {
if ((strcmp(entry->typeName, ofs->className) == 0) &&
(strcmp(entry->fieldName, ofs->fieldName) == 0)) {
/* If entry is expressing static field. */
if (entry->isStatic) {
*ofs->addr = entry->address;
} else {
*ofs->ofs = entry->offset;
}
break;
}
}
}
}
/*!
* \brief Get type size data from JVM inner struct.
* \param typeMap [out] Map of search constant target.
*/
void TVMStructScanner::GetDataFromVMTypes(TTypeSizeMap *typeMap) {
/* Sanity check. */
if (unlikely((typeMap == NULL) || (this->vmTypeEntries == NULL))) {
return;
}
/* Search JVM inner struct entry. */
for (TTypeSizeMap *types = typeMap; types->typeName != NULL; types++) {
/* Check map entry. */
for (VMTypeEntry *entry = *this->vmTypeEntries; entry->typeName != NULL;
entry++) {
if (strcmp(entry->typeName, types->typeName) == 0) {
*types->size = entry->size;
break;
}
}
}
}
/*!
* \brief Get int constant data from JVM inner struct.
* \param constMap [out] Map of search constant target.
*/
void TVMStructScanner::GetDataFromVMIntConstants(TIntConstMap *constMap) {
/* Sanity check. */
if (unlikely((constMap == NULL) || (this->vmIntConstEntries == NULL))) {
return;
}
/* Search JVM inner struct entry. */
for (TIntConstMap *consts = constMap; consts->name != NULL; consts++) {
/* Check map entry. */
for (VMIntConstantEntry *entry = *this->vmIntConstEntries;
entry->name != NULL; entry++) {
if (strcmp(entry->name, consts->name) == 0) {
*consts->value = entry->value;
break;
}
}
}
}
/*!
* \brief Get long constant data from JVM inner struct.
* \param constMap [out] Map of search constant target.
*/
void TVMStructScanner::GetDataFromVMLongConstants(TLongConstMap *constMap) {
/* Sanity check. */
if (unlikely((constMap == NULL) || (this->vmLongConstEntries == NULL))) {
return;
}
/* Search JVM inner struct entry. */
for (TLongConstMap *consts = constMap; consts->name != NULL; consts++) {
/* Check map entry. */
for (VMLongConstantEntry *entry = *this->vmLongConstEntries;
entry->name != NULL; entry++) {
if (strcmp(entry->name, consts->name) == 0) {
*consts->value = entry->value;
break;
}
}
}
}
| 6,686
|
C++
|
.cpp
| 197
| 29.949239
| 82
| 0.680805
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,010
|
snapShotProcessor.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/snapShotProcessor.cpp
|
/*!
* \file snapShotProcessor.cpp
* \brief This file is used to output ranking and call snapshot function.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "elapsedTimer.hpp"
#include "fsUtil.hpp"
#include "snapShotProcessor.hpp"
/*!
* \brief TSnapShotProcessor constructor.
* \param clsContainer [in] Class container object.
* \param info [in] JVM running performance information.
*/
TSnapShotProcessor::TSnapShotProcessor(TClassContainer *clsContainer,
TJvmInfo *info)
: TAgentThread("HeapStats SnapShot Processor"), snapQueue() {
/* Sanity check. */
if (clsContainer == NULL) {
throw "TClassContainer is NULL.";
}
if (info == NULL) {
throw "TJvmInfo is NULL.";
}
/* Setting parameter. */
this->_container = clsContainer;
this->jvmInfo = info;
}
/*!
* \brief TSnapShotProcessor destructor.
*/
TSnapShotProcessor::~TSnapShotProcessor(void) { /* Do Nothing. */ }
/*!
* \brief Parallel work function by JThread.
* \param jvmti [in] JVMTI environment information.
* \param jni [in] JNI environment information.
* \param data [in] Monitor-object for class-container.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-label"
void JNICALL
TSnapShotProcessor::entryPoint(jvmtiEnv *jvmti, JNIEnv *jni, void *data) {
/* Ranking pointer. */
TSorter<THeapDelta> *ranking = NULL;
/* Get self. */
TSnapShotProcessor *controller = (TSnapShotProcessor *)data;
/* Change running state. */
controller->_isRunning = true;
bool existRemainder = false;
/* Loop for agent run or remaining work exist. */
while (true) {
TSnapShotContainer *snapshot = NULL;
/* Is notify flag. */
bool needProcess = false;
{
TMutexLocker locker(&controller->mutex);
if (unlikely(controller->_terminateRequest && !existRemainder)) {
break;
}
if (likely(controller->_numRequests == 0)) {
/* Wait for notification or termination. */
pthread_cond_wait(&controller->mutexCond, &controller->mutex);
}
RACE_COND_DEBUG_POINT:
/* If get notification means output. */
if (likely(controller->_numRequests > 0)) {
controller->_numRequests--;
needProcess = true;
controller->snapQueue.try_pop(snapshot);
}
/* Check remaining work. */
existRemainder = (controller->_numRequests > 0);
}
/* If waiting is finished by notification. */
if (needProcess && (snapshot != NULL)) {
int result = 0;
{
/* Count working time. */
static const char *label = "Write SnapShot and calculation";
TElapsedTimer elapsedTime(label);
/* Output class-data. */
result = controller->_container->afterTakeSnapShot(snapshot, &ranking);
}
/* If raise disk full error. */
if (unlikely(isRaisedDiskFull(result))) {
checkDiskFull(result, "snapshot");
}
/* Output snapshot infomartion. */
snapshot->printGCInfo();
/* If output failure. */
if (likely(ranking != NULL)) {
/* Show class ranking. */
if (conf->RankLevel()->get() > 0) {
controller->showRanking(snapshot->getHeader(), ranking);
}
}
/* Clean up. */
TSnapShotContainer::releaseInstance(snapshot);
delete ranking;
ranking = NULL;
}
}
/* Change running state. */
controller->_isRunning = false;
}
#pragma GCC diagnostic pop
/*!
* \brief Start parallel work by JThread.
* \param jvmti [in] JVMTI environment information.
* \param env [in] JNI environment information.
*/
void TSnapShotProcessor::start(jvmtiEnv *jvmti, JNIEnv *env) {
/* Start JThread. */
TAgentThread::start(jvmti, env, TSnapShotProcessor::entryPoint, this,
JVMTI_THREAD_MIN_PRIORITY);
}
/*!
* \brief Notify output snapshot to this thread from other thread.
* \param snapshot [in] Output snapshot instance.
*/
void TSnapShotProcessor::notify(TSnapShotContainer *snapshot) {
/* Sanity check. */
if (unlikely(snapshot == NULL)) {
return;
}
bool raiseException = true;
/* Send notification and count notify. */
{
TMutexLocker locker(&this->mutex);
try {
/* Store and count data. */
snapQueue.push(snapshot);
this->_numRequests++;
/* Notify occurred deadlock. */
pthread_cond_signal(&this->mutexCond);
/* Reset exception flag. */
raiseException = false;
} catch (...) {
/*
* Maybe faield to allocate memory at "std:queue<T>::push()".
* So we throw exception again at after release lock.
*/
}
}
if (unlikely(raiseException)) {
throw "Failed to TSnapShotProcessor notify";
}
}
/*!
* \brief Show ranking.
* \param hdr [in] Snapshot file information.
* \param data [in] All class-data.
*/
void TSnapShotProcessor::showRanking(const TSnapShotFileHeader *hdr,
TSorter<THeapDelta> *data) {
/* Get now datetime. */
char time_str[20];
struct tm time_struct;
/* snapshot time is "msec" */
jlong snapDate = hdr->snapShotTime / 1000;
/* "time_t" is defined as type has 8byte size in 32bit. */
/* But jlong is defined as type has 16byte size in 32bit and 64bit. */
/* So this part need cast-code for 32bit. */
localtime_r((const time_t *)&snapDate, &time_struct);
strftime(time_str, 20, "%F %T", &time_struct);
/* Output ranking header. */
switch (hdr->cause) {
case GC:
logger->printInfoMsg("Heap Ranking at %s (caused by GC, GCCause: %s)",
time_str, hdr->gcCause);
break;
case DataDumpRequest:
logger->printInfoMsg("Heap Ranking at %s (caused by DataDumpRequest)",
time_str);
break;
case Interval:
logger->printInfoMsg("Heap Ranking at %s (caused by Interval)");
break;
default:
/* Illegal value. */
logger->printInfoMsg("Heap Ranking at %s (caused by UNKNOWN)");
logger->printWarnMsg("Illegal snapshot cause!");
return;
}
/* Output ranking column. */
logger->printInfoMsg("Rank usage(byte) increment(byte) Class name");
logger->printInfoMsg("---- --------------- --------------- ----------");
/* Output high-rank class information. */
int rankCnt = data->getCount();
Node<THeapDelta> *aNode = data->lastNode();
for (int Cnt = 0; Cnt < rankCnt && aNode != NULL;
Cnt++, aNode = aNode->prev) {
/* Output header. */
#ifdef LP64
logger->printInfoMsg("%4d %15ld %15ld %s",
#else
logger->printInfoMsg("%4d %15lld %15lld %s",
#endif
Cnt + 1, aNode->value.usage, aNode->value.delta,
((TObjectData *)aNode->value.tag)->className);
}
/* Clean up after ranking output. */
logger->flush();
}
| 7,619
|
C++
|
.cpp
| 219
| 29.684932
| 82
| 0.650733
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,011
|
cmdArchiver.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/cmdArchiver.cpp
|
/*!
* \file cmdArchiver.cpp
* \brief This file is used create archive file by command line.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <string.h>
#include <sys/wait.h>
#include "globals.hpp"
#include "util.hpp"
#include "cmdArchiver.hpp"
/*!
* \brief TCmdArchiver constructor.
*/
TCmdArchiver::TCmdArchiver(void) : TArchiveMaker() { /* Do Nothing. */ }
/*!
* \brief TCmdArchiver destructor.
*/
TCmdArchiver::~TCmdArchiver(void) { /* Do Nothing. */ }
/*!
* \brief Do file archive and create archive file.
* \param env [in] JNI environment object.
* \param archiveFile [in] archive file name.
* \return Process result code of create archive.
*/
int TCmdArchiver::doArchive(JNIEnv *env, char const *archiveFile) {
/* If Source file is empty. */
if (unlikely(strlen(this->getTarget()) == 0 || archiveFile == NULL ||
strlen(archiveFile) == 0 ||
conf->ArchiveCommand()->get() == NULL)) {
logger->printWarnMsg("Illegal archive paramter.");
clear();
return -1;
}
/* Copy command line. */
char *cmdline = strdup(conf->ArchiveCommand()->get());
if (unlikely(cmdline == NULL)) {
/* Failure copy string. */
logger->printWarnMsg("Couldn't allocate command line memory.");
clear();
return -1;
}
/* Setting replace rule. */
const int ruleCount = 2;
const char *sourceRule[ruleCount] = {"%logdir%", "%archivefile%"};
char *destRule[ruleCount] = {NULL, NULL};
destRule[0] = (char *)this->getTarget();
destRule[1] = (char *)archiveFile;
/* Replace paramters. */
for (int i = 0; i < ruleCount; i++) {
/* Replace with rule. */
char *afterStr = NULL;
afterStr = strReplase(cmdline, (char *)sourceRule[i], destRule[i]);
if (unlikely(afterStr == NULL)) {
/* Failure replace string. */
logger->printWarnMsg("Failure parse command line.");
free(cmdline);
clear();
return -1;
}
/* Cleanup and swap. */
free(cmdline);
cmdline = afterStr;
}
/* Exec command. */
int result = execute(cmdline);
/* Check archive file. */
struct stat st = {0};
if (unlikely(stat(archiveFile, &st) != 0)) {
/* If process is succeed but archive isn't exists. */
if (unlikely(result == 0)) {
/* Accept as failure. */
result = -1;
}
} else {
/* If process is failed but archive is still existing. */
if (unlikely(result != 0)) {
/* Remove file. Because it's maybe broken. */
unlink(archiveFile);
}
}
/* Cleanup. */
free(cmdline);
clear();
/* Succeed. */
return result;
}
/*!
* \brief Execute command line.
* \param cmdline [in] String of execute command.
* \return Response code of execute commad line.
*/
int TCmdArchiver::execute(char *cmdline) {
/* Variable for result code. */
int result = 0;
/* Enviroment variable for execve. */
char *envParam[] = {NULL};
/* Convert string to array. */
char **argArray = strToArray(cmdline);
if (unlikely(argArray == NULL)) {
/* Failure string to array string. */
logger->printWarnMsg("Couldn't allocate command line memory.");
return -1;
}
/* Fork process without copy. */
pid_t forkPid = vfork();
switch (forkPid) {
case -1:
/* Error vfork. */
result = errno;
logger->printWarnMsgWithErrno("Could not fork child process.");
break;
case 0:
/* Child process. */
/* Exec commad line. */
if (unlikely(execve(argArray[0], argArray, envParam) < 0)) {
/* Failure execute command line. */
_exit(errno);
}
/* Stopper for illegal route. */
_exit(-99);
default:
/* Parent Process. */
/* Wait child process. */
int st = 0;
if (unlikely(waitpid(forkPid, &st, 0) < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not wait command process.");
}
/* If process is failure. */
if (unlikely(!WIFEXITED(st) || WEXITSTATUS(st) != 0)) {
/* Failure execve, catch signal, etc.. */
if (WIFEXITED(st)) {
result = WEXITSTATUS(st);
} else {
result = -1;
}
logger->printWarnMsg("Failure execute archive command.");
}
}
/* Cleanup. */
free(argArray[0]);
free(argArray);
return result;
}
/*!
* \brief Convert string separated by space to string array.
* \param str [in] Separated string by space.
* \return Arrayed string.<br>Don't forget deallocate.<br>
* Value is null, if process failure or param is illegal.
*/
char **TCmdArchiver::strToArray(char *str) {
/* String separator. */
const char SEPARATOR_CHAR = ' ';
/* Sanity check. */
if (unlikely(str == NULL || strlen(str) == 0)) {
return NULL;
}
/* Count arguments. */
size_t argCount = 0;
size_t newStrSize = 0;
size_t oldStrLen = strlen(str);
for (size_t i = 0; i < oldStrLen;) {
size_t strSize = 0;
/* Skip string. */
while (i < oldStrLen && str[i] != SEPARATOR_CHAR) {
i++;
strSize++;
}
/* If exists string, then count separate string. */
if (strSize > 0) {
argCount++;
newStrSize += strSize + 1;
}
/* Skip a string separator sequence. */
while (i < oldStrLen && str[i] == SEPARATOR_CHAR) {
i++;
}
}
/* If string is separator char only. */
if (unlikely(argCount == 0)) {
return NULL;
}
/* Allocate string. */
char *tempStr = (char *)malloc(newStrSize + 1);
if (unlikely(tempStr == NULL)) {
return NULL;
}
/* Allocate string array. */
char **argArray = (char **)malloc(sizeof(char *) * (argCount + 1));
if (unlikely(argArray == NULL)) {
free(tempStr);
return NULL;
}
/* Parse string line to array. */
size_t argIdx = 0;
for (size_t i = 0; i < oldStrLen;) {
size_t oldIdx = i;
size_t strSize = 0;
/* Skip string. */
while (i < oldStrLen && str[i] != SEPARATOR_CHAR) {
i++;
strSize++;
}
/* If exists string, then separate string. */
if (strSize > 0) {
/* Copy string. */
strncpy(tempStr, &str[oldIdx], strSize);
tempStr[strSize] = '\0';
argArray[argIdx] = tempStr;
/* Move next. */
tempStr += strSize + 1;
argIdx++;
}
/* Skip and replace a string separator sequence. */
while (i < oldStrLen && str[i] == SEPARATOR_CHAR) {
i++;
}
}
/* Add end flag. */
argArray[argCount] = NULL;
return argArray;
}
| 7,198
|
C++
|
.cpp
| 237
| 25.945148
| 82
| 0.621711
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,012
|
oopUtil.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/oopUtil.cpp
|
/*!
* \file oopUtil.cpp
* \brief This file is used to getting information inner JVM.<br>
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "vmFunctions.hpp"
#include "oopUtil.hpp"
/* Variable for class object. */
TSymbolFinder *symFinder = NULL;
TVMStructScanner *vmScanner = NULL;
/* Macros. */
/*!
* \brief Calculate pointer align macro.
*/
#define ALIGN_POINTER_OFFSET(size) \
(ALIGN_SIZE_UP((size), TVMVariables::getInstance()->getHeapWordsPerLong()))
/* Function. */
/* Function for utilities. */
/*!
* \brief Convert COOP(narrowKlass) to wide Klass(normally Klass).
* \param narrowKlass [in] Java Klass object(compressed Klass pointer).
* \return Wide Klass object.
*/
inline void *getWideKlass(unsigned int narrowKlass) {
TVMVariables *vmVal = TVMVariables::getInstance();
/*
* narrowKlass decoding is defined in
* inline Klass* Klass::decode_klass_not_null(narrowKlass v)
* hotspot/src/share/vm/oops/klass.inline.hpp
*/
return (
void *)(vmVal->getNarrowKlassOffsetBase() +
((ptrdiff_t)narrowKlass << vmVal->getNarrowKlassOffsetShift()));
}
/*!
* \brief Getting oop's class information(It's "Klass", not "KlassOop").
* \param klassOop [in] Java heap object(Inner "KlassOop" class).
* \return Class information object(Inner "Klass" class).
*/
void *getKlassFromKlassOop(void *klassOop) {
if (unlikely(klassOop == NULL || jvmInfo->isAfterCR6964458())) {
return klassOop;
}
return incAddress(klassOop,
TVMVariables::getInstance()->getClsSizeKlassOop());
}
/*!
* \brief Getting oop's class information(It's "Klass", not "KlassOop").
* \param oop [in] Java heap object(Inner class format).
* \return Class information object.
* \sa oopDesc::klass()<br>
* at hotspot/src/share/vm/oops/oop.inline.hpp in JDK.
*/
void *getKlassOopFromOop(void *oop) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* Sanity check. */
if (unlikely(oop == NULL)) {
return NULL;
}
void *tempAddr = NULL;
/* If JVM use "C"ompressed "OOP". */
if (vmVal->getIsCOOP()) {
/* Get oop's klassOop from "_compressed_klass" field. */
unsigned int *testAddr =
(unsigned int *)((ptrdiff_t)oop + vmVal->getOfsCoopKlassAtOop());
if (likely(testAddr != NULL)) {
/* Decode COOP. */
tempAddr = getWideKlass(*testAddr);
}
} else {
/* Get oop's klassOop from "_klass" field. */
void **testAddr = (void **)incAddress(oop, vmVal->getOfsKlassAtOop());
if (likely(testAddr != NULL)) {
tempAddr = (*testAddr);
}
}
return tempAddr;
}
/*!
* \brief Getting class's name form java inner class.
* \param klass [in] Java class object(Inner class format).
* \return String of object class name.<br>
* Don't forget deallocate if value isn't null.
*/
char *getClassName(void *klass) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* Sanity check. */
if (unlikely(klass == NULL)) {
return NULL;
}
/* Get class symbol information. */
void **klassSymbol = (void **)incAddress(klass, vmVal->getOfsNameAtKlass());
if (unlikely(klassSymbol == NULL || (*klassSymbol) == NULL)) {
return NULL;
}
/* Get class name pointer. */
char *name = (char *)incAddress((*klassSymbol), vmVal->getOfsBodyAtSymbol());
if (unlikely(name == NULL)) {
return NULL;
}
bool isInstanceClass = (*name != '[');
/* Get class name size. */
unsigned short len = *(unsigned short *)incAddress(
(*klassSymbol), vmVal->getOfsLengthAtSymbol());
char *str = NULL;
/* If class is instance class. */
if (isInstanceClass) {
/* Add length of "L" and ";". */
str = (char *)malloc(len + 3);
} else {
/* Get string memory. */
str = (char *)malloc(len + 1);
}
if (likely(str != NULL)) {
/* Get class name. */
if (isInstanceClass) {
/* Copy class name if class is instance class. */
/* As like "instanceKlass::signature_name()". */
str[0] = 'L';
// memcpy(&str[1], name, len);
__builtin_memcpy(&str[1], name, len);
str[len + 1] = ';';
str[len + 2] = '\0';
} else {
/* Copy class name if class is other. */
// memcpy(str, name, len);
__builtin_memcpy(str, name, len);
str[len] = '\0';
}
}
return str;
}
/*!
* \brief Is marked object on CMS bitmap.
* \param oop [in] Java heap object(Inner class format).
* \return Value is true, if object is marked.
*/
inline bool isMarkedObject(void *oop) {
TVMVariables *vmVal = TVMVariables::getInstance();
size_t idx = (((ptrdiff_t)oop - (ptrdiff_t)vmVal->getCmsBitMap_startWord()) >>
((unsigned)vmVal->getLogHeapWordSize() +
(unsigned)vmVal->getCmsBitMap_shifter()));
size_t mask = (size_t)1 << (idx & vmVal->getBitsPerWordMask());
return (((size_t *)vmVal->getCmsBitMap_startAddr())[(
idx >> vmVal->getLogBitsPerWord())] &
mask) != 0;
}
/*!
* \brief Get first field object block for "InstanceKlass".
* \param klassOop [in] Class information object(Inner "Klass" class).
* \return Oop's field information inner class object("OopMapBlock" class).
* \sa hotspot/src/share/vm/oops/instanceKlass.hpp
* InstanceKlass::start_of_static_fields()
*/
inline void *getBeginBlock(void *klassOop) {
TVMVariables *vmVal = TVMVariables::getInstance();
/*
* Memory map of "klass(InstanceKlass)" class.
* - Klass object head pointer -
* - OopDesc -
* - InstanceKlass -
* - Java's v-table -
* - Java's i-table -
* - Static field oops(Notice) -
* - Non-Static field oops -
* Notice - By CR7017732, this area is removed.
*/
void *klass = getKlassFromKlassOop(klassOop);
if (unlikely(klass == NULL)) {
return NULL;
}
/* Move to v-table head. */
off_t ofsStartVTable =
jvmInfo->isAfterCR6964458()
? ALIGN_POINTER_OFFSET(vmVal->getClsSizeInstanceKlass() /
vmVal->getHeapWordSize())
: ALIGN_POINTER_OFFSET(
(vmVal->getClsSizeOopDesc() / vmVal->getHeapWordSize()) +
(vmVal->getClsSizeInstanceKlass() / vmVal->getHeapWordSize()));
void *startVTablePtr = (intptr_t *)klassOop + ofsStartVTable;
int vTableLen =
*(int *)incAddress(klass, vmVal->getOfsVTableSizeAtInsKlass());
/* Increment v-table size. */
void *startITablePtr =
(intptr_t *)startVTablePtr + ALIGN_POINTER_OFFSET(vTableLen);
int iTableLen =
*(int *)incAddress(klass, vmVal->getOfsITableSizeAtInsKlass());
/* Increment i-table size. */
void *startStaticFieldPtr =
(intptr_t *)startITablePtr + ALIGN_POINTER_OFFSET(iTableLen);
if (jvmInfo->isAfterCR7017732()) {
return startStaticFieldPtr;
}
/* Increment static field size. */
int staticFieldSize =
*(int *)incAddress(klass, vmVal->getOfsStaticFieldSizeAtInsKlass());
return (intptr_t *)startStaticFieldPtr + staticFieldSize;
}
/*!
* \brief Get number of field object blocks for "InstanceKlass".
* \param instanceKlass [in] Class information object about "InstanceKlass".
* (Inner "Klass" class)
* \return Oop's field information inner class object("OopMapBlock" class).
* \sa hotspot/src/share/vm/oops/instanceKlass.hpp
* InstanceKlass::nonstatic_oop_map_count()
*/
inline int getBlockCount(void *instanceKlass) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* Get total field size. */
int nonstaticFieldSize =
*(int *)incAddress(instanceKlass,
vmVal->getOfsNonstaticOopMapSizeAtInsKlass());
/* Get single field size. */
int sizeInWord =
ALIGN_SIZE_UP(sizeof(TOopMapBlock), vmVal->getHeapWordSize()) >>
vmVal->getLogHeapWordSize();
/* Calculate number of fields. */
return nonstaticFieldSize / sizeInWord;
}
/*!
* \brief Get class loader that loaded expected class as KlassOop.
* \param klassName [in] String of target class name (JNI class format).
* \return Java heap object which is class loader load expected the class.
*/
TOopType getClassType(const char *klassName) {
TOopType result = otIllegal;
if (likely(klassName != NULL)) {
if (*(unsigned short *)klassName == HEADER_KLASS_ARRAY_ARRAY) {
result = otArrayArray;
} else if (*(unsigned short *)klassName == HEADER_KLASS_OBJ_ARRAY) {
result = otObjArarry;
} else if (*klassName == HEADER_KLASS_ARRAY) {
result = otArray;
} else {
/* Expected class name is instance class. */
result = otInstance;
}
}
return result;
}
/*!
* \brief Get class loader that loaded expected class as KlassOop.
* \param klassOop [in] Class information object(Inner "Klass" class).
* \param type [in] KlassOop type.
* \return Java heap object which is class loader load expected the class.
*/
void *getClassLoader(void *klassOop, const TOopType type) {
TVMFunctions *vmFunc = TVMFunctions::getInstance();
void *classLoader = NULL;
void *klass = getKlassFromKlassOop(klassOop);
/* Sanity check. */
if (unlikely(klassOop == NULL || klass == NULL)) {
return NULL;
}
switch (type) {
case otObjArarry:
classLoader = vmFunc->GetClassLoaderForObjArrayKlass(klass);
break;
case otInstance:
classLoader = vmFunc->GetClassLoaderForInstanceKlass(klass);
break;
case otArray:
case otArrayArray:
/*
* This type oop has no class loader.
* Because such oop is loaded by system bootstrap class loader.
* Or the class is loaded at system initialize (e.g. "Universe").
*/
default:
;
}
return classLoader;
}
/* Function for callback. */
/*!
* \brief Follow oop field block.
* \param event [in] Callback function.
* \param fieldOops [in] Pointer of field block head.
* \param count [in] Count of field block.
* \param data [in] User expected data.
*/
inline void followFieldBlock(THeapObjectCallback event, void **fieldOops,
const unsigned int count, void *data) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* Follow oop at each block. */
for (unsigned int idx = 0; idx < count; idx++) {
void *childOop = NULL;
/* Sanity check. */
if (unlikely(fieldOops == NULL)) {
continue;
}
/* Get child oop and move next array item. */
if (vmVal->getIsCOOP()) {
/* If this field is not null. */
if (likely((*(unsigned int *)fieldOops) != 0)) {
childOop = getWideOop(*(unsigned int *)fieldOops);
}
fieldOops = (void **)((unsigned int *)fieldOops + 1);
} else {
childOop = *fieldOops++;
}
/* Check oops isn't in permanent generation. */
if (childOop != NULL && !is_in_permanent(collectedHeap, childOop)) {
/* Invoke callback. */
event(childOop, data);
}
}
}
/*!
* \brief Generate oop field offset cache.
* \param klassOop [in] Target class object(klassOop format).
* \param oopType [in] Type of inner "Klass" type.
* \param offsets [out] Field offset array.<br />
* Please don't forget deallocate this value.
* \param count [out] Count of field offset array.
*/
void generateIterateFieldOffsets(void *klassOop, TOopType oopType,
TOopMapBlock **offsets, int *count) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* Sanity check. */
if (unlikely(klassOop == NULL || offsets == NULL || count == NULL)) {
return;
}
void *klass = getKlassFromKlassOop(klassOop);
if (unlikely(klass == NULL)) {
return;
}
TOopMapBlock *block = NULL;
/* Get field blocks. */
switch (oopType) {
case otInstance: {
int blockCount = getBlockCount(klass);
TOopMapBlock *mapBlock = (TOopMapBlock *)getBeginBlock(klassOop);
/* Allocate block offset records. */
block = (TOopMapBlock *)malloc(sizeof(TOopMapBlock) * blockCount);
if (likely(mapBlock != NULL && block != NULL && blockCount > 0)) {
/* Follow each block. */
for (int i = 0; i < blockCount; i++) {
/* Store block information. */
block[i].offset = mapBlock->offset;
block[i].count = mapBlock->count;
/* Go next block. */
mapBlock++;
}
(*offsets) = block;
(*count) = blockCount;
} else {
/* If class has no field. */
if (blockCount == 0) {
(*offsets) = NULL;
(*count) = 0;
}
/* Deallocate memory. */
free(block);
}
break;
}
case otObjArarry:
/* Allocate a block offset record. */
block = (TOopMapBlock *)malloc(sizeof(TOopMapBlock));
if (likely(block != NULL)) {
/*
* Get array's length field and array field offset.
* But such fields isn't define by C++. So be cafeful.
* Please see below source file about detail implementation.
* hostpost/src/share/vm/oops/arrayOop.hpp
*/
block->count =
vmVal->getIsCOOP()
? (vmVal->getOfsKlassAtOop() + vmVal->getClsSizeNarrowOop())
: vmVal->getClsSizeArrayOopDesc();
block->offset =
ALIGN_SIZE_UP(block->count + sizeof(int), vmVal->getHeapWordSize());
(*offsets) = block;
(*count) = 1;
}
break;
default:
/* The oop has no field. */
;
}
}
/*!
* \brief Iterate oop's field oops.
* \param event [in] Callback function.
* \param oop [in] Itearate target object(OopDesc format).
* \param oopType [in] Type of oop's class.
* \param ofsData [in,out] Cache data for iterate oop fields.<br />
* If value is null, then create and set cache data.
* \param ofsDataSize [in,out] Cache data count.<br />
* If value is null, then set count of "ofsData".
* \param data [in,out] User expected data for callback.
*/
void iterateFieldObject(THeapObjectCallback event, void *oop, TOopType oopType,
TOopMapBlock **ofsData, int *ofsDataSize, void *data) {
/* Sanity check. */
if (unlikely(oop == NULL || event == NULL || ofsData == NULL ||
ofsDataSize == NULL || (*ofsData) == NULL ||
(*ofsDataSize) <= 0)) {
return;
}
/* If oop has no field. */
if (unlikely(!hasOopField(oopType))) {
return;
}
/* Use expected data by function calling arguments. */
TOopMapBlock *offsets = (*ofsData);
int offsetCount = (*ofsDataSize);
if (oopType == otInstance) {
/* Iterate each oop field block as "Instance klass". */
for (TOopMapBlock *endOfs = offsets + offsetCount; offsets < endOfs;
offsets++) {
followFieldBlock(event, (void **)incAddress(oop, offsets->offset),
offsets->count, data);
}
} else {
/* Iterate each oop field block as "ObjArray klass". */
followFieldBlock(event, (void **)incAddress(oop, offsets->offset),
*(int *)incAddress(oop, offsets->count), data);
}
}
/*!
* \brief Initialization of this util.
* \param jvmti [in] JVMTI environment object.
* \return Process result.
*/
bool oopUtilInitialize(jvmtiEnv *jvmti) {
/* Search symbol in libjvm. */
char *libPath = NULL;
jvmti->GetSystemProperty("sun.boot.library.path", &libPath);
try {
/* Create symbol finder instance. */
symFinder = new TSymbolFinder();
if (unlikely(!symFinder->loadLibrary(libPath, "libjvm.so"))) {
throw 1;
}
/* Cretae VMStruct scanner instance. */
vmScanner = new TVMStructScanner(symFinder);
} catch (...) {
logger->printCritMsg("Cannot initialize symbol finder (libjvm).");
jvmti->Deallocate((unsigned char *)libPath);
delete symFinder;
symFinder = NULL;
return false;
}
jvmti->Deallocate((unsigned char *)libPath);
bool result = true;
try {
/* Initialize TVMVariables */
TVMVariables *vmVal = TVMVariables::initialize(symFinder, vmScanner);
if (vmVal == NULL) {
logger->printCritMsg("Cannot get TVMVariables instance.");
throw 3;
}
/* Initialize TVMFunctions */
TVMFunctions *vmFunc = TVMFunctions::initialize(symFinder);
if (vmFunc == NULL) {
logger->printCritMsg("Cannot get TVMFunctions instance.");
throw 4;
}
/* Initialize overrider */
if (!initOverrider()) {
logger->printCritMsg("Cannot initialize HotSpot overrider.");
throw 5;
}
} catch (...) {
/* Deallocate memory. */
delete symFinder;
symFinder = NULL;
TVMVariables *vmVal = TVMVariables::getInstance();
if (vmVal != NULL) delete vmVal;
TVMFunctions *vmFunc = TVMFunctions::getInstance();
if (vmFunc != NULL) delete vmFunc;
result = false;
}
return result;
}
/*!
* \brief Finailization of this util.
*/
void oopUtilFinalize(void) {
delete symFinder;
symFinder = NULL;
delete vmScanner;
vmScanner = NULL;
}
| 17,805
|
C++
|
.cpp
| 502
| 30.591633
| 82
| 0.643413
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,013
|
agentThread.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/agentThread.cpp
|
/*!
* \file agentThread.cpp
* \brief This file is used to work on Jthread.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <sched.h>
#include "globals.hpp"
#include "util.hpp"
#include "agentThread.hpp"
/*!
* \brief TAgentThread constructor.
* \param name [in] Thread name.
*/
TAgentThread::TAgentThread(const char *name) {
/* Sanity check. */
if (unlikely(name == NULL)) {
throw "AgentThread name is illegal.";
}
/* Create mutex and condition. */
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&mutexCond, NULL);
/* Initialization. */
this->_numRequests = 0;
this->_terminateRequest = false;
this->_isRunning = false;
this->threadName = strdup(name);
}
/*!
* \brief TAgentThread destructor.
*/
TAgentThread::~TAgentThread(void) {
/* Destroy mutex and condition. */
pthread_cond_destroy(&mutexCond);
pthread_mutex_destroy(&mutex);
/* Cleanup. */
free(this->threadName);
}
/*!
* \brief Make and begin Jthread.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param entryPoint [in] Entry point for jThread.
* \param conf [in] Pointer of user data.
* \param prio [in] Jthread priority.
*/
void TAgentThread::start(jvmtiEnv *jvmti, JNIEnv *env,
TThreadEntryPoint entryPoint, void *conf, jint prio) {
/* Sanity check. */
if (this->_isRunning) {
logger->printWarnMsg("AgentThread already started.");
return;
}
/* Find jThread class. */
jclass threadClass = env->FindClass("Ljava/lang/Thread;");
if (unlikely(threadClass == NULL)) {
throw "Couldn't get java thread class.";
}
/* Find jThread class's constructor. */
jmethodID constructorID =
env->GetMethodID(threadClass, "<init>", "(Ljava/lang/String;)V");
if (unlikely(constructorID == NULL)) {
throw "Couldn't get java thread class's constructor.";
}
/* Create new jThread name. */
jstring jThreadName = env->NewStringUTF(threadName);
if (unlikely(jThreadName == NULL)) {
throw "Couldn't generate AgentThread name.";
}
/* Create new jThread object. */
jthread thread = env->NewObject(threadClass, constructorID, jThreadName);
if (unlikely(thread == NULL)) {
throw "Couldn't generate AgentThread instance!";
}
/* Run thread. */
if (isError(jvmti, jvmti->RunAgentThread(thread, entryPoint, conf, prio))) {
throw "Couldn't start AgentThread!";
}
}
/*!
* \brief Notify timing to this thread from other thread.
*/
void TAgentThread::notify(void) {
/* Send notification and count notify. */
TMutexLocker locker(&this->mutex);
this->_numRequests++;
pthread_cond_signal(&this->mutexCond);
}
/*!
* \brief Notify stopping to this thread from other thread.
*/
void TAgentThread::stop(void) {
/* Sanity check. */
if (!this->_isRunning) {
logger->printWarnMsg("AgentThread already finished.");
return;
}
/* Send notification and count notify. */
{
TMutexLocker locker(&this->mutex);
this->_terminateRequest = true;
pthread_cond_signal(&this->mutexCond);
}
/* SpinLock for AgentThread termination. */
while (this->_isRunning) {
sched_yield();
}
/* Clean termination flag. */
this->_terminateRequest = false;
}
/*!
* \brief Notify termination to this thread from other thread.
*/
void TAgentThread::terminate(void) {
/* Sanity check. */
if (this->_isRunning) {
stop();
}
}
| 4,180
|
C++
|
.cpp
| 133
| 28.466165
| 82
| 0.697466
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,014
|
vmVariables.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/vmVariables.cpp
|
/*!
* \file vmVariables.cpp
* \brief This file includes variables in HotSpot VM.<br>
* Copyright (C) 2014-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "vmVariables.hpp"
/* Variables */
TVMVariables *TVMVariables::inst = NULL;
/*!
* \brief Pointer of "_collectedHeap" field in Universe.<br>
* Use to calling "is_in_permanent" function.
*/
void *collectedHeap;
/*!
* \brief Constructor of TVMVariables
* \param sym [in] Symbol finder of libjvm.so .
* \param scan [in] VMStruct scanner.
*/
TVMVariables::TVMVariables(TSymbolFinder *sym, TVMStructScanner *scan)
: symFinder(sym), vmScanner(scan) {
/* Member initialization */
isCOOP = false;
useParallel = false;
useParOld = false;
useCMS = false;
useG1 = false;
CMS_collectorState = NULL;
collectedHeap = NULL;
clsSizeOopDesc = 0;
clsSizeKlassOop = 0;
clsSizeNarrowOop = 0;
clsSizeKlass = 0;
clsSizeInstanceKlass = 0;
clsSizeArrayOopDesc = 0;
ofsKlassAtOop = -1;
ofsCoopKlassAtOop = -1;
ofsMarkAtOop = -1;
ofsNameAtKlass = -1;
ofsLengthAtSymbol = -1;
ofsBodyAtSymbol = -1;
ofsVTableSizeAtInsKlass = -1;
ofsITableSizeAtInsKlass = -1;
ofsStaticFieldSizeAtInsKlass = -1;
ofsNonstaticOopMapSizeAtInsKlass = -1;
ofsKlassOffsetInBytesAtOopDesc = -1;
narrowOffsetBase = 0;
narrowOffsetShift = 0;
narrowKlassOffsetBase = 0;
narrowKlassOffsetShift = 0;
lockMaskInPlaceMarkOop = 0;
marked_value = 0;
cmsBitMap_startWord = NULL;
cmsBitMap_shifter = 0;
cmsBitMap_startAddr = NULL;
BitsPerWordMask = 0;
safePointState = NULL;
g1StartAddr = NULL;
ofsJavaThreadOsthread = -1;
ofsJavaThreadThreadObj = -1;
ofsJavaThreadThreadState = -1;
ofsThreadCurrentPendingMonitor = -1;
ofsOSThreadThreadId = -1;
ofsObjectMonitorObject = -1;
threads_lock = NULL;
youngGen = NULL;
youngGenStartAddr = NULL;
youngGenSize = 0;
#ifdef __LP64__
HeapWordSize = 8;
LogHeapWordSize = 3;
HeapWordsPerLong = 1;
LogBitsPerWord = 6;
BitsPerWord = 64;
#else
HeapWordSize = 4;
LogHeapWordSize = 2;
HeapWordsPerLong = 2;
LogBitsPerWord = 5;
BitsPerWord = 32;
#endif
}
/*!
* \brief Instance initializer.
* \param sym [in] Symbol finder of libjvm.so .
* \param scan [in] VMStruct scanner.
* \return Singleton instance of TVMVariables.
*/
TVMVariables *TVMVariables::initialize(TSymbolFinder *sym,
TVMStructScanner *scan) {
/* Create instance */
try {
inst = new TVMVariables(sym, scan);
} catch (...) {
logger->printCritMsg("Cannot initialize TVMVariables.");
return NULL;
}
bool result = inst->getUnrecognizedOptions() &&
inst->getValuesFromVMStructs() && inst->getValuesFromSymbol();
return result ? inst : NULL;
}
/*!
* \brief Get unrecognized options (-XX)
* \return Result of this function.
*/
bool TVMVariables::getUnrecognizedOptions(void) {
/* Search basically unrecognized flags. */
struct {
const char *symbolStr;
bool *flagPtr;
} flagList[] = {
#ifdef __LP64__
{"UseCompressedOops", &this->isCOOP},
#endif
{"UseParallelGC", &this->useParallel},
{"UseParallelOldGC", &this->useParOld},
{"UseConcMarkSweepGC", &this->useCMS},
{"UseG1GC", &this->useG1},
/* End marker. */
{NULL, NULL}};
for (int i = 0; flagList[i].flagPtr != NULL; i++) {
bool *tempPtr = NULL;
/* Search symbol. */
tempPtr = (bool *)symFinder->findSymbol(flagList[i].symbolStr);
if (unlikely(tempPtr == NULL)) {
logger->printCritMsg("%s not found.", flagList[i].symbolStr);
return false;
}
*(flagList[i].flagPtr) = *tempPtr;
}
/* Search "Threads_lock" symbol. */
threads_lock = symFinder->findSymbol("Threads_lock");
if (unlikely(threads_lock == NULL)) {
logger->printCritMsg("Threads_lock not found.");
return false;
}
#ifdef __LP64__
if (jvmInfo->isAfterCR6964458()) {
bool *tempPtr = NULL;
const char *target_sym = jvmInfo->isAfterCR8015107()
? "UseCompressedClassPointers"
: "UseCompressedKlassPointers";
/* Search symbol. */
tempPtr = (bool *)symFinder->findSymbol(target_sym);
if (unlikely(tempPtr == NULL)) {
logger->printCritMsg("%s not found.", target_sym);
return false;
} else {
isCOOP = *tempPtr;
}
}
#endif
logger->printDebugMsg("Compressed Class = %s", isCOOP ? "true" : "false");
return true;
}
/*!
* \brief Get HotSpot values through VMStructs.
* \return Result of this function.
*/
bool TVMVariables::getValuesFromVMStructs(void) {
TOffsetNameMap ofsMap[] = {
{"oopDesc", "_metadata._klass", &ofsKlassAtOop, NULL},
{"oopDesc", "_metadata._compressed_klass", &ofsCoopKlassAtOop, NULL},
{"oopDesc", "_mark", &ofsMarkAtOop, NULL},
{"Klass", "_name", &ofsNameAtKlass, NULL},
{"JavaThread", "_osthread", &ofsJavaThreadOsthread, NULL},
{"JavaThread", "_threadObj", &ofsJavaThreadThreadObj, NULL},
{"JavaThread", "_thread_state", &ofsJavaThreadThreadState, NULL},
{"Thread", "_current_pending_monitor", &ofsThreadCurrentPendingMonitor,
NULL},
{"OSThread", "_thread_id", &ofsOSThreadThreadId, NULL},
{"ObjectMonitor", "_object", &ofsObjectMonitorObject, NULL},
/*
* For CR6990754.
* Use native memory and reference counting to implement SymbolTable.
*/
{"symbolOopDesc", "_length", &ofsLengthAtSymbol, NULL},
{"symbolOopDesc", "_body", &ofsBodyAtSymbol, NULL},
{"Symbol", "_length", &ofsLengthAtSymbol, NULL},
{"Symbol", "_body", &ofsBodyAtSymbol, NULL},
{"instanceKlass", "_vtable_len", &ofsVTableSizeAtInsKlass, NULL},
{"instanceKlass", "_itable_len", &ofsITableSizeAtInsKlass, NULL},
{"instanceKlass", "_static_field_size", &ofsStaticFieldSizeAtInsKlass,
NULL},
{"instanceKlass", "_nonstatic_oop_map_size",
&ofsNonstaticOopMapSizeAtInsKlass, NULL},
/* For CR6964458 */
{"InstanceKlass", "_vtable_len", &ofsVTableSizeAtInsKlass, NULL},
{"InstanceKlass", "_itable_len", &ofsITableSizeAtInsKlass, NULL},
{"InstanceKlass", "_static_field_size", &ofsStaticFieldSizeAtInsKlass,
NULL},
{"InstanceKlass", "_nonstatic_oop_map_size",
&ofsNonstaticOopMapSizeAtInsKlass, NULL},
/* For JDK-8148047 */
{"Klass", "_vtable_len", &ofsVTableSizeAtInsKlass, NULL},
/* End marker. */
{NULL, NULL, NULL, NULL}};
this->vmScanner->GetDataFromVMStructs(ofsMap);
if (unlikely(ofsKlassAtOop == -1 || ofsCoopKlassAtOop == -1 ||
ofsNameAtKlass == -1 || ofsLengthAtSymbol == -1 ||
ofsJavaThreadOsthread == -1 || ofsJavaThreadThreadObj == -1 ||
ofsJavaThreadThreadState == -1 ||
ofsThreadCurrentPendingMonitor == -1 ||
ofsOSThreadThreadId == -1 || ofsObjectMonitorObject == -1 ||
ofsBodyAtSymbol == -1 || ofsVTableSizeAtInsKlass == -1 ||
ofsITableSizeAtInsKlass == -1 ||
(!jvmInfo->isAfterCR7017732() &&
(ofsStaticFieldSizeAtInsKlass == -1)) ||
ofsNonstaticOopMapSizeAtInsKlass == -1)) {
logger->printCritMsg("Cannot get values from VMStructs.");
return false;
}
TTypeSizeMap typeMap[] = {/*
* After CR6964458.
* Not exists class "klassOopDesc".
*/
{"klassOopDesc", &clsSizeKlassOop},
{"oopDesc", &clsSizeOopDesc},
{"instanceKlass", &clsSizeInstanceKlass},
{"InstanceKlass", &clsSizeInstanceKlass},
{"arrayOopDesc", &clsSizeArrayOopDesc},
{"narrowOop", &clsSizeNarrowOop},
/* End marker. */
{NULL, NULL}};
vmScanner->GetDataFromVMTypes(typeMap);
if (unlikely((!jvmInfo->isAfterCR6964458() && clsSizeKlassOop == 0) ||
clsSizeOopDesc == 0 || clsSizeInstanceKlass == 0 ||
clsSizeArrayOopDesc == 0 || clsSizeNarrowOop == 0)) {
logger->printCritMsg("Cannot get values from VMTypes.");
return false;
}
TLongConstMap longMap[] = {
{"markOopDesc::lock_mask_in_place", &lockMaskInPlaceMarkOop},
{"markOopDesc::marked_value", &marked_value},
/* End marker. */
{NULL, NULL}};
vmScanner->GetDataFromVMLongConstants(longMap);
if (unlikely((lockMaskInPlaceMarkOop == 0) || (marked_value == 0))) {
logger->printCritMsg("Cannot get values from VMLongConstants.");
return false;
}
TIntConstMap intMap[] = {{"HeapWordSize", &HeapWordSize},
{"LogHeapWordSize", &LogHeapWordSize},
/* End marker. */
{NULL, NULL}};
vmScanner->GetDataFromVMIntConstants(intMap);
return true;
}
/*!
* \brief Get values which are decided after VMInit JVMTI event.
* This function should be called after JVMTI VMInit event.
* \return Process result.
*/
bool TVMVariables::getValuesAfterVMInit(void) {
int *narrowOffsetShiftBuf = NULL;
int *narrowKlassOffsetShiftBuf = NULL;
TOffsetNameMap ofsMap[] = {
{"Universe", "_collectedHeap", NULL, &collectedHeap},
{"Universe", "_narrow_oop._base", NULL, (void **)&narrowOffsetBase},
{"Universe", "_narrow_oop._shift", NULL, (void **)&narrowOffsetShiftBuf},
{"Universe", "_narrow_klass._base", NULL,
(void **)&narrowKlassOffsetBase},
{"Universe", "_narrow_klass._shift", NULL,
(void **)&narrowKlassOffsetShiftBuf},
/* End marker. */
{NULL, NULL, NULL, NULL}};
this->vmScanner->GetDataFromVMStructs(ofsMap);
if (unlikely(collectedHeap == NULL || narrowOffsetBase == 0 ||
narrowOffsetShiftBuf == NULL)) {
logger->printCritMsg("Cannot get values from VMStructs.");
return false;
}
narrowOffsetShift = *narrowOffsetShiftBuf;
if (!jvmInfo->isAfterCR8003424()) {
narrowKlassOffsetBase = narrowOffsetBase;
narrowKlassOffsetShift = narrowOffsetShift;
} else {
if (unlikely(narrowKlassOffsetShiftBuf == NULL)) {
logger->printCritMsg("Cannot get values from VMStructs.");
return false;
}
narrowKlassOffsetShift = *narrowKlassOffsetShiftBuf;
}
collectedHeap = (*(void **)collectedHeap);
narrowOffsetBase = (ptrdiff_t) * (void **)narrowOffsetBase;
narrowKlassOffsetBase = (ptrdiff_t) * (void **)narrowKlassOffsetBase;
bool result = true;
if (this->useCMS) {
result =
this->getCMSValuesFromVMStructs() && this->getCMSValuesFromSymbol();
} else if (this->useG1) {
result = this->getG1ValuesFromVMStructs();
}
return result;
}
/*!
* \brief Get HotSpot values through VMStructs which is related to CMS.
* \return Result of this function.
*/
bool TVMVariables::getCMSValuesFromVMStructs(void) {
void *cmsCollector = NULL;
off_t offsetLowAtVirtualSpace = -1;
off_t offsetCmsStartWord = -1;
off_t offsetCmsShifter = -1;
off_t offsetCmsMapAtCollector = -1;
off_t offsetCmsVirtualSpace = -1;
off_t offsetGens = -1;
off_t offsetYoungGen = -1;
off_t offsetYoungGenReserved = -1;
off_t offsetMemRegionStart = -1;
off_t offsetMemRegionWordSize = -1;
TOffsetNameMap ofsMap[] = {
{"CMSBitMap", "_virtual_space", &offsetCmsVirtualSpace, NULL},
{"CMSBitMap", "_bmStartWord", &offsetCmsStartWord, NULL},
{"CMSBitMap", "_shifter", &offsetCmsShifter, NULL},
{"CMSCollector", "_markBitMap", &offsetCmsMapAtCollector, NULL},
{"ConcurrentMarkSweepThread", "_collector", NULL, &cmsCollector},
{"VirtualSpace", "_low", &offsetLowAtVirtualSpace, NULL},
{"GenCollectedHeap", "_gens", &offsetGens, NULL},
{"GenCollectedHeap", "_young_gen", &offsetYoungGen, NULL},
{"Generation", "_reserved", &offsetYoungGenReserved, NULL},
{"MemRegion", "_start", &offsetMemRegionStart, NULL},
{"MemRegion", "_word_size", &offsetMemRegionWordSize, NULL},
/* End marker. */
{NULL, NULL, NULL, NULL}};
this->vmScanner->GetDataFromVMStructs(ofsMap);
/* "CMSBitMap::_bmStartWord" is not found in vmstruct. */
if (jvmInfo->isAfterCR6964458()) {
off_t bmWordSizeOfs = -1;
TOffsetNameMap bmWordSizeMap[] = {
{"CMSBitMap", "_bmWordSize", &bmWordSizeOfs, NULL},
{NULL, NULL, NULL, NULL}};
this->vmScanner->GetDataFromVMStructs(bmWordSizeMap);
if (likely(bmWordSizeOfs != -1)) {
/*
* CMSBitMap::_bmStartWord is appeared before _bmWordSize.
* See CMSBitMap definition in
* hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/
* concurrentMarkSweepGeneration.hpp
*/
offsetCmsStartWord = bmWordSizeOfs - sizeof(void *);
}
}
if (unlikely(offsetCmsVirtualSpace == -1 || offsetCmsStartWord == -1 ||
offsetCmsShifter == -1 || offsetCmsMapAtCollector == -1 ||
cmsCollector == NULL || offsetLowAtVirtualSpace == -1 ||
(offsetGens == -1 && offsetYoungGen == -1) ||
offsetYoungGenReserved == -1 || offsetMemRegionStart == -1 ||
offsetMemRegionWordSize == -1 ||
*(void **)cmsCollector == NULL)) {
logger->printCritMsg("Cannot get CMS values from VMStructs.");
return false;
}
/* Calculate about CMS bitmap information. */
cmsCollector = *(void **)cmsCollector;
ptrdiff_t cmsBitmapPtr = (ptrdiff_t)cmsCollector + offsetCmsMapAtCollector;
cmsBitMap_startWord = *(void **)(cmsBitmapPtr + offsetCmsStartWord);
cmsBitMap_shifter = *(int *)(cmsBitmapPtr + offsetCmsShifter);
ptrdiff_t virtSpace = cmsBitmapPtr + offsetCmsVirtualSpace;
cmsBitMap_startAddr = *(size_t **)(virtSpace + offsetLowAtVirtualSpace);
youngGen = (offsetGens == -1) // JDK-8061802
? *(void **)incAddress(collectedHeap, offsetYoungGen)
: *(void **)incAddress(collectedHeap, offsetGens);
void *youngGenReserved = incAddress(youngGen, offsetYoungGenReserved);
youngGenStartAddr =
*(void **)incAddress(youngGenReserved, offsetMemRegionStart);
size_t youngGenWordSize =
*(size_t *)incAddress(youngGenReserved, offsetMemRegionWordSize);
youngGenSize = youngGenWordSize * HeapWordSize;
if (unlikely((cmsBitMap_startWord == NULL) ||
(cmsBitMap_startAddr == NULL) ||
(youngGen == NULL) || (youngGenStartAddr == NULL))) {
logger->printCritMsg("Cannot calculate CMS values.");
return false;
}
BitsPerWordMask = BitsPerWord - 1;
return true;
}
/*!
* \brief Get HotSpot values through symbol table which is related to CMS.
* \return Result of this function.
*/
bool TVMVariables::getCMSValuesFromSymbol(void) {
/* Search symbol for CMS state. */
CMS_collectorState =
(int *)symFinder->findSymbol("_ZN12CMSCollector15_collectorStateE");
bool result = (CMS_collectorState != NULL);
if (unlikely(!result)) {
logger->printCritMsg("CollectorState not found.");
}
return result;
}
/*!
* \brief Get HotSpot values through VMStructs which is related to G1.
* \return Result of this function.
*/
bool TVMVariables::getG1ValuesFromVMStructs(void) {
off_t offsetReserved = -1;
off_t offsetMemRegionStart = -1;
TOffsetNameMap ofsMap[] = {
{"CollectedHeap", "_reserved", &offsetReserved, NULL},
{"MemRegion", "_start", &offsetMemRegionStart, NULL},
/* End marker. */
{NULL, NULL, NULL, NULL}};
vmScanner->GetDataFromVMStructs(ofsMap);
if (unlikely(offsetReserved == -1 || offsetMemRegionStart == -1 ||
collectedHeap == NULL)) {
logger->printCritMsg("Cannot get G1 values from VMStructs.");
return false;
}
/* Calculate about G1GC memory information. */
void *reservedRegion = *(void **)incAddress(collectedHeap, offsetReserved);
this->g1StartAddr = incAddress(reservedRegion, offsetMemRegionStart);
if (unlikely(reservedRegion == NULL || g1StartAddr == NULL)) {
logger->printCritMsg("Cannot calculate G1 values.");
return false;
}
return true;
}
/*!
* \brief Get HotSpot values through symbol table.
* \return Result of this function.
*/
bool TVMVariables::getValuesFromSymbol(void) {
/* Search symbol for integer information. */
struct {
const char *symbol;
const char *subSymbol;
int *pointer;
} intSymList[] = {
{"HeapWordsPerLong", "_ZL16HeapWordsPerLong", &HeapWordsPerLong},
{"LogBitsPerWord", "_ZL14LogBitsPerWord", &LogBitsPerWord},
{"BitsPerWord", "_ZL11BitsPerWord", &BitsPerWord},
/* End marker. */
{NULL, NULL, NULL}};
for (int i = 0; intSymList[i].pointer != NULL; i++) {
int *intPos = NULL;
intPos = (int *)symFinder->findSymbol(intSymList[i].symbol);
if (unlikely(intPos == NULL)) {
intPos = (int *)symFinder->findSymbol(intSymList[i].subSymbol);
}
if (unlikely(intPos == NULL)) {
logger->printDebugMsg("%s not found. Use default value.",
intSymList[i].symbol);
} else {
(*intSymList[i].pointer) = (*intPos);
}
}
/* Search symbol of variable stored safepoint state. */
safePointState = (int *)this->symFinder->findSymbol(SAFEPOINT_STATE_SYMBOL);
if (unlikely(safePointState == NULL)) {
logger->printWarnMsg("safepoint_state not found.");
return false;
}
return true;
}
| 18,242
|
C++
|
.cpp
| 471
| 32.868365
| 82
| 0.658925
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,015
|
timer.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/timer.cpp
|
/*!
* \file timer.cpp
* \brief This file is used to take interval snapshot.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "timer.hpp"
/*!
* \brief TTimer constructor.
* \param event [in] Callback is used by interval calling.
* \param timerName [in] Unique name of timer.
*/
TTimer::TTimer(TTimerEventFunc event, const char *timerName)
: TAgentThread(timerName) {
/* Sanity check. */
if (event == NULL) {
throw "Event callback is NULL.";
}
/* Setting param. */
this->timerInterval = 0;
this->_eventFunc = event;
this->_isInterrupted = false;
/* Create semphore. */
if (unlikely(sem_init(&this->timerSem, 0, 0))) {
throw "Couldn't create semphore.";
}
}
/*!
* \brief TTimer destructor.
*/
TTimer::~TTimer(void) {
/* Destroy semphore. */
sem_destroy(&this->timerSem);
}
/*!
* \brief JThread entry point called by interval or nofity.
* \param jvmti [in] JVMTI environment object.
* \param jni [in] JNI environment object.
* \param data [in] Pointer of TTimer.
*/
void JNICALL TTimer::entryPoint(jvmtiEnv *jvmti, JNIEnv *jni, void *data) {
/* Get self. */
TTimer *controller = (TTimer *)data;
/* Create increment time. */
struct timespec incTs = {0};
incTs.tv_sec = controller->timerInterval / 1000;
incTs.tv_nsec = (controller->timerInterval % 1000) * 1000;
/* Change running state. */
controller->_isRunning = true;
/* Loop for agent run. */
while (true) {
/* Reset timer interrupt flag. */
controller->_isInterrupted = false;
{
TMutexLocker locker(&controller->mutex);
if (unlikely(controller->_terminateRequest)) {
break;
}
/* Create limit datetime. */
struct timespec limitTs = {0};
struct timeval nowTv = {0};
gettimeofday(&nowTv, NULL);
TIMEVAL_TO_TIMESPEC(&nowTv, &limitTs);
limitTs.tv_sec += incTs.tv_sec;
limitTs.tv_nsec += incTs.tv_nsec;
/* Wait for notification, termination or timeout. */
pthread_cond_timedwait(&controller->mutexCond, &controller->mutex,
&limitTs);
}
/* If waiting finished by timeout. */
if (!controller->_isInterrupted) {
/* Call event callback. */
(*controller->_eventFunc)(jvmti, jni, Interval);
}
}
/* Change running state */
controller->_isRunning = false;
}
/*!
* \brief JThread entry point called by notify only.
* \param jvmti [in] JVMTI environment object.
* \param jni [in] JNI environment object.
* \param data [in] Pointer of TTimer.
*/
void JNICALL
TTimer::entryPointByCall(jvmtiEnv *jvmti, JNIEnv *jni, void *data) {
/* Get self. */
TTimer *controller = (TTimer *)data;
/* Change running state. */
controller->_isRunning = true;
/* Loop for agent run. */
while (!controller->_terminateRequest) {
/* Reset timer interrupt flag. */
controller->_isInterrupted = false;
/* Wait notify or terminate. */
sem_wait(&controller->timerSem);
/* If waiting finished by timeout. */
if (!controller->_isInterrupted) {
/* Call event callback. */
(*controller->_eventFunc)(jvmti, jni, Interval);
}
}
/* Change running state */
controller->_isRunning = false;
}
/*!
* \brief Make and begin Jthread.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param interval [in] Interval of invoke timer event.
*/
void TTimer::start(jvmtiEnv *jvmti, JNIEnv *env, jlong interval) {
/* Set timer interval. */
this->timerInterval = interval;
if (interval == 0) {
/* Notify process mode. Using semaphore. */
TAgentThread::start(jvmti, env, TTimer::entryPointByCall, this,
JVMTI_THREAD_MAX_PRIORITY);
} else {
/* Interval process mode. Using pthread monitor. */
TAgentThread::start(jvmti, env, TTimer::entryPoint, this,
JVMTI_THREAD_MAX_PRIORITY);
}
}
/*!
* \brief Notify reset timing to this thread from other thread.
*/
void TTimer::notify(void) {
if (this->timerInterval == 0) {
/* Notify process to waiting thread. */
sem_post(&this->timerSem);
} else {
/* Set interrupt flag and notify. */
TMutexLocker locker(&this->mutex);
this->_isInterrupted = true;
pthread_cond_signal(&this->mutexCond);
}
}
/*!
* \brief Notify stop to this thread from other thread.
*/
void TTimer::stop(void) {
/* Terminate follow entry callback type. */
if (this->timerInterval == 0) {
/* Sanity check. */
if (!this->_isRunning) {
logger->printWarnMsg("AgentThread already finished.");
return;
}
/* Send notification and count notify. */
this->_isInterrupted = true;
this->_terminateRequest = true;
sem_post(&this->timerSem);
/* SpinLock for AgentThread termination. */
while (this->_isRunning) {
; /* none. */
}
/* Clean termination flag. */
this->_terminateRequest = false;
} else {
/* Set interrupt flag and notify termination. */
this->_isInterrupted = true;
TAgentThread::stop();
}
}
| 5,842
|
C++
|
.cpp
| 180
| 28.472222
| 82
| 0.665838
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,016
|
bitMapMarker.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/bitMapMarker.cpp
|
/*!
* \file bitMapMarker.cpp
* \brief This file is used to store and control of bit map.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <sys/mman.h>
#include "globals.hpp"
#include "util.hpp"
#include "bitMapMarker.hpp"
/*!
* \brief TBitMapMarker constructor.
* \param startAddr [in] Start address of Java heap.
* \param size [in] Max Java heap size.
*/
TBitMapMarker::TBitMapMarker(const void *startAddr, const size_t size) {
/* Sanity check. */
if (unlikely(startAddr == NULL || size <= 0)) {
throw - 1;
}
/* Initialize setting. */
size_t alignedSize = ALIGN_SIZE_UP(size, systemPageSize);
this->beginAddr = const_cast<void *>(startAddr);
this->endAddr = incAddress(this->beginAddr, alignedSize);
this->bitmapSize = ALIGN_SIZE_UP(alignedSize >> MEMALIGN_BIT, systemPageSize);
this->bitmapAddr = mmap(NULL, this->bitmapSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
/* If failure allocate bitmap memory. */
if (unlikely(this->bitmapAddr == MAP_FAILED)) {
throw errno;
}
/* Advise the kernel that this memory will be random access. */
madvise(this->bitmapAddr, this->bitmapSize, POSIX_MADV_RANDOM);
/* Initialize bitmap (clear bitmap). */
this->clear();
}
/*!
* \brief TBitMapMarker destructor.
*/
TBitMapMarker::~TBitMapMarker() {
/* Release memory map. */
munmap(this->bitmapAddr, this->bitmapSize);
}
/*!
* \brief Get marked flag of designated pointer.
* \param addr [in] Targer pointer.
* \return Designated pointer is marked.
*/
bool TBitMapMarker::isMarked(const void *addr) {
/* Sanity check. */
if (unlikely(!this->isInZone(addr))) {
return false;
}
/* Get block and mask for getting mark flag. */
ptrdiff_t *bitmapBlock;
ptrdiff_t bitmapMask;
this->getBlockAndMask(addr, &bitmapBlock, &bitmapMask);
return (*bitmapBlock & bitmapMask);
}
/*!
* \brief Clear bitmap flag.
*/
void TBitMapMarker::clear(void) {
/* Temporary advise to zero-clear with sequential access. */
madvise(this->bitmapAddr, this->bitmapSize, MADV_SEQUENTIAL);
memset(this->bitmapAddr, 0, this->bitmapSize);
madvise(this->bitmapAddr, this->bitmapSize, MADV_RANDOM);
}
| 2,956
|
C++
|
.cpp
| 82
| 33.317073
| 82
| 0.71828
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,017
|
configuration.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/configuration.cpp
|
/*!
* \file configuration.cpp
* \brief This file treats HeapStats configuration.
* Copyright (C) 2014-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "fsUtil.hpp"
#include "signalManager.hpp"
#include "configuration.hpp"
#if USE_PCRE
#include "pcreRegex.hpp"
#else
#include "cppRegex.hpp"
#endif
/* Macro define. */
/*!
* \brief Macro of return code length.<br />
* E.g. linux is 1(LF), mac is 1(CR), windows is 2 (CRLF).
*/
#define RETURN_CODE_LEN 1
/*!
* \brief Constructor of TConfiguration.
*/
TConfiguration::TConfiguration(TJvmInfo *info) {
jvmInfo = info;
isLoaded = false;
firstCollected = false; /* Don't collected yet, */
/* Initialize each configurations. */
initializeConfig(NULL);
}
/*!
* \brief Copy constructor of TConfiguration.
*/
TConfiguration::TConfiguration(const TConfiguration &src) {
jvmInfo = src.jvmInfo;
isLoaded = false; // Set to false to load configuration from src.
alertThreshold = src.alertThreshold;
heapAlertThreshold = src.heapAlertThreshold;
/* Initialize each configurations. */
initializeConfig(&src);
isLoaded = src.isLoaded;
}
/*!
* \brief Initialize each configurations.
*
* \param src Source operand of configuration.
* If this value is not NULL, each configurations are copied from
* src.
*/
void TConfiguration::initializeConfig(const TConfiguration *src) {
configs.clear();
if (src == NULL) {
attach = new TBooleanConfig(this, "attach", true);
fileName =
new TStringConfig(this, "file", (char *)"heapstats_snapshot.dat",
&ReadStringValue, (TStringConfig::TFinalizer) & free);
heapLogFile =
new TStringConfig(this, "heaplogfile", (char *)"heapstats_log.csv",
&ReadStringValue, (TStringConfig::TFinalizer) & free);
archiveFile =
new TStringConfig(this, "archivefile", (char *)"heapstats_analyze.zip",
&ReadStringValue, (TStringConfig::TFinalizer) & free);
logFile = new TStringConfig(this, "logfile", (char *)"", &ReadStringValue,
(TStringConfig::TFinalizer) & free);
reduceSnapShot = new TBooleanConfig(this, "reduce_snapshot", true);
collectRefTree = new TBooleanConfig(this, "collect_reftree", true);
triggerOnFullGC = new TBooleanConfig(this, "trigger_on_fullgc", true,
&setOnewayBooleanValue);
triggerOnDump = new TBooleanConfig(this, "trigger_on_dump", true,
&setOnewayBooleanValue);
checkDeadlock = new TBooleanConfig(this, "check_deadlock", false,
&setOnewayBooleanValue);
triggerOnLogError = new TBooleanConfig(this, "trigger_on_logerror", true,
&setOnewayBooleanValue);
triggerOnLogSignal = new TBooleanConfig(this, "trigger_on_logsignal", true,
&setOnewayBooleanValue);
triggerOnLogLock = new TBooleanConfig(this, "trigger_on_loglock", true);
rankLevel = new TIntConfig(this, "rank_level", 5);
logLevel = new TLogLevelConfig(this, "loglevel", INFO, &setLogLevel);
order = new TRankOrderConfig(this, "rank_order", DELTA);
alertPercentage = new TIntConfig(this, "alert_percentage", 50);
heapAlertPercentage = new TIntConfig(this, "javaheap_alert_percentage", 95);
metaspaceThreshold = new TLongConfig(this, "metaspace_alert_threshold", 0);
timerInterval = new TLongConfig(this, "snapshot_interval", 0);
logInterval = new TLongConfig(this, "log_interval", 300);
firstCollect = new TBooleanConfig(this, "first_collect", true);
logSignalNormal =
new TStringConfig(this, "logsignal_normal", NULL, &setSignalValue,
(TStringConfig::TFinalizer) & free);
logSignalAll =
new TStringConfig(this, "logsignal_all", (char *)"SIGUSR2",
&setSignalValue, (TStringConfig::TFinalizer) & free);
reloadSignal =
new TStringConfig(this, "signal_reload", (char *)"SIGHUP",
&setSignalValue, (TStringConfig::TFinalizer) & free);
threadRecordEnable =
new TBooleanConfig(this, "thread_record_enable", false);
threadRecordBufferSize =
new TLongConfig(this, "thread_record_buffer_size", 100);
threadRecordFileName = new TStringConfig(
this, "thread_record_filename", (char *)"heapstats-thread-records.htr",
&ReadStringValue, (TStringConfig::TFinalizer) & free);
threadRecordIOTracer = new TStringConfig(
this, "thread_record_iotracer",
(char *)DEFAULT_CONF_DIR "/IoTrace.class",
&ReadStringValue, (TStringConfig::TFinalizer) & free);
snmpSend =
new TBooleanConfig(this, "snmp_send", false, &setOnewayBooleanValue);
snmpTarget =
new TStringConfig(this, "snmp_target", (char *)"localhost",
&setSnmpTarget, (TStringConfig::TFinalizer) & free);
snmpComName =
new TStringConfig(this, "snmp_comname", (char *)"public",
&setSnmpComName, (TStringConfig::TFinalizer) & free);
snmpLibPath =
new TStringConfig(this, "snmp_libpath", (char *)LIBNETSNMP_PATH,
&setSnmpLibPath, (TStringConfig::TFinalizer) & free);
logDir = new TStringConfig(this, "logdir", (char *)"./tmp",
&ReadStringValue,
(TStringConfig::TFinalizer) & free);
archiveCommand = new TStringConfig(
this, "archive_command",
(char *)"/usr/bin/zip %archivefile% -jr %logdir%",
&ReadStringValue, (TStringConfig::TFinalizer) & free);
killOnError = new TBooleanConfig(this, "kill_on_error", false);
} else {
attach = new TBooleanConfig(*src->attach);
fileName = new TStringConfig(*src->fileName);
heapLogFile = new TStringConfig(*src->heapLogFile);
archiveFile = new TStringConfig(*src->archiveFile);
logFile = new TStringConfig(*src->logFile);
reduceSnapShot = new TBooleanConfig(*src->reduceSnapShot);
collectRefTree = new TBooleanConfig(*src->collectRefTree);
triggerOnFullGC = new TBooleanConfig(*src->triggerOnFullGC);
triggerOnDump = new TBooleanConfig(*src->triggerOnDump);
checkDeadlock = new TBooleanConfig(*src->checkDeadlock);
triggerOnLogError = new TBooleanConfig(*src->triggerOnLogError);
triggerOnLogSignal = new TBooleanConfig(*src->triggerOnLogSignal);
triggerOnLogLock = new TBooleanConfig(*src->triggerOnLogLock);
rankLevel = new TIntConfig(*src->rankLevel);
logLevel = new TLogLevelConfig(*src->logLevel);
order = new TRankOrderConfig(*src->order);
alertPercentage = new TIntConfig(*src->alertPercentage);
heapAlertPercentage = new TIntConfig(*src->heapAlertPercentage);
metaspaceThreshold = new TLongConfig(*src->metaspaceThreshold);
timerInterval = new TLongConfig(*src->timerInterval);
logInterval = new TLongConfig(*src->logInterval);
firstCollect = new TBooleanConfig(*src->firstCollect);
logSignalNormal = new TStringConfig(*src->logSignalNormal);
logSignalAll = new TStringConfig(*src->logSignalAll);
reloadSignal = new TStringConfig(*src->reloadSignal);
threadRecordEnable = new TBooleanConfig(*src->threadRecordEnable);
threadRecordBufferSize = new TLongConfig(*src->threadRecordBufferSize);
threadRecordFileName = new TStringConfig(*src->threadRecordFileName);
threadRecordIOTracer = new TStringConfig(*src->threadRecordIOTracer);
snmpSend = new TBooleanConfig(*src->snmpSend);
snmpTarget = new TStringConfig(*src->snmpTarget);
snmpComName = new TStringConfig(*src->snmpComName);
snmpLibPath = new TStringConfig(*src->snmpLibPath);
logDir = new TStringConfig(*src->logDir);
archiveCommand = new TStringConfig(*src->archiveCommand);
killOnError = new TBooleanConfig(*src->killOnError);
}
configs.push_back(attach);
configs.push_back(fileName);
configs.push_back(heapLogFile);
configs.push_back(archiveFile);
configs.push_back(logFile);
configs.push_back(reduceSnapShot);
configs.push_back(collectRefTree);
configs.push_back(triggerOnFullGC);
configs.push_back(triggerOnDump);
configs.push_back(checkDeadlock);
configs.push_back(triggerOnLogError);
configs.push_back(triggerOnLogSignal);
configs.push_back(triggerOnLogLock);
configs.push_back(rankLevel);
configs.push_back(logLevel);
configs.push_back(order);
configs.push_back(alertPercentage);
configs.push_back(heapAlertPercentage);
configs.push_back(metaspaceThreshold);
configs.push_back(timerInterval);
configs.push_back(logInterval);
configs.push_back(firstCollect);
configs.push_back(logSignalNormal);
configs.push_back(logSignalAll);
configs.push_back(reloadSignal);
configs.push_back(threadRecordEnable);
configs.push_back(threadRecordBufferSize);
configs.push_back(threadRecordFileName);
configs.push_back(threadRecordIOTracer);
configs.push_back(snmpSend);
configs.push_back(snmpTarget);
configs.push_back(snmpComName);
configs.push_back(snmpLibPath);
configs.push_back(logDir);
configs.push_back(archiveCommand);
configs.push_back(killOnError);
}
/*!
* \brief Destructor of TConfiguration.
*/
TConfiguration::~TConfiguration() {
for (std::list<TConfigElementSuper *>::iterator itr = configs.begin();
itr != configs.end(); itr++) {
delete *itr;
}
}
/*!
* \brief Read boolean value from configuration.
* \param value [in] Value of this configuration.
* \return value which is represented by boolean.
*/
bool TConfiguration::ReadBooleanValue(const char *value) {
if (strcmp(value, "true") == 0) {
return true;
} else if (strcmp(value, "false") == 0) {
return false;
} else {
throw "Illegal boolean value";
}
}
/*!
* \brief Read string value from configuration.
* \param value [in] Value of this configuration.
* \param dest [in] [out] Destination of this configuration.
*/
void TConfiguration::ReadStringValue(TConfiguration *inst, char *value,
char **dest) {
if (*dest != NULL) {
free(*dest);
}
*dest = value == NULL ? NULL : strdup(value);
}
/*!
* \brief Read string value for signal from configuration.
* \param value [in] Value of this configuration.
* \param dest [in] [out] Destination of this configuration.
*/
void TConfiguration::ReadSignalValue(const char *value, char **dest) {
if ((value == NULL) || (value[0] == '\0')) {
if (*dest != NULL) {
free(*dest);
}
*dest = NULL;
} else if (TSignalManager::findSignal(value) != -1) {
if (*dest != NULL) {
free(*dest);
}
*dest = strdup(value);
} else {
throw "Illegal signal name";
}
}
/*!
* \brief Read long/int value from configuration.
* \param value [in] Value of this configuration.
* \param max_val [in] Max value of this parameter.
* \return value which is represented by long.
*/
long TConfiguration::ReadLongValue(const char *value, const jlong max_val) {
/* Convert to number from string. */
char *done = NULL;
errno = 0;
jlong temp = strtoll(value, &done, 10);
/* If all string is able to convert to number. */
if ((*done == '\0') && (temp <= max_val) && (temp >= 0)) {
return temp;
} else if (((temp == LLONG_MIN) || (temp == LLONG_MAX)) && (errno != 0)) {
throw errno;
} else {
throw "Illegal number";
}
}
/*!
* \brief Read order value from configuration.
* \param value [in] Value of this configuration.
* \return value which is represented by TRankOrder.
*/
TRankOrder TConfiguration::ReadRankOrderValue(const char *value) {
if (strcmp(value, "usage") == 0) {
return USAGE;
} else if (strcmp(value, "delta") == 0) {
return DELTA;
} else {
throw "Illegal order";
}
}
/*!
* \brief Read log level value from configuration.
* \param value [in] Value of this configuration.
* \return value which is represented by TLogLevel.
*/
TLogLevel TConfiguration::ReadLogLevelValue(const char *value) {
if (strcmp(value, "CRIT") == 0) {
return CRIT;
} else if (strcmp(value, "WARN") == 0) {
return WARN;
} else if (strcmp(value, "INFO") == 0) {
return INFO;
} else if (strcmp(value, "DEBUG") == 0) {
return DEBUG;
} else {
throw "Illegal level";
}
}
/*!
* \brief Load configuration from file.
* \param filename [in] Read configuration file path.
*/
void TConfiguration::loadConfiguration(const char *filename) {
/* Check filename. */
if (filename == NULL || strlen(filename) == 0) {
return;
}
/* Open file. */
FILE *conf = fopen(filename, "r");
if (unlikely(conf == NULL)) {
logger->printWarnMsgWithErrno("Could not open configuration file: %s",
filename);
return;
}
#if USE_PCRE
TPCRERegex confRegex("^\\s*(\\S+?)\\s*=\\s*(\\S+)?\\s*$", 9);
#else
TCPPRegex confRegex("^\\s*(\\S+?)\\s*=\\s*(\\S+)?\\s*$");
#endif
/* Get string line from configure file. */
long lineCnt = 0;
char *lineBuff = NULL;
size_t lineBuffLen = 0;
/* Read line. */
while (likely(getline(&lineBuff, &lineBuffLen, conf) > 0)) {
lineCnt++;
/* If this line is empty. */
if (unlikely(strlen(lineBuff) <= RETURN_CODE_LEN)) {
/* skip this line. */
continue;
}
/* Remove comments */
char *comment = strchr(lineBuff, '#');
if (comment != NULL) {
*comment = '\0';
}
/* Check matched pair. */
if (confRegex.find(lineBuff)) {
/* Key and value variables. */
char *key = confRegex.group(1);
char *value;
try {
value = confRegex.group(2);
} catch (const char *errStr) {
logger->printDebugMsg(errStr);
value = (char *)calloc(1, sizeof(char));
}
/* Check key name. */
try {
applyConfig(key, value);
} catch (const char *errStr) {
logger->printWarnMsg("Configuration error(key=%s, value=%s): %s", key,
value, errStr);
} catch (int err) {
errno = err;
logger->printWarnMsgWithErrno("Configuration error(key=%s, value=%s) ",
key, value);
}
/* Cleanup after param setting. */
free(key);
free(value);
}
}
/* Cleanup after load file. */
if (likely(lineBuff != NULL)) {
free(lineBuff);
}
fclose(conf);
isLoaded = true;
firstCollected = false;
}
/*!
* \brief Print setting information.
*/
void TConfiguration::printSetting(void) {
/* Agent attach state. */
logger->printInfoMsg("Agent Attach Enable = %s",
attach->get() ? "true" : "false");
/* Output filenames. */
logger->printInfoMsg("SnapShot FileName = %s", fileName->get());
logger->printInfoMsg("Heap Log FileName = %s", heapLogFile->get());
logger->printInfoMsg("Archive FileName = %s", archiveFile->get());
logger->printInfoMsg(
"Console Log FileName = %s",
strlen(logFile->get()) > 0 ? logFile->get() : "None (output to console)");
/* Output log-level. */
logger->printInfoMsg("LogLevel = %s", getLogLevelAsString());
/* Output about reduce SnapShot. */
logger->printInfoMsg("ReduceSnapShot = %s",
reduceSnapShot->get() ? "true" : "false");
/* Output whether collecting reftree. */
logger->printInfoMsg("CollectRefTree = %s",
collectRefTree->get() ? "true" : "false");
/* Output status of snapshot triggers. */
logger->printInfoMsg("Trigger on FullGC = %s",
triggerOnFullGC->get() ? "true" : "false");
logger->printInfoMsg("Trigger on DumpRequest = %s",
triggerOnDump->get() ? "true" : "false");
/* Output status of deadlock check. */
logger->printInfoMsg("Deadlock check = %s",
checkDeadlock->get() ? "true" : "false");
/* Output status of logging triggers. */
logger->printInfoMsg("Log trigger on Error = %s",
triggerOnLogError->get() ? "true" : "false");
logger->printInfoMsg("Log trigger on Signal = %s",
triggerOnLogSignal->get() ? "true" : "false");
logger->printInfoMsg("Log trigger on Deadlock = %s",
triggerOnLogLock->get() ? "true" : "false");
/* Output about ranking. */
logger->printInfoMsg("RankingOrder = %s", getRankOrderAsString());
logger->printInfoMsg("RankLevel = %d", rankLevel->get());
/* Output about heap alert. */
if (alertThreshold <= 0) {
logger->printInfoMsg("HeapAlert is DISABLED.");
} else {
logger->printInfoMsg("AlertPercentage = %d ( %lu bytes )",
alertPercentage->get(), alertThreshold);
}
/* Output about heap alert. */
if (heapAlertThreshold <= 0) {
logger->printInfoMsg("Java heap usage alert is DISABLED.");
} else {
logger->printInfoMsg("Java heap usage alert percentage = %d ( %lu MB )",
heapAlertPercentage->get(),
heapAlertThreshold / 1024 / 1024);
}
/* Output about metaspace alert. */
const char *label = jvmInfo->isAfterCR6964458() ? "Metaspace" : "PermGen";
if (metaspaceThreshold <= 0) {
logger->printInfoMsg("%s usage alert is DISABLED.", label);
} else {
logger->printInfoMsg("%s usage alert threshold %lu MB", label,
metaspaceThreshold->get() / 1024 / 1024);
}
/* Output about interval snapshot. */
if (timerInterval == 0) {
logger->printInfoMsg("Interval SnapShot is DISABLED.");
} else {
logger->printInfoMsg("SnapShot interval = %d sec", timerInterval->get());
}
/* Output about interval logging. */
if (logInterval->get() == 0) {
logger->printInfoMsg("Interval Logging is DISABLED.");
} else {
logger->printInfoMsg("Log interval = %d sec", logInterval->get());
}
logger->printInfoMsg("First collect log = %s",
firstCollect->get() ? "true" : "false");
/* Output logging signal name. */
char *normalSig = logSignalNormal->get();
if (normalSig == NULL || strlen(normalSig) == 0) {
logger->printInfoMsg("Signal for normal logging is DISABLED.");
} else {
logger->printInfoMsg("Signal for normal logging = %s", normalSig);
}
char *allSig = logSignalAll->get();
if (allSig == NULL || strlen(allSig) == 0) {
logger->printInfoMsg("Signal for all logging is DISABLED.");
} else {
logger->printInfoMsg("Signal for all logging = %s", allSig);
}
char *reloadSig = reloadSignal->get();
if (reloadSig == NULL || strlen(reloadSig) == 0) {
logger->printInfoMsg("Signal for config reloading is DISABLED.");
} else {
logger->printInfoMsg("Signal for config reloading = %s", reloadSig);
}
/* Thread recorder. */
logger->printInfoMsg("Thread recorder = %s",
threadRecordEnable->get() ? "true" : "false");
logger->printInfoMsg("Buffer size of thread recorder = %ld MB",
threadRecordBufferSize->get());
logger->printInfoMsg("Thread record file name = %s",
threadRecordFileName->get());
logger->printInfoMsg("Thread record I/O tracer = %s",
threadRecordIOTracer->get());
/* Output about SNMP trap. */
logger->printInfoMsg("Send SNMP Trap = %s",
snmpSend->get() ? "true" : "false");
logger->printInfoMsg("SNMP target = %s", snmpTarget->get());
logger->printInfoMsg("SNMP community = %s", snmpComName->get());
logger->printInfoMsg("NET-SNMP client library path = %s", snmpLibPath->get());
/* Output temporary log directory path. */
logger->printInfoMsg("Temporary log directory = %s", logDir->get());
/* Output archive command. */
logger->printInfoMsg("Archive command = \"%s\"", archiveCommand->get());
/* Output about force killing JVM. */
logger->printInfoMsg("Kill on Error = %s",
killOnError->get() ? "true" : "false");
}
/*!
* \brief Validate this configuration..
* \return Return true if all configuration is valid.
*/
bool TConfiguration::validate(void) {
bool result = true;
/* File check */
TStringConfig *filenames[] = {fileName, heapLogFile, archiveFile,
logFile, logDir, NULL};
for (TStringConfig **elmt = filenames; *elmt != NULL; elmt++) {
if (strlen((*elmt)->get()) == 0) {
// "" means "disable", not a file path like "./".
continue;
}
try {
if (!isValidPath((*elmt)->get())) {
throw "Permission denied";
}
} catch (const char *message) {
logger->printWarnMsg("%s: %s = %s", message, (*elmt)->getConfigName(),
(*elmt)->get());
result = false;
} catch (int errnum) {
logger->printWarnMsgWithErrno("Configuration error: %s = %s",
(*elmt)->getConfigName(), (*elmt)->get());
result = false;
}
}
/* Range check */
TIntConfig *percentages[] = {alertPercentage, heapAlertPercentage, NULL};
for (TIntConfig **percentage = percentages; *percentage != NULL;
percentage++) {
if (((*percentage)->get() < 0) || ((*percentage)->get() > 100)) {
logger->printWarnMsg("Out of range: %s = %d",
(*percentage)->getConfigName(),
(*percentage)->get());
result = false;
}
}
/* Set alert threshold. */
jlong maxMem = this->jvmInfo->getMaxMemory();
alertThreshold =
(maxMem == -1) ? -1 : (maxMem * alertPercentage->get() / 100);
heapAlertThreshold =
(maxMem == -1) ? -1 : (maxMem * heapAlertPercentage->get() / 100);
/* Signal check */
char *reloadSig = reloadSignal->get();
char *normalSig = logSignalNormal->get();
char *allSig = logSignalAll->get();
if (reloadSig != NULL) {
if ((normalSig != NULL) && (strcmp(normalSig, reloadSig) == 0)) {
logger->printWarnMsg(
"Cannot set same signal: logsignal_normal & signal_reload");
result = false;
}
if ((allSig != NULL) && (strcmp(allSig, reloadSig) == 0)) {
logger->printWarnMsg(
"Cannot set same signal: logsignal_all & signal_reload");
result = false;
}
}
if ((normalSig != NULL) && (allSig != NULL) &&
(strcmp(normalSig, allSig) == 0)) {
logger->printWarnMsg(
"Cannot set same signal: logsignal_normal & logsignal_all");
result = false;
}
/* Thread recorder check */
if (threadRecordEnable->get()) {
if (threadRecordBufferSize <= 0) {
logger->printWarnMsg("Invalid value: thread_record_buffer_size = %ld",
threadRecordBufferSize->get());
result = false;
} else if (!isValidPath(threadRecordFileName->get())) {
logger->printWarnMsg("Permission denied: thread_record_filename = %s",
threadRecordFileName->get());
result = false;
}
}
/* SNMP check */
if (snmpSend->get()) {
if (snmpLibPath->get() == NULL) {
logger->printWarnMsg("snmp_libpath must be set when snmp_send is set.");
result = false;
}
if ((snmpTarget->get() == NULL) || (strlen(snmpTarget->get()) == 0)) {
logger->printWarnMsg("snmp_target have to be set when snmp_send is set");
result = false;
}
if ((snmpComName->get() == NULL) || (strlen(snmpComName->get()) == 0)) {
logger->printWarnMsg("snmp_comname have to be set when snmp_send is set");
result = false;
}
}
return result;
}
/*!
* \brief Merge configuration from others.
* \param src Pointer of source configuration.
*/
void TConfiguration::merge(TConfiguration *src) {
attach->set(src->attach->get());
fileName->set(src->fileName->get());
heapLogFile->set(src->heapLogFile->get());
archiveFile->set(src->archiveFile->get());
logFile->set(src->logFile->get());
rankLevel->set(src->rankLevel->get());
logLevel->set(src->logLevel->get());
reduceSnapShot->set(src->reduceSnapShot->get());
collectRefTree->set(src->collectRefTree->get());
triggerOnFullGC->set(triggerOnFullGC->get() && src->triggerOnFullGC->get());
triggerOnDump->set(triggerOnDump->get() && src->triggerOnDump->get());
checkDeadlock->set(checkDeadlock->get() && src->checkDeadlock->get());
triggerOnLogError->set(triggerOnLogError->get() &&
src->triggerOnLogError->get());
triggerOnLogSignal->set(triggerOnLogSignal->get() &&
src->triggerOnLogSignal->get());
triggerOnLogLock->set(triggerOnLogLock->get() &&
src->triggerOnLogLock->get());
order->set(src->order->get());
alertPercentage->set(src->alertPercentage->get());
heapAlertPercentage->set(src->heapAlertPercentage->get());
metaspaceThreshold->set(src->metaspaceThreshold->get());
timerInterval->set(src->timerInterval->get());
logInterval->set(src->logInterval->get());
firstCollect->set(src->firstCollect->get());
threadRecordFileName->set(src->threadRecordFileName->get());
snmpSend->set(snmpSend->get() & src->snmpSend->get());
logDir->set(src->logDir->get());
archiveCommand->set(src->archiveCommand->get());
killOnError->set(src->killOnError->get());
}
/*!
* \brief Apply value to configuration which is presented by key.
* \param key Key of configuration.
* \param value New value.
* \exception Throws const char * or int which presents error.
*/
void TConfiguration::applyConfig(char *key, char *value) {
for (std::list<TConfigElementSuper *>::iterator itr = configs.begin();
itr != configs.end(); itr++) {
if (strcmp((*itr)->getConfigName(), key) == 0) {
switch ((*itr)->getConfigDataType()) {
case BOOLEAN:
((TBooleanConfig *)*itr)->set(ReadBooleanValue(value));
break;
case INTEGER:
((TIntConfig *)*itr)->set(ReadLongValue(value, INT_MAX));
break;
case LONG:
((TLongConfig *)*itr)->set(ReadLongValue(value, JLONG_MAX));
break;
case STRING:
((TStringConfig *)*itr)->set(value);
break;
case LOGLEVEL:
((TLogLevelConfig *)*itr)->set(ReadLogLevelValue(value));
break;
case RANKORDER:
((TRankOrderConfig *)*itr)->set(ReadRankOrderValue(value));
break;
}
}
}
}
void TConfiguration::setLogLevel(TConfiguration *inst,
TLogLevel val, TLogLevel *dest) {
*dest = val;
logger->setLogLevel(val);
}
| 27,205
|
C++
|
.cpp
| 684
| 33.763158
| 82
| 0.644723
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,018
|
vmFunctions.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/vmFunctions.cpp
|
/*!
* \file vmFunctions.cpp
* \brief This file includes functions in HotSpot VM.<br>
* Copyright (C) 2014-2018 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "globals.hpp"
#include "vmFunctions.hpp"
/* Variables */
TVMFunctions *TVMFunctions::inst = NULL;
/*!
* \brief VTable list which should be hooked.
*/
void *VTableForTypeArrayOopClosure[2] __attribute__((aligned(16)));
/*!
* \brief Function pointer for "is_in_permanent".
*/
THeap_IsIn is_in_permanent = NULL;
/* Internal function */
/*!
* \brief This dummy function for "is_in_permanent".<br>
* \param thisptr [in] Heap object instance.
* \param oop [in] Java object.
* \return Always value is "false".
*/
bool dummyIsInPermanent(void *thisptr, void *oop) { return false; }
/**********************************************************/
/*!
* \brief Instance initialier.
* \param sym [in] Symbol finder of libjvm.so .
* \return Singleton instance of TVMFunctions.
*/
TVMFunctions *TVMFunctions::initialize(TSymbolFinder *sym) {
inst = new TVMFunctions(sym);
if (inst == NULL) {
logger->printCritMsg("Cannot initialize TVMFunctions.");
return NULL;
}
if (inst->getFunctionsFromSymbol()) {
return inst;
} else {
logger->printCritMsg("Cannot initialize TVMFunctions.");
delete inst;
return NULL;
}
}
/*!
* \brief Get HotSpot functions through symbol table.
* \return Result of this function.
*/
bool TVMFunctions::getFunctionsFromSymbol(void) {
TVMVariables *vmVal = TVMVariables::getInstance();
if (vmVal == NULL) {
logger->printCritMsg(
"TVMVariables should be initialized before TVMFunction call.");
return false;
}
/* Search "is_in_permanent" function symbol. */
if (jvmInfo->isAfterCR6964458()) {
/* Perm gen does not exist. */
is_in_permanent = (THeap_IsIn)&dummyIsInPermanent;
} else if (vmVal->getUseParallel() || vmVal->getUseParOld()) {
is_in_permanent = (THeap_IsIn) this->symFinder->findSymbol(
IS_IN_PERM_ON_PARALLEL_GC_SYMBOL);
} else {
is_in_permanent = (THeap_IsIn) this->symFinder->findSymbol(
IS_IN_PERM_ON_OTHER_GC_SYMBOL);
}
if (unlikely(is_in_permanent == NULL)) {
logger->printCritMsg("is_in_permanent() not found.");
return false;
}
/* Search "is_in" function symbol for ParNew GC when CMS GC is worked. */
if (vmVal->getUseCMS()) {
is_in = (THeap_IsIn) this->symFinder->findSymbol(IS_IN_SYMBOL);
if (unlikely(is_in == NULL)) {
logger->printCritMsg("is_in() not found.");
return false;
}
}
/* Search "GetObjectSize" function symbol. */
getObjectSize = (TJvmtiEnv_GetObjectSize) this->symFinder->findSymbol(
SYMBOL_GETOBJCTSIZE);
if (unlikely(getObjectSize == NULL)) {
logger->printCritMsg("GetObjectSize() not found.");
return false;
}
/* Search "as_klassOop" function symbol. */
asKlassOop = (TJavaLangClass_AsKlassOop) this->symFinder->findSymbol(
(jvmInfo->isAfterCR6964458()) ? AS_KLASS_SYMBOL : AS_KLASSOOP_SYMBOL);
if (unlikely(asKlassOop == NULL)) {
logger->printWarnMsg("as_klassOop() not found.");
return false;
}
/* Search symbol of function getting classloader. */
if (jvmInfo->isAfterCR8004883()) {
getClassLoaderForInstanceKlass = (TGetClassLoader)symFinder->findSymbol(
CR8004883_GET_CLSLOADER_FOR_INSTANCE_SYMBOL);
getClassLoaderForObjArrayKlass = (TGetClassLoader)symFinder->findSymbol(
CR8004883_GET_CLSLOADER_FOR_OBJARY_SYMBOL);
} else {
getClassLoaderForInstanceKlass = (TGetClassLoader)symFinder->findSymbol(
GET_CLSLOADER_FOR_INSTANCE_SYMBOL);
getClassLoaderForObjArrayKlass =
(TGetClassLoader)symFinder->findSymbol(GET_CLSLOADER_FOR_OBJARY_SYMBOL);
}
if (unlikely(getClassLoaderForInstanceKlass == NULL ||
getClassLoaderForObjArrayKlass == NULL)) {
logger->printCritMsg("get_classloader not found.");
return false;
}
/* Search "thread_id" function symbol. */
getThreadId =
(TGetThreadId) this->symFinder->findSymbol(GET_THREAD_ID_SYMBOL);
if (unlikely(getThreadId == NULL)) {
logger->printWarnMsg("java_lang_Thread::thread_id() not found.");
return false;
}
/* Search "Unsafe_Park" function symbol. */
unsafePark = (TUnsafe_Park) this->symFinder->findSymbol(UNSAFE_PARK_SYMBOL);
if (unlikely(unsafePark == NULL)) {
logger->printWarnMsg("Unsafe_Park() not found.");
return false;
}
/* Search "get_thread" function symbol. */
get_thread = (TGet_thread) this->symFinder->findSymbol(GET_THREAD_SYMBOL);
if (get_thread == NULL) { // for JDK 9
/* Search "ThreadLocalStorage::thread" function symbol. */
get_thread = (TGet_thread) this->symFinder->findSymbol(
THREADLOCALSTORAGE_THREAD_SYMBOL);
if (unlikely(get_thread == NULL)) {
logger->printWarnMsg("ThreadLocalStorage::thread() not found.");
return false;
}
}
/* Search "UserHandler" function symbol. */
userHandler = (TUserHandler) this->symFinder->findSymbol(USERHANDLER_SYMBOL);
if (unlikely(userHandler == NULL)) {
userHandler = (TUserHandler) this->symFinder->findSymbol(
USERHANDLER_SYMBOL_JDK6);
if (unlikely(userHandler == NULL)) {
logger->printWarnMsg("UserHandler() not found.");
return false;
}
}
/* Search "SR_handler" function symbol. */
sr_handler = (TSR_Handler) this->symFinder->findSymbol(SR_HANDLER_SYMBOL);
if (sr_handler == NULL) { // for OpenJDK
sr_handler = (TSR_Handler) this->symFinder->findSymbol(
SR_HANDLER_SYMBOL_FALLBACK);
if (sr_handler == NULL) {
sr_handler = (TSR_Handler) this->symFinder->findSymbol(
SR_HANDLER_SYMBOL_JDK6);
if (sr_handler == NULL) {
sr_handler = (TSR_Handler) this->symFinder->findSymbol(
SR_HANDLER_SYMBOL_FALLBACK2);
if (sr_handler == NULL) {
logger->printWarnMsg("SR_handler() not found.");
return false;
}
}
}
}
/* Search "ThreadSafepointState::create()" function symbol. */
threadSafepointStateCreate = (TVMThreadFunction) this->symFinder->findSymbol(
THREADSAFEPOINTSTATE_CREATE_SYMBOL);
if (unlikely(threadSafepointStateCreate == NULL)) {
logger->printWarnMsg("ThreadSafepointState::create() not found.");
return false;
}
/* Search "ThreadSafepointState::destroy()" function symbol. */
threadSafepointStateDestroy = (TVMThreadFunction) this->symFinder->findSymbol(
THREADSAFEPOINTSTATE_DESTROY_SYMBOL);
if (unlikely(threadSafepointStateDestroy == NULL)) {
logger->printWarnMsg("ThreadSafepointState::destroy() not found.");
return false;
}
/* Search "Monitor::lock()" function symbol. */
monitor_lock = (TVMMonitorFunction) this->symFinder->findSymbol(
MONITOR_LOCK_SYMBOL);
if (unlikely(monitor_lock == NULL)) {
logger->printWarnMsg("Monitor::lock() not found.");
return false;
}
/* Search "Monitor::lock_without_safepoint_check()" function symbol. */
monitor_lock_without_safepoint_check =
(TVMMonitorFunction) this->symFinder->findSymbol(
MONITOR_LOCK_WTIHOUT_SAFEPOINT_CHECK_SYMBOL);
if (unlikely(monitor_lock_without_safepoint_check == NULL)) {
logger->printWarnMsg("Monitor::lock_without_safepoint_check() not found.");
return false;
}
/* Search "Monitor::unlock()" function symbol. */
monitor_unlock = (TVMMonitorFunction) this->symFinder->findSymbol(
MONITOR_UNLOCK_SYMBOL);
if (unlikely(monitor_unlock == NULL)) {
logger->printWarnMsg("Monitor::unlock() not found.");
return false;
}
/* Search "Monitor::owned_by_self()" function symbol. */
monitor_owned_by_self = (TOwnedBySelf) this->symFinder->findSymbol(
MONITOR_OWNED_BY_SELF_SYMBOL);
if (unlikely(monitor_owned_by_self == NULL)) {
logger->printWarnMsg("Monitor::owned_by_self() not found.");
return false;
}
if (vmVal->getUseG1()) {
inst->getG1VTableFromSymbol();
}
return true;
}
/*!
* \brief Get vtable through symbol table which is related to G1.
* \return Result of this function.
*/
bool TVMFunctions::getG1VTableFromSymbol(void) {
/* Add vtable offset */
#ifdef __LP64__
VTableForTypeArrayOopClosure[0] =
incAddress(symFinder->findSymbol("_ZTV14G1CMOopClosure"), 16);
VTableForTypeArrayOopClosure[1] =
incAddress(symFinder->findSymbol("_ZTV23G1RootRegionScanClosure"), 16);
#else
VTableForTypeArrayOopClosure[0] =
incAddress(symFinder->findSymbol("_ZTV14G1CMOopClosure"), 8);
VTableForTypeArrayOopClosure[1] =
incAddress(symFinder->findSymbol("_ZTV23G1RootRegionScanClosure"), 8);
#endif
if (unlikely(VTableForTypeArrayOopClosure[0] == NULL ||
VTableForTypeArrayOopClosure[1] == NULL)) {
logger->printCritMsg("Cannot get vtables which are related to G1.");
return false;
}
return true;
}
| 10,016
|
C++
|
.cpp
| 249
| 34.176707
| 82
| 0.664886
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,019
|
snapShotContainer.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/snapShotContainer.cpp
|
/*!
* \file snapshotContainer.cpp
* \brief This file is used to add up using size every class.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <utility>
#include <algorithm>
#include "globals.hpp"
#include "snapShotContainer.hpp"
#include "classContainer.hpp"
/*!
* \brief Snapshot container instance stock queue.
*/
tbb::concurrent_queue<TSnapShotContainer *>
*TSnapShotContainer::stockQueue = NULL;
/*!
* \brief Set of active TSnapShotContainer set
*/
TActiveSnapShots TSnapShotContainer::activeSnapShots;
/*!
* \brief Initialize snapshot caontainer class.
* \return Is process succeed.
* \warning Please call only once from main thread.
*/
bool TSnapShotContainer::globalInitialize(void) {
try {
/* Create snapshot container storage. */
stockQueue = new TSnapShotQueue();
} catch (...) {
logger->printWarnMsg("Failure initialize snapshot container.");
return false;
}
return true;
}
/*!
* \brief Finalize snapshot caontainer class.
* \warning Please call only once from main thread.
*/
void TSnapShotContainer::globalFinalize(void) {
if (likely(stockQueue != NULL)) {
TSnapShotContainer *item;
/* Clear snapshots in queue. */
while (stockQueue->try_pop(item)) {
/* Deallocate snapshot instance. */
delete item;
}
/* Deallocate stock queue. */
delete stockQueue;
stockQueue = NULL;
}
}
/*!
* \brief Get snapshot container instance.
* \return Snapshot container instance.
* \warning Don't deallocate instance getting by this function.<br>
* Please call "releaseInstance" method.
*/
TSnapShotContainer *TSnapShotContainer::getInstance(void) {
TSnapShotContainer *result = NULL;
if (!stockQueue->try_pop(result)) {
/* Create new snapshot container instance. */
result = new TSnapShotContainer();
TActiveSnapShots::accessor acc;
activeSnapShots.insert(acc, result);
}
return result;
}
/*!
* \brief Release snapshot container instance..
* \param instance [in] Snapshot container instance.
* \warning Don't access instance after called this function.
*/
void TSnapShotContainer::releaseInstance(TSnapShotContainer *instance) {
/* Sanity check. */
if (unlikely(instance == NULL)) {
return;
}
/*
* unsafe_size() might return actual size if it is accessed concurrently.
* However we use this function because we can use to decide cache count.
* SnapShot cache means best effort.
*/
if (likely(stockQueue->unsafe_size() < MAX_STOCK_COUNT)) {
/* Clear data. */
instance->clear(false);
/* Store instance. */
stockQueue->push(instance);
} else {
/* Deallocate instance. */
activeSnapShots.erase(instance);
delete instance;
}
}
/*!
* \brief TSnapshotContainer constructor.
*/
TSnapShotContainer::TSnapShotContainer(void) : counterMap(), childrenMap() {
/* Header setting. */
this->_header.magicNumber = conf->CollectRefTree()->get()
? EXTENDED_REFTREE_SNAPSHOT
: EXTENDED_SNAPSHOT;
this->_header.byteOrderMark = BOM;
this->_header.snapShotTime = 0;
this->_header.size = 0;
memset((void *)&this->_header.gcCause[0], 0, 80);
this->isCleared = true;
}
/*!
* \brief TSnapshotContainer destructor.
*/
TSnapShotContainer::~TSnapShotContainer(void) {
/* Cleanup elements on counter map. */
for (auto itr = counterMap.begin(); itr != counterMap.end(); itr++) {
TClassCounter *clsCounter = itr->second;
free(clsCounter->offsets);
free(clsCounter->counter);
free(clsCounter);
}
/* Cleanup elements on children map. */
for (auto itr = childrenMap.begin(); itr != childrenMap.end(); itr++) {
TChildClassCounter *childCounter = itr->second;
free(childCounter->counter);
free(childCounter);
}
}
/*!
* \brief Append new-class to container.
* \param objData [in] New-class key object.
* \return New-class data.
*/
TClassCounter *TSnapShotContainer::pushNewClass(TObjectData *objData) {
TClassCounter *cur = NULL;
cur = (TClassCounter *)calloc(1, sizeof(TClassCounter));
/* If failure allocate counter data. */
if (unlikely(cur == NULL)) {
/* Adding empty to list is deny. */
logger->printWarnMsg("Couldn't allocate counter memory!");
return NULL;
}
cur->offsetCount = -1;
int ret = posix_memalign(
(void **)&cur->counter, 16,
sizeof(TObjectCounter) /* sizeof(TObjectCounter) == 16. */);
/* If failure allocate counter. */
if (unlikely(ret != 0)) {
/* Adding empty to list is deny. */
logger->printWarnMsg("Couldn't allocate counter memory!");
free(cur);
return NULL;
}
this->clearObjectCounter(cur->counter);
/* Set to counter map. */
TSizeMap::accessor acc;
if (!counterMap.insert(acc, std::make_pair(objData, cur))) {
free(cur->counter);
free(cur);
cur = NULL;
}
return acc->second;
}
/*!
* \brief Append new-child-class to container.
* \param clsCounter [in] Parent class counter object.
* \param objData [in] New-child-class key object.
* \return New-class data.
*/
TChildClassCounter *TSnapShotContainer::pushNewChildClass(
TClassCounter *clsCounter, TObjectData *objData) {
TChildClassCounter *newCounter =
(TChildClassCounter *)calloc(1, sizeof(TChildClassCounter));
/* If failure allocate child class counter data. */
if (unlikely(newCounter == NULL)) {
return NULL;
}
int ret = posix_memalign(
(void **)&newCounter->counter, 16,
sizeof(TObjectCounter) /* sizeof(TObjectCounter) == 16. */);
/* If failure allocate child class counter. */
if (unlikely(ret != 0)) {
free(newCounter);
return NULL;
}
this->clearObjectCounter(newCounter->counter);
newCounter->objData = objData;
/* Set to children map. */
TChildrenMapKey key = std::make_pair(clsCounter, objData->klassOop);
TChildrenMap::accessor acc;
TChildrenMap::value_type value = std::make_pair(key, newCounter);
childrenMap.insert(acc, value);
acc.release();
/* Add new counter to children list */
spinLockWait(&clsCounter->spinlock);
{
TChildClassCounter *counter = clsCounter->child;
if (unlikely(counter == NULL)) {
clsCounter->child = newCounter;
} else {
/* Get last counter. */
while (counter->next != NULL) {
counter = counter->next;
}
counter->next = newCounter;
}
}
spinLockRelease(&clsCounter->spinlock);
return newCounter;
}
/*!
* \brief Set JVM performance info to header.
* \param info [in] JVM running performance information.
*/
void TSnapShotContainer::setJvmInfo(TJvmInfo *info) {
/* Sanity check. */
if (unlikely(info == NULL)) {
logger->printWarnMsg("Couldn't get GC Information!");
return;
}
/* If GC cause is need. */
if (this->_header.cause == GC) {
/* Copy GC cause. */
strcpy((char *)this->_header.gcCause, info->getGCCause());
this->_header.gcCauseLen = strlen((char *)this->_header.gcCause);
/* Setting GC work time. */
this->_header.gcWorktime = info->getGCWorktime();
} else {
/* Clear GC cause. */
this->_header.gcCauseLen = 1;
this->_header.gcCause[0] = '\0';
/* GC no work. */
this->_header.gcWorktime = 0;
}
/* Setting header info from TJvmInfo.
* Total memory (JVM_TotalMemory) should be called from outside of GC.
* Comment of VM_ENTRY_BASE macro says as following:
* ENTRY routines may lock, GC and throw exceptions
* So we set TSnapShotFileHeader.totalHeapSize in TakeSnapShot() .
*/
this->_header.FGCCount = info->getFGCCount();
this->_header.YGCCount = info->getYGCCount();
this->_header.newAreaSize = info->getNewAreaSize();
this->_header.oldAreaSize = info->getOldAreaSize();
this->_header.metaspaceUsage = info->getMetaspaceUsage();
this->_header.metaspaceCapacity = info->getMetaspaceCapacity();
}
/*!
* \brief Clear snapshot data.
*/
void TSnapShotContainer::clear(bool isForce) {
if (!isForce && this->isCleared) {
return;
}
/* Cleanup elements on counter map. */
for (auto itr = counterMap.begin(); itr != counterMap.end(); itr++) {
TClassCounter *clsCounter = itr->second;
free(clsCounter->offsets);
clsCounter->offsets = NULL;
clsCounter->offsetCount = -1;
/* Reset counters. */
clearChildClassCounters(clsCounter);
}
}
/*!
* \brief Output GC statistics information.
*/
void TSnapShotContainer::printGCInfo(void) {
logger->printInfoMsg("GC Statistics Information:");
/* GC cause and GC worktime show only raised GC. */
if (this->_header.cause == GC) {
logger->printInfoMsg(
"GC Cause: %s, GC Worktime: " JLONG_FORMAT_STR " msec",
(char *)this->_header.gcCause, this->_header.gcWorktime);
}
/* Output GC count. */
logger->printInfoMsg("GC Count: FullGC: " JLONG_FORMAT_STR
" / Young GC: " JLONG_FORMAT_STR,
this->_header.FGCCount, this->_header.YGCCount);
/* Output heap size status. */
logger->printInfoMsg("Area using size: New: " JLONG_FORMAT_STR
" bytes"
" / Old: " JLONG_FORMAT_STR
" bytes"
" / Total: " JLONG_FORMAT_STR " bytes",
this->_header.newAreaSize, this->_header.oldAreaSize,
this->_header.totalHeapSize);
/* Output metaspace size status. */
const char *label =
jvmInfo->isAfterCR6964458() ? "Metaspace usage: " : "PermGen usage: ";
logger->printInfoMsg("%s " JLONG_FORMAT_STR
" bytes"
", capacity: " JLONG_FORMAT_STR " bytes",
label, this->_header.metaspaceUsage,
this->_header.metaspaceCapacity);
}
/*!
* \brief Remove unloaded TObjectData in this snapshot container.
* This function should be called at safepoint.
* \param unloadedList Set of unloaded TObjectData.
*/
void TSnapShotContainer::removeObjectData(TClassInfoSet &unloadedList) {
/*
* This function is called at safepoint.
* (from OnGarbageCollectionFinishForUnload() in classContainer.cpp)
* So we can use *unsafe* iterator access in tbb::concurrent_queue.
*/
for (auto itr = unloadedList.unsafe_begin();
itr != unloadedList.unsafe_end(); itr++) {
TSizeMap::const_accessor acc;
if (counterMap.find(acc, *itr)) {
TClassCounter *clsCounter = acc->second;
counterMap.erase(acc);
acc.release();
TChildClassCounter *child = clsCounter->child;
while (child != NULL) {
TChildClassCounter *next = child->next;
childrenMap.erase(std::make_pair(clsCounter, child->objData->klassOop));
free(child->counter);
free(child);
child = next;
}
}
}
}
/*!
* \brief Remove unloaded TObjectData all active snapshot container.
* \param unloadedList Set of unloaded TObjectData.
*/
void TSnapShotContainer::removeObjectDataFromAllSnapShots(
TClassInfoSet &unloadedList) {
for (auto itr = activeSnapShots.begin();
itr != activeSnapShots.end(); itr++) {
itr->first->removeObjectData(unloadedList);
}
}
| 11,963
|
C++
|
.cpp
| 348
| 29.758621
| 82
| 0.673956
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,020
|
pcreRegex.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/pcreRegex.cpp
|
/*!
* \file pcreRegex.cpp
* \brief Regex implementation to use PCRE.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <string.h>
#include <pcre.h>
#include "pcreRegex.hpp"
TPCRERegex::TPCRERegex(const char *pattern, int ovecsz)
: TRegexAdapter(pattern) {
const char *errMsg;
int errPos;
pcreExpr = pcre_compile(pattern, PCRE_ANCHORED, &errMsg, &errPos, NULL);
if (pcreExpr == NULL) {
throw errMsg;
}
ovecsize = ovecsz;
ovec = new int[ovecsize];
}
TPCRERegex::~TPCRERegex() {
pcre_free(pcreExpr);
delete[] ovec;
}
bool TPCRERegex::find(const char *str) {
find_str = str;
int result =
pcre_exec(pcreExpr, NULL, str, strlen(str), 0, 0, ovec, ovecsize);
return result >= 0;
}
char *TPCRERegex::group(int index) {
const char *val = NULL;
if (pcre_get_substring(find_str, ovec, ovecsize, index, &val) <= 0) {
if (val != NULL) {
pcre_free_substring(val);
}
throw "Could not get substring through PCRE.";
}
char *result = strdup(val);
pcre_free_substring(val);
return result;
}
| 1,779
|
C++
|
.cpp
| 56
| 29.017857
| 82
| 0.715537
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,021
|
threadRecorder.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/threadRecorder.cpp
|
/*!
* \iile threadRecorder.cpp
* \brief Recording thread status.
* Copyright (C) 2015-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <jvmti.h>
#include <jni.h>
#include <stddef.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sched.h>
#ifdef HAVE_ATOMIC
#include <atomic>
#else
#include <cstdatomic>
#endif
#include "globals.hpp"
#include "util.hpp"
#include "vmFunctions.hpp"
#include "callbackRegister.hpp"
#include "jniCallbackRegister.hpp"
#include "threadRecorder.hpp"
#if PROCESSOR_ARCH == X86
#include "arch/x86/lock.inline.hpp"
#elif PROCESSOR_ARCH == ARM
#include "arch/arm/lock.inline.hpp"
#endif
/* Static valiable */
TThreadRecorder *TThreadRecorder::inst = NULL;
/* variables */
jclass threadClass;
jmethodID currentThreadMethod;
static std::atomic_int processing(0);
/* JVMTI event handler */
/*!
* \brief JVMTI callback for ThreadStart event.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param thread [in] jthread object which is created.
*/
void JNICALL OnThreadStart(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
TProcessMark mark(processing);
TThreadRecorder *recorder = TThreadRecorder::getInstance();
recorder->registerNewThread(jvmti, thread);
recorder->putEvent(thread, ThreadStart, 0);
}
/*!
* \brief JVMTI callback for ThreadEnd event.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param thread [in] jthread object which is created.
*/
void JNICALL OnThreadEnd(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
TProcessMark mark(processing);
TThreadRecorder::getInstance()->putEvent(thread, ThreadEnd, 0);
}
/*!
* \brief JVMTI callback for MonitorContendedEnter event.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param thread [in] jthread object which is created.
* \param object [in] Monitor object which is contended.
*/
void JNICALL
OnMonitorContendedEnterForThreadRecording(jvmtiEnv *jvmti, JNIEnv *env,
jthread thread, jobject object) {
TProcessMark mark(processing);
TThreadRecorder::getInstance()->putEvent(thread, MonitorContendedEnter, 0);
}
/*!
* \brief JVMTI callback for MonitorContendedEntered event.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param thread [in] jthread object which is created.
* \param object [in] Monitor object which was contended.
*/
void JNICALL OnMonitorContendedEnteredForThreadRecording(jvmtiEnv *jvmti,
JNIEnv *env,
jthread thread,
jobject object) {
TProcessMark mark(processing);
TThreadRecorder::getInstance()->putEvent(thread, MonitorContendedEntered, 0);
}
/*!
* \brief JVMTI callback for MonitorWait event.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param thread [in] jthread object which is created.
* \param object [in] Monitor object which is waiting.
* \param timeout [in] Timeout of this monitor.
*/
void JNICALL OnMonitorWait(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread,
jobject object, jlong timeout) {
TProcessMark mark(processing);
TThreadRecorder::getInstance()->putEvent(thread, MonitorWait, timeout);
}
/*!
* \brief JVMTI callback for MonitorWait event.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param thread [in] jthread object which is created.
* \param object [in] Monitor object which is waiting.
* \param timeout [in] Timeout of this monitor.
*/
void JNICALL OnMonitorWaited(jvmtiEnv *jvmti, JNIEnv *jni_env, jthread thread,
jobject object, jboolean timeout) {
TProcessMark mark(processing);
TThreadRecorder::getInstance()->putEvent(thread, MonitorWaited, timeout);
}
/*!
* \brief JVMTI callback for DataDumpRequest to dump thread record data.
*
* \param jvmti [in] JVMTI environment.
*/
void JNICALL OnDataDumpRequestForDumpThreadRecordData(jvmtiEnv *jvmti) {
TProcessMark mark(processing);
TThreadRecorder::inst->dump(conf->ThreadRecordFileName()->get());
}
/* Support function. */
/*!
* \brief Get current thread as pointer of JavaThread in HotSpot.
*
* \param env [in] JNI environment.
* \return JavaThread instance of current thread.
*/
void *GetCurrentThread(JNIEnv *env) {
jobject threadObj =
env->CallStaticObjectMethod(threadClass, currentThreadMethod);
return *(void **)threadObj;
}
/* JNI event handler */
/*!
* \brief Prologue callback of JVM_Sleep.
*
* \param env [in] JNI environment.
* \param threadClass [in] jclass of java.lang.Thread .
* \param millis [in] Time of sleeping.
*/
void JNICALL JVM_SleepPrologue(JNIEnv *env, jclass threadClass, jlong millis) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
ThreadSleepStart, millis);
}
/*!
* \brief Epilogue callback of JVM_Sleep.
*
* \param env [in] JNI environment.
* \param threadClass [in] jclass of java.lang.Thread .
* \param millis [in] Time of sleeping.
*/
void JNICALL JVM_SleepEpilogue(JNIEnv *env, jclass threadClass, jlong millis) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
ThreadSleepEnd, millis);
}
/*!
* \brief Prologue callback of Unsafe_Park.
*
* \param env [in] JNI environment.
* \param unsafe [in] Instance of Unsafe.
* \param isAbsolute [in] Absolute time or not.
* \param time [in] Park time.
*/
void JNICALL UnsafeParkPrologue(JNIEnv *env, jobject unsafe,
jboolean isAbsolute, jlong time) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread, Park, time);
}
/*!
* \brief Epilogue callback of Unsafe_Park.
*
* \param env [in] JNI environment.
* \param unsafe [in] Instance of Unsafe.
* \param isAbsolute [in] Absolute time or not.
* \param time [in] Park time.
*/
void JNICALL UnsafeParkEpilogue(JNIEnv *env, jobject unsafe,
jboolean isAbsolute, jlong time) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread, Unpark, time);
}
/* I/O tracer */
/* Dummy method */
void * JNICALL IoTrace_dummy(void) {
return NULL;
}
/*
* Method: socketReadBegin
* Signature: ()Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL IoTrace_socketReadBegin(JNIEnv *env, jclass cls) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
SocketReadStart, 0);
return NULL;
}
/*
* Method: socketReadEnd
* Signature: (Ljava/lang/Object;Ljava/net/InetAddress;IIJ)V
*/
JNIEXPORT void JNICALL IoTrace_socketReadEnd(JNIEnv *env, jclass cls,
jobject context, jobject address,
jint port, jint timeout,
jlong bytesRead) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
SocketReadEnd, bytesRead);
}
/*
* Method: socketWriteBegin
* Signature: ()Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL IoTrace_socketWriteBegin(JNIEnv *env, jclass cls) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
SocketWriteStart, 0);
return NULL;
}
/*
* Method: socketWriteEnd
* Signature: (Ljava/lang/Object;Ljava/net/InetAddress;IJ)V
*/
JNIEXPORT void JNICALL IoTrace_socketWriteEnd(JNIEnv *env, jclass cls,
jobject context, jobject address,
jint port, jlong bytesWritten) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
SocketWriteEnd, bytesWritten);
}
/*
* Method: fileReadBegin
* Signature: (Ljava/lang/String;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL
IoTrace_fileReadBegin(JNIEnv *env, jclass cls, jstring path) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
FileReadStart, 0);
return NULL;
}
/*
* Method: fileReadEnd
* Signature: (Ljava/lang/Object;J)V
*/
JNIEXPORT void JNICALL IoTrace_fileReadEnd(JNIEnv *env, jclass cls,
jobject context, jlong bytesRead) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
FileReadEnd, bytesRead);
}
/*
* Method: fileWriteBegin
* Signature: (Ljava/lang/String;)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL
IoTrace_fileWriteBegin(JNIEnv *env, jclass cls, jstring path) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
FileWriteStart, 0);
return NULL;
}
/*
* Method: fileWriteEnd
* Signature: (Ljava/lang/Object;J)V
*/
JNIEXPORT void JNICALL IoTrace_fileWriteEnd(JNIEnv *env, jclass cls,
jobject context,
jlong bytesWritten) {
TProcessMark mark(processing);
void *javaThread = GetCurrentThread(env);
TThreadRecorder::getInstance()->putEvent((jthread)&javaThread,
FileWriteEnd, bytesWritten);
}
/* Class member functions */
/*!
* \brief Constructor of TThreadRecorder.
*
* \param buffer_size [in] Size of ring buffer.
* Ring buffer size will be aligned to page size.
*/
TThreadRecorder::TThreadRecorder(size_t buffer_size) : threadIDMap() {
aligned_buffer_size = ALIGN_SIZE_UP(buffer_size, systemPageSize);
bufferLockVal = 0;
/* manpage of mmap(2):
*
* MAP_ANONYMOUS:
* The mapping is not backed by any iile;
* to zero.
*/
record_buffer = mmap(NULL, aligned_buffer_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (record_buffer == MAP_FAILED) {
throw errno;
}
top_of_buffer = (TEventRecord *)record_buffer;
end_of_buffer =
(TEventRecord *)((unsigned char *)record_buffer + aligned_buffer_size);
}
/*!
* \brief Destructor of TThreadRecorder.
*/
TThreadRecorder::~TThreadRecorder() {
munmap(record_buffer, aligned_buffer_size);
/* Deallocate memory for thread name. */
for (auto itr = threadIDMap.begin(); itr != threadIDMap.end(); itr++) {
free(itr->second);
}
}
/*!
* \brief Register JVMTI hook point.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
*/
void TThreadRecorder::registerHookPoint(jvmtiEnv *jvmti, JNIEnv *env) {
/* Set JVMTI event capabilities. */
jvmtiCapabilities capabilities = {0};
TThreadStartCallback::mergeCapabilities(&capabilities);
TThreadEndCallback::mergeCapabilities(&capabilities);
TMonitorContendedEnterCallback::mergeCapabilities(&capabilities);
TMonitorContendedEnteredCallback::mergeCapabilities(&capabilities);
TMonitorWaitCallback::mergeCapabilities(&capabilities);
TMonitorWaitedCallback::mergeCapabilities(&capabilities);
TDataDumpRequestCallback::mergeCapabilities(&capabilities);
if (isError(jvmti, jvmti->AddCapabilities(&capabilities))) {
logger->printCritMsg(
"Couldn't set event capabilities for Thread recording.");
return;
}
/* Set JVMTI event callbacks. */
TThreadStartCallback::registerCallback(&OnThreadStart);
TThreadEndCallback::registerCallback(&OnThreadEnd);
TMonitorContendedEnterCallback::registerCallback(
&OnMonitorContendedEnterForThreadRecording);
TMonitorContendedEnteredCallback::registerCallback(
&OnMonitorContendedEnteredForThreadRecording);
TMonitorWaitCallback::registerCallback(&OnMonitorWait);
TMonitorWaitedCallback::registerCallback(&OnMonitorWaited);
TDataDumpRequestCallback::registerCallback(
&OnDataDumpRequestForDumpThreadRecordData);
if (registerJVMTICallbacks(jvmti)) {
logger->printCritMsg("Couldn't register normal event.");
return;
}
}
/*!
* \brief Register JNI hook point.
*
* \param env [in] JNI environment.
*/
void TThreadRecorder::registerJNIHookPoint(JNIEnv *env) {
/* Set JNI varibles */
threadClass = env->FindClass("java/lang/Thread");
currentThreadMethod = env->GetStaticMethodID(threadClass, "currentThread",
"()Ljava/lang/Thread;");
/* Set JNI function callbacks. */
TJVMSleepCallback::registerCallback(&JVM_SleepPrologue, &JVM_SleepEpilogue);
TUnsafeParkCallback::registerCallback(&UnsafeParkPrologue,
&UnsafeParkEpilogue);
}
/*!
* \brief Register I/O tracer.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
*
* \return true if succeeded.
*/
bool TThreadRecorder::registerIOTracer(jvmtiEnv *jvmti, JNIEnv *env) {
char *iotrace_classfile = conf->ThreadRecordIOTracer()->get();
if (iotrace_classfile == NULL) {
logger->printWarnMsg("thread_record_iotracer is not set.");
logger->printWarnMsg("Turn off I/O recording.");
return false;
}
jclass iotraceClass = env->FindClass("sun/misc/IoTrace");
if (iotraceClass == NULL) {
logger->printWarnMsg("Could not find sun.misc.IoTrace class.");
logger->printWarnMsg("Turn off I/O recording.");
env->ExceptionClear(); // It may occur NoClassDefFoumdError
return false;
}
int fd = open(iotrace_classfile, O_RDONLY);
if (fd == -1) {
logger->printWarnMsgWithErrno("Could not open thread_record_iotracer: %s",
iotrace_classfile);
logger->printWarnMsg("Turn off I/O recording.");
return false;
}
struct stat st;
if (fstat(fd, &st) == -1) {
logger->printWarnMsgWithErrno(
"Could not get stat of thread_record_iotracer: %s", iotrace_classfile);
logger->printWarnMsg("Turn off I/O recording.");
close(fd);
return false;
}
unsigned char *iotracer_bytecode = (unsigned char *)malloc(st.st_size);
ssize_t read_bytes = read(fd, iotracer_bytecode, st.st_size);
int saved_errno = errno;
close(fd);
if (read_bytes == -1) {
errno = saved_errno;
logger->printWarnMsgWithErrno(
"Could not read bytecodes from thread_record_iotracer: %s",
iotrace_classfile);
logger->printWarnMsg("Turn off I/O recording.");
return false;
} else if (read_bytes != st.st_size) {
errno = saved_errno;
logger->printWarnMsg(
"Could not read bytecodes from thread_record_iotracer: %s",
iotrace_classfile);
logger->printWarnMsg("Turn off I/O recording.");
return false;
}
/* Redefine IoTrace */
jvmtiClassDefinition classDef = {iotraceClass, (jint)st.st_size,
iotracer_bytecode};
if (isError(jvmti, jvmti->RedefineClasses(1, &classDef))) {
logger->printWarnMsg("Could not redefine sun.misc.IoTrace .");
logger->printWarnMsg("Turn off I/O recording.");
return false;
}
/* Register hook native methods. */
JNINativeMethod methods[] = {
{(char *)"socketReadBegin",
(char *)"()Ljava/lang/Object;",
(void *)&IoTrace_socketReadBegin},
{(char *)"socketReadEnd",
(char *)"(Ljava/lang/Object;Ljava/net/InetAddress;IIJ)V",
(void *)&IoTrace_socketReadEnd},
{(char *)"socketWriteBegin",
(char *)"()Ljava/lang/Object;",
(void *)&IoTrace_socketWriteBegin},
{(char *)"socketWriteEnd",
(char *)"(Ljava/lang/Object;Ljava/net/InetAddress;IJ)V",
(void *)&IoTrace_socketWriteEnd},
{(char *)"fileReadBegin",
(char *)"(Ljava/lang/String;)Ljava/lang/Object;",
(void *)&IoTrace_fileReadBegin},
{(char *)"fileReadEnd",
(char *)"(Ljava/lang/Object;J)V",
(void *)&IoTrace_fileReadEnd},
{(char *)"fileWriteBegin",
(char *)"(Ljava/lang/String;)Ljava/lang/Object;",
(void *)&IoTrace_fileWriteBegin},
{(char *)"fileWriteEnd",
(char *)"(Ljava/lang/Object;J)V",
(void *)&IoTrace_fileWriteEnd}};
env->RegisterNatives(iotraceClass, methods, 8);
return true;
}
/*!
* \brief Unegister I/O tracer.
*
* \param env [in] JNI environment.
*/
void TThreadRecorder::UnregisterIOTracer(JNIEnv *env) {
if (conf->ThreadRecordIOTracer()->get() == NULL) {
return;
}
jclass iotraceClass = env->FindClass("sun/misc/IoTrace");
if (iotraceClass == NULL) {
env->ExceptionClear(); // It may occur NoClassDefFoumdError
return;
}
/* Register hook native methods. */
JNINativeMethod methods[] = {
{(char *)"socketReadBegin",
(char *)"()Ljava/lang/Object;",
(void *)&IoTrace_dummy},
{(char *)"socketReadEnd",
(char *)"(Ljava/lang/Object;Ljava/net/InetAddress;IIJ)V",
(void *)&IoTrace_dummy},
{(char *)"socketWriteBegin",
(char *)"()Ljava/lang/Object;",
(void *)&IoTrace_dummy},
{(char *)"socketWriteEnd",
(char *)"(Ljava/lang/Object;Ljava/net/InetAddress;IJ)V",
(void *)&IoTrace_dummy},
{(char *)"fileReadBegin",
(char *)"(Ljava/lang/String;)Ljava/lang/Object;",
(void *)&IoTrace_dummy},
{(char *)"fileReadEnd",
(char *)"(Ljava/lang/Object;J)V",
(void *)&IoTrace_dummy},
{(char *)"fileWriteBegin",
(char *)"(Ljava/lang/String;)Ljava/lang/Object;",
(void *)&IoTrace_dummy},
{(char *)"fileWriteEnd",
(char *)"(Ljava/lang/Object;J)V",
(void *)&IoTrace_dummy}};
env->RegisterNatives(iotraceClass, methods, 8);
return;
}
/*!
* \brief Initialize HeapStats Thread Recorder.
*
* \param jvmti [in] JVMTI environment.
* \param jni [in] JNI environment.
* \param buf_sz [in] Size of ring buffer.
*/
void TThreadRecorder::initialize(jvmtiEnv *jvmti, JNIEnv *env, size_t buf_sz) {
if (likely(inst == NULL)) {
inst = new TThreadRecorder(buf_sz);
registerHookPoint(jvmti, env);
registerJNIHookPoint(env);
registerIOTracer(jvmti, env);
inst->registerAllThreads(jvmti);
}
/* Start to hook JVMTI event */
TThreadStartCallback::switchEventNotification(jvmti, JVMTI_ENABLE);
TThreadEndCallback::switchEventNotification(jvmti, JVMTI_ENABLE);
TMonitorContendedEnterCallback::switchEventNotification(jvmti, JVMTI_ENABLE);
TMonitorContendedEnteredCallback::switchEventNotification(jvmti,
JVMTI_ENABLE);
TMonitorWaitCallback::switchEventNotification(jvmti, JVMTI_ENABLE);
TMonitorWaitedCallback::switchEventNotification(jvmti, JVMTI_ENABLE);
/* Start to hook JNI function */
TJVMSleepCallback::switchCallback(env, true);
TUnsafeParkCallback::switchCallback(env, true);
}
/*!
* \brief Dump record data to file.
*
* \param fname [in] File name to dump record data.
*/
void TThreadRecorder::dump(const char *fname) {
int fd = creat(fname, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd == -1) {
logger->printWarnMsgWithErrno("Thread Recorder dump failed.");
throw errno;
}
/* Write byte order mark. */
char bom = BOM;
write(fd, &bom, sizeof(char));
/* Dump thread list. */
auto workIDMap(threadIDMap);
int threadIDMapSize = workIDMap.size();
write(fd, &threadIDMapSize, sizeof(int));
for (auto itr = workIDMap.begin(); itr != workIDMap.end(); itr++) {
jlong id = itr->first;
int classname_length = strlen(itr->second);
write(fd, &id, sizeof(jlong));
write(fd, &classname_length, sizeof(int));
write(fd, itr->second, classname_length);
}
/* Dump thread event. */
write(fd, record_buffer, aligned_buffer_size);
close(fd);
}
/*!
* \brief Finalize HeapStats Thread Recorder.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param fname [in] File name to dump record data.
*/
void TThreadRecorder::finalize(jvmtiEnv *jvmti, JNIEnv *env,
const char *fname) {
/* Stop JVMTI events which are used by ThreadRecorder only. */
TThreadStartCallback::switchEventNotification(jvmti, JVMTI_DISABLE);
TThreadEndCallback::switchEventNotification(jvmti, JVMTI_DISABLE);
TMonitorContendedEnteredCallback::switchEventNotification(jvmti,
JVMTI_DISABLE);
TMonitorWaitCallback::switchEventNotification(jvmti, JVMTI_DISABLE);
TMonitorWaitedCallback::switchEventNotification(jvmti, JVMTI_DISABLE);
/* Stop JNI function hooks. */
TJVMSleepCallback::switchCallback(env, false);
TUnsafeParkCallback::switchCallback(env, false);
/* Unregister JVMTI event callbacks which are used by ThreadRecorder. */
TThreadStartCallback::unregisterCallback(&OnThreadStart);
TThreadEndCallback::unregisterCallback(&OnThreadEnd);
TMonitorContendedEnterCallback::unregisterCallback(
&OnMonitorContendedEnterForThreadRecording);
TMonitorContendedEnteredCallback::unregisterCallback(
&OnMonitorContendedEnteredForThreadRecording);
TMonitorWaitCallback::unregisterCallback(&OnMonitorWait);
TMonitorWaitedCallback::unregisterCallback(&OnMonitorWaited);
TDataDumpRequestCallback::unregisterCallback(
&OnDataDumpRequestForDumpThreadRecordData);
/* Refresh JVMTI event callbacks */
registerJVMTICallbacks(jvmti);
/* Unregister JNI function hooks which are used by ThreadRecorder. */
TJVMSleepCallback::unregisterCallback(&JVM_SleepPrologue, &JVM_SleepEpilogue);
TUnsafeParkCallback::unregisterCallback(&UnsafeParkPrologue,
&UnsafeParkEpilogue);
/* Stop IoTrace hook */
UnregisterIOTracer(env);
/* Wait until all tasks are finished. */
while (processing > 0) {
sched_yield();
}
/* Stop HeapStats Thread Recorder */
inst->dump(fname);
delete inst;
inst = NULL;
}
/*!
* \brief Set JVMTI capabilities to work HeapStats Thread Recorder.
*
* \param capabilities [out] JVMTI capabilities.
*/
void TThreadRecorder::setCapabilities(jvmtiCapabilities *capabilities) {
/* For RedefineClass() */
capabilities->can_redefine_classes = 1;
capabilities->can_redefine_any_class = 1;
}
/*!
* \brief Register new thread to thread id map.
*
* \param jvmti [in] JVMTI environment.
* \param thread [in] jthread object of new thread.
*/
void TThreadRecorder::registerNewThread(jvmtiEnv *jvmti, jthread thread) {
void *thread_oop = *(void **)thread;
jlong id = TVMFunctions::getInstance()->GetThreadId(thread_oop);
jvmtiThreadInfo threadInfo;
jvmti->GetThreadInfo(thread, &threadInfo);
{
TThreadIDMap::accessor acc;
if (!threadIDMap.insert(acc, id)) {
free(acc->second);
}
acc->second = strdup(threadInfo.name);
}
jvmti->Deallocate((unsigned char *)threadInfo.name);
}
/*!
* \brief Register all existed threads to thread id map.
*
* \param jvmti [in] JVMTI environment.
*/
void TThreadRecorder::registerAllThreads(jvmtiEnv *jvmti) {
jint thread_count;
jthread *threads;
jvmti->GetAllThreads(&thread_count, &threads);
for (int Cnt = 0; Cnt < thread_count; Cnt++) {
registerNewThread(jvmti, threads[Cnt]);
}
jvmti->Deallocate((unsigned char *)threads);
}
/*!
* \brief Enqueue new event.
*
* \param thread [in] jthread object which occurs new event.
* \param event [in] New thread event.
* \param additionalData [in] Additional data if exist.
*/
void TThreadRecorder::putEvent(jthread thread, TThreadEvent event,
jlong additionalData) {
struct timeval tv;
gettimeofday(&tv, NULL);
TEventRecord eventRecord __attribute__((aligned(32))); // for YMM vmovdqa
eventRecord.time = (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
eventRecord.thread_id =
TVMFunctions::getInstance()->GetThreadId(*(void **)thread);
eventRecord.event = event;
eventRecord.additionalData = additionalData;
if (unlikely(top_of_buffer->event == ThreadEnd)) {
TThreadIDMap::accessor acc;
if (threadIDMap.find(acc, top_of_buffer->thread_id)) {
free(acc->second);
threadIDMap.erase(acc);
}
}
spinLockWait(&bufferLockVal);
{
memcpy32(top_of_buffer, &eventRecord);
if (unlikely(++top_of_buffer == end_of_buffer)) {
logger->printDebugMsg(
"Ring buffer for Thread Recorder has been rewinded.");
top_of_buffer = (TEventRecord *)record_buffer;
}
}
spinLockRelease(&bufferLockVal);
}
| 26,103
|
C++
|
.cpp
| 716
| 31.25838
| 82
| 0.686783
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,022
|
heapstatsMBean.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/heapstatsMBean.cpp
|
/*!
* \file heapstatsMBean.cpp
* \brief JNI implementation for HeapStatsMBean.
* Copyright (C) 2014-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <jni.h>
#include <limits.h>
#include <sched.h>
#include <list>
#ifdef HAVE_ATOMIC
#include <atomic>
#else
#include <cstdatomic>
#endif
#include "globals.hpp"
#include "configuration.hpp"
#include "heapstatsMBean.hpp"
#include "util.hpp"
/* Variables */
static jclass mapCls = NULL;
static jmethodID map_ctor = NULL;
static jmethodID map_put = NULL;
static jclass boolCls = NULL;
static jmethodID boolValue = NULL;
static jobject boolFalse = NULL;
static jobject boolTrue = NULL;
static jobjectArray logLevelArray;
static jobjectArray rankOrderArray;
static jclass integerCls = NULL;
static jmethodID intValue = NULL;
static jmethodID intValueOf = NULL;
static jclass longCls = NULL;
static jmethodID longValue = NULL;
static jmethodID longValueOf = NULL;
static jclass linkedCls = NULL;
static volatile bool isLoaded = false;
static std::atomic_int processing(0);
/*!
* \brief Raise Java Exception.
*
* \param env Pointer of JNI environment.
* \param cls_sig Class signature of Throwable.
* \param message Error message.
*/
static void raiseException(JNIEnv *env, const char *cls_sig,
const char *message) {
jthrowable ex = env->ExceptionOccurred();
if (ex != NULL) {
env->Throw(ex);
return;
}
jclass ex_cls = env->FindClass(cls_sig);
env->ThrowNew(ex_cls, message);
}
/*!
* \brief Load jclass object.
* This function returns jclass as JNI global object.
*
* \param env Pointer of JNI environment.
* \param className Class name to load.
* \return jclass object.
*/
static jclass loadClassGlobal(JNIEnv *env, const char *className) {
jclass cls = env->FindClass(className);
if (cls != NULL) {
cls = (jclass)env->NewGlobalRef(cls);
if (cls == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Could not get JNI Global value.");
}
} else {
raiseException(env, "java/lang/NoClassDefFoundError", className);
}
return cls;
}
/*!
* \brief Preparation for Map object.
* This function initialize JNI variables for LinkedHashMap to use in
* getConfigurationList0()
*
* \param env Pointer of JNI environment.
* \return true if succeeded.
*/
static bool prepareForMapObject(JNIEnv *env) {
mapCls = loadClassGlobal(env, "java/util/LinkedHashMap");
if (mapCls == NULL) {
return false;
}
map_ctor = env->GetMethodID(mapCls, "<init>", "()V");
map_put = env->GetMethodID(
mapCls, "put",
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
if ((map_ctor == NULL) || (map_put == NULL)) {
raiseException(env, "java/lang/RuntimeException",
"Could not get methods in LinkedHashMap.");
return false;
}
return true;
}
/*!
* \brief Preparation for Boolean object.
* This function initialize JNI variables for Boolean.TRUE and FALSE.
*
* \param env Pointer of JNI environment.
* \param fieldName Field name in Boolean. It must be "TRUE" or "FALSE".
* \param target jobject to store value of field.
* \return true if succeeded.
*/
static bool prepareForBoolean(JNIEnv *env, const char *fieldName,
jobject *target) {
if (boolCls == NULL) {
boolCls = loadClassGlobal(env, "java/lang/Boolean");
if (boolCls == NULL) {
return false;
}
boolValue = env->GetMethodID(boolCls, "booleanValue", "()Z");
if (boolValue == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Could not find Boolean method.");
return false;
}
}
jfieldID field =
env->GetStaticFieldID(boolCls, fieldName, "Ljava/lang/Boolean;");
if (field == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Could not find Boolean field.");
return false;
}
*target = env->GetStaticObjectField(boolCls, field);
if (*target != NULL) {
*target = env->NewGlobalRef(*target);
if (*target == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Could not get JNI Global value.");
return false;
}
} else {
raiseException(env, "java/lang/RuntimeException",
"Could not get Boolean value.");
return false;
}
return true;
}
/*!
* \brief Preparation for Enum object in HeapStatsMBean.
*
* \param env Pointer of JNI environment.
* \param className Class name to initialize.
* It must be "LogLevel" or "RankOrder".
* \param target jobjectArray to store values in enum.
* \return true if succeeded.
*/
static bool prepareForEnumObject(JNIEnv *env, const char *className,
jobjectArray *target) {
char jniCls[100] = "jp/co/ntt/oss/heapstats/mbean/HeapStatsMBean$";
strcat(jniCls, className);
char sig[110];
sprintf(sig, "()[L%s;", jniCls);
jclass cls = loadClassGlobal(env, jniCls);
if (cls == NULL) {
return false;
}
jmethodID values = env->GetStaticMethodID(cls, "values", sig);
if (values == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Could not get Enum values method.");
return false;
}
*target = (jobjectArray)env->CallStaticObjectMethod(cls, values);
if (*target != NULL) {
*target = (jobjectArray)env->NewGlobalRef(*target);
if (*target == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Could not get JNI Global value.");
return false;
}
} else {
raiseException(env, "java/lang/RuntimeException",
"Could not get Enum values.");
return false;
}
return true;
}
/*!
* \brief Preparation for number object.
* This function can initialize Integer and Long.
*
* \param env Pointer of JNI environment.
* \param className Class name to initialize.
* It must be "Integer" or "Long".
* \param cls jclass object to store its class.
* \param valueOfMethod jmethodID to store "valueOf" method in its class.
* \param valueMethod jmethodID to store "intValue" or "longValue" method
* in its class.
* \return true if succeeded.
*/
static bool prepareForNumObject(JNIEnv *env, const char *className, jclass *cls,
jmethodID *valueOfMethod,
jmethodID *valueMethod) {
char jniCls[30] = "java/lang/";
strcat(jniCls, className);
char sig[40];
*cls = loadClassGlobal(env, jniCls);
if (*cls == NULL) {
return false;
}
if (strcmp(className, "Long") == 0) {
sprintf(sig, "(J)L%s;", jniCls);
*valueOfMethod = env->GetStaticMethodID(*cls, "valueOf", sig);
*valueMethod = env->GetMethodID(*cls, "longValue", "()J");
} else {
sprintf(sig, "(I)L%s;", jniCls);
*valueOfMethod = env->GetStaticMethodID(*cls, "valueOf", sig);
*valueMethod = env->GetMethodID(*cls, "intValue", "()I");
}
if ((*valueOfMethod == NULL) || (*valueMethod == NULL)) {
raiseException(env, "java/lang/RuntimeException",
"Could not get valueOf method.");
return false;
}
return true;
}
/*!
* \brief Register JNI functions in libheapstats.
*
* \param env Pointer of JNI environment.
* \param cls Class of HeapStatsMBean implementation.
*/
JNIEXPORT void JNICALL RegisterHeapStatsNative(JNIEnv *env, jclass cls) {
/* Regist JNI functions */
JNINativeMethod methods[] = {
{(char *)"getHeapStatsVersion0",
(char *)"()Ljava/lang/String;",
(void *)GetHeapStatsVersion},
{(char *)"getConfiguration0",
(char *)"(Ljava/lang/String;)Ljava/lang/Object;",
(void *)GetConfiguration},
{(char *)"getConfigurationList0",
(char *)"()Ljava/util/Map;",
(void *)GetConfigurationList},
{(char *)"changeConfiguration0",
(char *)"(Ljava/lang/String;Ljava/lang/Object;)Z",
(void *)ChangeConfiguration},
{(char *)"invokeLogCollection0",
(char *)"()Z",
(void *)InvokeLogCollection},
{(char *)"invokeAllLogCollection0",
(char *)"()Z",
(void *)InvokeAllLogCollection}};
if (env->RegisterNatives(cls, methods, 6) != 0) {
raiseException(env, "java/lang/UnsatisfiedLinkError",
"Native function for HeapStatsMBean failed.");
return;
}
TProcessMark mark(processing);
/* Initialize variables. */
linkedCls = (jclass)env->NewGlobalRef(cls);
isLoaded = true;
/* For Map object */
if (!prepareForMapObject(env)) {
return;
}
/* For Boolean object */
if (!prepareForBoolean(env, "TRUE", &boolTrue) ||
!prepareForBoolean(env, "FALSE", &boolFalse)) {
return;
}
/* For Enum values */
if (!prepareForEnumObject(env, "LogLevel", &logLevelArray) ||
!prepareForEnumObject(env, "RankOrder", &rankOrderArray)) {
return;
}
/* For number Object */
if (!prepareForNumObject(env, "Integer", &integerCls, &intValueOf,
&intValue) ||
!prepareForNumObject(env, "Long", &longCls, &longValueOf, &longValue)) {
return;
}
}
static void *JNIDummy(void) {
return NULL;
}
/*!
* \brief Unregister JNI functions in libheapstats.
* \param env Pointer of JNI environment.
*/
void UnregisterHeapStatsNatives(JNIEnv *env) {
if (!isLoaded) {
return;
}
/* Regist JNI functions */
JNINativeMethod methods[] = {
{(char *)"getHeapStatsVersion0",
(char *)"()Ljava/lang/String;",
(void *)JNIDummy},
{(char *)"getConfiguration0",
(char *)"(Ljava/lang/String;)Ljava/lang/Object;",
(void *)JNIDummy},
{(char *)"getConfigurationList0",
(char *)"()Ljava/util/Map;",
(void *)JNIDummy},
{(char *)"changeConfiguration0",
(char *)"(Ljava/lang/String;Ljava/lang/Object;)Z",
(void *)JNIDummy},
{(char *)"invokeLogCollection0",
(char *)"()Z",
(void *)JNIDummy},
{(char *)"invokeAllLogCollection0",
(char *)"()Z",
(void *)JNIDummy}};
if (env->RegisterNatives(linkedCls, methods, 6) != 0) {
raiseException(env, "java/lang/UnsatisfiedLinkError",
"Could not unregister HeapStats native functions.");
}
env->DeleteGlobalRef(linkedCls);
while (processing > 0) {
sched_yield();
}
}
/*!
* \brief Get HeapStats version string from libheapstats.
*
* \param env Pointer of JNI environment.
* \param obj Instance of HeapStatsMBean implementation.
* \return Version string which is attached.
*/
JNIEXPORT jstring JNICALL GetHeapStatsVersion(JNIEnv *env, jobject obj) {
TProcessMark mark(processing);
jstring versionStr = env->NewStringUTF(PACKAGE_STRING
" ("
#ifdef SSE2
"SSE2)"
#endif
#ifdef SSE4
"SSE4)"
#endif
#ifdef AVX
"AVX)"
#endif
#if (!defined AVX) && (!defined SSE4) && (!defined SSE2)
"None)"
#endif
);
if (versionStr == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Could not create HeapStats version string.");
}
return versionStr;
}
/*!
* \brief Create java.lang.String instance.
*
* \param env Pointer of JNI environment.
* \param val Value of string.
* \return Instance of String.
*/
static jstring createString(JNIEnv *env, const char *val) {
if (val == NULL) {
return NULL;
}
jstring ret = env->NewStringUTF(val);
if (ret == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Cannot get string in JNI");
}
return ret;
}
/*!
* \brief Get configuration value as jobject.
*
* \param env Pointer of JNI environment.
* \param config Configuration element.
* \return jobject value of configuration.
*/
static jobject getConfigAsJObject(JNIEnv *env, TConfigElementSuper *config) {
jobject ret = NULL;
switch (config->getConfigDataType()) {
case BOOLEAN:
ret = ((TBooleanConfig *)config)->get() ? boolTrue : boolFalse;
break;
case INTEGER:
ret = env->CallStaticObjectMethod(integerCls, intValueOf,
((TIntConfig *)config)->get());
break;
case LONG:
ret = env->CallStaticObjectMethod(longCls, longValueOf,
((TLongConfig *)config)->get());
break;
case STRING:
ret = createString(env, ((TStringConfig *)config)->get());
break;
case LOGLEVEL:
ret = env->GetObjectArrayElement(logLevelArray,
((TLogLevelConfig *)config)->get());
break;
case RANKORDER:
ret = env->GetObjectArrayElement(rankOrderArray,
((TRankOrderConfig *)config)->get());
break;
}
return ret;
}
/*!
* \brief Get HeapStats agent configuration from libheapstats.
*
* \param env Pointer of JNI environment.
* \param obj Instance of HeapStatsMBean implementation.
* \param key Name of configuration.
* \return Current value of configuration key.
*/
JNIEXPORT jobject JNICALL
GetConfiguration(JNIEnv *env, jobject obj, jstring key) {
TProcessMark mark(processing);
const char *opt = env->GetStringUTFChars(key, NULL);
if (opt == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Cannot get string in JNI");
return NULL;
}
jobject result = NULL;
std::list<TConfigElementSuper *> configs = conf->getConfigs();
for (std::list<TConfigElementSuper *>::iterator itr = configs.begin();
itr != configs.end(); itr++) {
if (strcmp(opt, (*itr)->getConfigName()) == 0) {
result = getConfigAsJObject(env, *itr);
jthrowable ex = env->ExceptionOccurred();
if (ex != NULL) {
env->Throw(ex);
return NULL;
}
}
}
env->ReleaseStringUTFChars(key, opt);
return result;
}
/*!
* \brief Get all of HeapStats agent configurations from libheapstats.
*
* \param env Pointer of JNI environment.
* \param obj Instance of HeapStatsMBean implementation.
* \return Current configuration list.
*/
JNIEXPORT jobject JNICALL GetConfigurationList(JNIEnv *env, jobject obj) {
TProcessMark mark(processing);
jobject result = env->NewObject(mapCls, map_ctor);
if (result == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Cannot create Map instance.");
return NULL;
}
std::list<TConfigElementSuper *> configs = conf->getConfigs();
jstring key;
jobject value = NULL;
for (std::list<TConfigElementSuper *>::iterator itr = configs.begin();
itr != configs.end(); itr++) {
key = createString(env, (*itr)->getConfigName());
if (key == NULL) {
return NULL;
}
value = getConfigAsJObject(env, *itr);
env->CallObjectMethod(result, map_put, key, value);
if (env->ExceptionCheck()) {
raiseException(env, "java/lang/RuntimeException",
"Cannot put config to Map instance.");
return NULL;
}
}
return result;
}
/*!
* \brief Change HeapStats agent configuration in libheapstats.
*
* \param env Pointer of JNI environment.
* \param obj Instance of HeapStatsMBean implementation.
* \param key Name of configuration.
* \param value New configuration value.
* \return Result of this change.
*/
JNIEXPORT jboolean JNICALL
ChangeConfiguration(JNIEnv *env, jobject obj, jstring key, jobject value) {
TProcessMark mark(processing);
jclass valueCls = env->GetObjectClass(value);
char *opt = (char *)env->GetStringUTFChars(key, NULL);
if (opt == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Cannot get string in JNI");
return JNI_FALSE;
}
TConfiguration new_conf = *conf;
std::list<TConfigElementSuper *> configs = new_conf.getConfigs();
for (std::list<TConfigElementSuper *>::iterator itr = configs.begin();
itr != configs.end(); itr++) {
try{
if (strcmp(opt, (*itr)->getConfigName()) == 0) {
switch ((*itr)->getConfigDataType()) {
case BOOLEAN:
if (env->IsAssignableFrom(valueCls, boolCls)) {
jboolean newval = env->CallBooleanMethod(value, boolValue);
((TBooleanConfig *)*itr)->set((bool)newval);
} else {
raiseException(env, "java/lang/ClassCastException",
"Cannot convert new configuration to Boolean.");
}
break;
case INTEGER:
if (env->IsAssignableFrom(valueCls, integerCls)) {
jint newval = env->CallIntMethod(value, intValue);
((TIntConfig *)*itr)->set(newval);
} else {
raiseException(env, "java/lang/ClassCastException",
"Cannot convert new configuration to Integer.");
}
break;
case LONG:
if (env->IsAssignableFrom(valueCls, longCls)) {
jlong newval = env->CallLongMethod(value, longValue);
((TLongConfig *)*itr)->set(newval);
} else {
raiseException(env, "java/lang/ClassCastException",
"Cannot convert new configuration to Long.");
}
break;
case LOGLEVEL:
for (int Cnt = 0; Cnt < env->GetArrayLength(logLevelArray); Cnt++) {
if (env->IsSameObject(
env->GetObjectArrayElement(logLevelArray, Cnt), value)) {
((TLogLevelConfig *)*itr)->set((TLogLevel)Cnt);
break;
}
}
break;
case RANKORDER:
for (int Cnt = 0;
Cnt < env->GetArrayLength(rankOrderArray); Cnt++) {
if (env->IsSameObject(
env->GetObjectArrayElement(rankOrderArray, Cnt), value)) {
((TRankOrderConfig *)*itr)->set((TRankOrder)Cnt);
break;
}
}
break;
default: // String
if (value == NULL) {
((TStringConfig *)*itr)->set(NULL);
} else if (env->IsAssignableFrom(
valueCls, env->FindClass("java/lang/String"))) {
char *val = (char *)env->GetStringUTFChars((jstring)value, NULL);
if (val == NULL) {
raiseException(env, "java/lang/RuntimeException",
"Cannot get string in JNI");
} else {
((TStringConfig *)*itr)->set(val);
env->ReleaseStringUTFChars((jstring)value, val);
}
} else {
raiseException(env, "java/lang/RuntimeException",
"Cannot support this configuration type.");
}
}
}
} catch (const char *msg) {
const char *const_msg = " cannot be set new value: ";
size_t msg_len = strlen(opt) + strlen(const_msg) + strlen(msg);
char *exception_msg = (char *)malloc(msg_len);
sprintf(exception_msg, "%s%s%s", opt, const_msg, msg);
raiseException(env, "java/lang/IllegalArgumentException", exception_msg);
free(exception_msg);
}
}
jboolean result = JNI_FALSE;
if (!env->ExceptionOccurred()) {
if (new_conf.validate()) {
conf->merge(&new_conf);
logger->printInfoMsg("Configuration has been changed through JMX.");
conf->printSetting();
result = JNI_TRUE;
} else {
raiseException(env, "java/lang/IllegalArgumentException",
"Illegal parameter was set.");
}
}
env->ReleaseStringUTFChars(key, opt);
return result;
}
/*!
* \brief Invoke Resource Log collection at libheapstats.
*
* \param env Pointer of JNI environment.
* \param obj Instance of HeapStatsMBean implementation.
* \return Result of this call.
*/
JNIEXPORT jboolean JNICALL InvokeLogCollection(JNIEnv *env, jobject obj) {
TProcessMark mark(processing);
int ret = logManager->collectLog(NULL, env, Signal,
(TMSecTime)getNowTimeSec(), "JMX event");
return ret == 0 ? JNI_TRUE : JNI_FALSE;
}
/*!
* \brief Invoke All Log collection at libheapstats.
*
* \param env Pointer of JNI environment.
* \param obj Instance of HeapStatsMBean implementation.
* \return Result of this call.
*/
JNIEXPORT jboolean JNICALL InvokeAllLogCollection(JNIEnv *env, jobject obj) {
TProcessMark mark(processing);
int ret = logManager->collectLog(NULL, env, AnotherSignal,
(TMSecTime)getNowTimeSec(), "JMX event");
return ret == 0 ? JNI_TRUE : JNI_FALSE;
}
| 21,570
|
C++
|
.cpp
| 626
| 28.105431
| 82
| 0.629136
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,023
|
jvmInfo.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/jvmInfo.cpp
|
/*!
* \file jvmInfo.cpp
* \brief This file is used to get JVM performance information.
* Copyright (C) 2011-2020 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <dlfcn.h>
#include <stdlib.h>
#ifndef USE_VMSTRUCTS
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#endif
#ifdef USE_VMSTRUCTS
#include "vmStructScanner.hpp"
#endif
#include "globals.hpp"
#include "util.hpp"
#include "jvmInfo.hpp"
#if USE_PCRE
#include "pcreRegex.hpp"
#else
#include "cppRegex.hpp"
#endif
/*!
* \brief TJvmInfo constructor.
*/
TJvmInfo::TJvmInfo(void) {
/* Initialization. */
_nowFGC = NULL;
_nowYGC = NULL;
_edenSize = NULL;
_sur0Size = NULL;
_sur1Size = NULL;
_oldSize = NULL;
_metaspaceUsage = NULL;
_metaspaceCapacity = NULL;
_FGCTime = NULL;
_YGCTime = NULL;
_freqTime = NULL;
_gcCause = NULL;
perfAddr = 0;
elapFGCTime = 0;
elapYGCTime = 0;
fullgcFlag = false;
loadLogFlag = false;
loadDelayLogFlag = false;
/* Logging information. */
_syncPark = NULL;
_threadLive = NULL;
_safePointTime = NULL;
_safePoints = NULL;
_vmVersion = NULL;
_vmName = NULL;
_classPath = NULL;
_endorsedPath = NULL;
_javaVersion = NULL;
_javaHome = NULL;
_bootClassPath = NULL;
_vmArgs = NULL;
_vmFlags = NULL;
_javaCommand = NULL;
_tickTime = NULL;
/* Allocate GC cause container. */
if (unlikely(posix_memalign((void **)&gcCause, 32, /* for vmovdqa. */
MAXSIZE_GC_CAUSE) != 0)) {
throw "Couldn't allocate gc-cause memory!";
}
/* If failure allocate GC cause container. */
if (unlikely(gcCause == NULL)) {
throw "Couldn't allocate gc-cause memory!";
}
/* Initialize. */
memcpy(this->gcCause, UNKNOWN_GC_CAUSE, 16);
/* Get memory function address. */
this->maxMemFunc = (TGetMemoryFunc)dlsym(RTLD_DEFAULT, "JVM_MaxMemory");
this->totalMemFunc = (TGetMemoryFunc)dlsym(RTLD_DEFAULT, "JVM_TotalMemory");
/* Check memory function address. */
if (this->maxMemFunc == NULL) {
logger->printWarnMsg("Couldn't get memory function: JVM_MaxMemory");
}
if (this->totalMemFunc == NULL) {
logger->printWarnMsg("Couldn't get memory function: JVM_TotalMemory");
}
}
/*!
* \brief TJvmInfo destructor.
*/
TJvmInfo::~TJvmInfo() {
/* Free allcated GC cause container. */
free(gcCause);
}
/*!
* \brief Set JVM version from system property (java.vm.version) .
* \param jvmti [in] JVMTI Environment.
* \return Process result.
*/
bool TJvmInfo::setHSVersion(jvmtiEnv *jvmti) {
/* Setup HotSpot version. */
char *versionStr = NULL;
if (unlikely(isError(
jvmti, jvmti->GetSystemProperty("java.vm.version", &versionStr)))) {
logger->printCritMsg(
"Cannot get JVM version from \"java.vm.version\" property.");
return false;
} else {
logger->printDebugMsg("HotSpot version: %s", versionStr);
/*
* Version-String Scheme has changed since JDK 9 (JEP223).
* afterJDK9 means whether this version is after JDK 9(1) or not(0).
* major means hotspot version until JDK 8, jdk major version since JDK 9.
* minor means jdk minor version in every JDK.
* build means build version in every JDK.
* security means security version which has introduced since JDK 9.
*
* NOT support Early Access because the binaries do not archive.
* See also: https://bugs.openjdk.java.net/browse/JDK-8061493
*/
unsigned char afterJDK9 = 0;
unsigned char major = 0;
unsigned char minor = 0;
unsigned char build = 0;
unsigned char security = 0;
int result = 0;
/* Parse version string of JDK 8 and older. */
result = sscanf(versionStr, "%hhu.%hhu-b%hhu", &major, &minor, &build);
if (result != 3) {
/*
* Parse version string of JDK 9+ GA.
* GA release does not include minor and security.
*/
result = sscanf(versionStr, "%hhu+%hhu", &major, &build);
if (likely(result != 2)) {
/* Parse version string of JDK 9 GA (Minor #1) and later */
result = sscanf(versionStr, "%hhu.%hhu.%hhu+%hhu", &major, &minor,
&security, &build);
if (unlikely(result != 4)) {
logger->printCritMsg("Unsupported JVM version: %s", versionStr);
jvmti->Deallocate((unsigned char *)versionStr);
return false;
}
}
afterJDK9 = 1;
}
jvmti->Deallocate((unsigned char *)versionStr);
_hsVersion = MAKE_HS_VERSION(afterJDK9, major, minor, security, build);
}
return true;
}
#ifdef USE_VMSTRUCTS
/*!
* \brief Get JVM performance data address.<br>
* Use external VM structure.
* \return JVM performance data address.
*/
ptrdiff_t TJvmInfo::getPerfMemoryAddress(void) {
/* Symbol "gHotSpotVMStructs" is included in "libjvm.so". */
extern VMStructEntry *gHotSpotVMStructs;
/* If don't exist gHotSpotVMStructs. */
if (gHotSpotVMStructs == NULL) {
return 0;
}
/* Search perfomance data in gHotSpotVMStructs. */
int Cnt = 0;
ptrdiff_t addr = 0;
while (gHotSpotVMStructs[Cnt].typeName != NULL) {
/* Check each entry. */
if ((strncmp(gHotSpotVMStructs[Cnt].typeName, "PerfMemory", 10) == 0) &&
(strncmp(gHotSpotVMStructs[Cnt].fieldName, "_start", 6) == 0)) {
/* Found. */
addr = (ptrdiff_t) * (char **)gHotSpotVMStructs[Cnt].address;
break;
}
/* Go next entry. */
Cnt++;
}
return addr;
}
#else
/*!
* \brief Search JVM performance data address in memory.
* \param path [in] Path of hsperfdata.
* \return JVM performance data address.
*/
ptrdiff_t TJvmInfo::findPerfMemoryAddress(char *path) {
/* Search entries in performance file. */
ptrdiff_t addr = 0;
ptrdiff_t start_addr;
char mapPath[101];
char file[PATH_MAX + 1];
char *line = NULL;
char lineFmt[101];
size_t len = 0;
/* Decode link in path. */
char target[PATH_MAX + 1] = {0};
if (unlikely(realpath(path, target) == NULL)) {
return 0;
}
/* Open process map. */
snprintf(mapPath, 100, "/proc/%d/maps", getpid());
FILE *maps = fopen(mapPath, "r");
/* If failure open file. */
if (unlikely(maps == NULL)) {
return 0;
}
snprintf(lineFmt, 100, "%%tx-%%*x %%*s %%*x %%*x:%%*x %%*u %%%ds", PATH_MAX);
/* Repeats until EOF. */
while (getline(&line, &len, maps) != -1) {
/*
* From Linux Kernel source.
* fs/proc/task_mmu.c: static void show_map_vma()
*/
if (sscanf(line, lineFmt, &start_addr, file) == 2) {
/* If found load address. */
if (strcmp(file, target) == 0) {
addr = start_addr;
break;
}
}
}
/* Clean up after. */
if (line != NULL) {
free(line);
}
/* Close map. */
fclose(maps);
return addr;
}
/*!
* \brief Get JVM performance data address.<br>
* Use performance data file.
* \param env [in] JNI environment object.
* \return JVM performance data address.
*/
ptrdiff_t TJvmInfo::getPerfMemoryAddress(JNIEnv *env) {
/* Get perfomance file path. */
char perfPath[PATH_MAX];
char tempPath[PATH_MAX];
char *tmpdir = NULL;
char *username = NULL;
char *separator = NULL;
ptrdiff_t addr = 0;
/* GetSystemProperty() on JVMTI gets value from Arguments::_system_properties
* ONLY. */
/* Arguments::_system_properties differents from
* java.lang.System.getProperties(). */
/* So, this function uses java.lang.System.getProperty(String). */
tmpdir = GetSystemProperty(env, "java.io.tmpdir");
username = GetSystemProperty(env, "user.name");
separator = GetSystemProperty(env, "file.separator");
/* Value check. */
if ((tmpdir == NULL) || (username == NULL) || (separator == NULL)) {
/* Free allocated memories. */
if (tmpdir != NULL) {
free(tmpdir);
}
if (username != NULL) {
free(username);
}
if (separator != NULL) {
free(separator);
}
return 0;
}
/* Check and fix path. e.g "/usr/local/". */
if (strlen(tmpdir) > 0 && tmpdir[strlen(tmpdir) - 1] == '/') {
tmpdir[strlen(tmpdir) - 1] = '\0';
}
/* Make performance file path. */
sprintf(perfPath, "%s%shsperfdata_%s%s%d", tmpdir, separator, username,
separator, getpid());
sprintf(tempPath, "%stmp%shsperfdata_%s%s%d", separator, separator, username,
separator, getpid());
/* Clean up after get performance file path. */
free(tmpdir);
free(username);
free(separator);
/* Search entries in performance file. */
addr = findPerfMemoryAddress(perfPath);
if (addr == 0) {
addr = findPerfMemoryAddress(tempPath);
}
return addr;
}
#endif
/*!
* \brief Search GC-informaion address.
* \param entries [in,out] List of search target entries.
* \param count [in] Count of search target list.
*/
void TJvmInfo::SearchInfoInVMStruct(VMStructSearchEntry *entries, int count) {
/* Copy performance data's header. */
PerfDataPrologue prologue;
memcpy(&prologue, (void *)perfAddr, sizeof(PerfDataPrologue));
/* Check performance data's header. */
#ifdef WORDS_BIGENDIAN
if (unlikely(prologue.magic != (jint)0xcafec0c0)) {
#else
if (unlikely(prologue.magic != (jint)0xc0c0feca)) {
#endif
logger->printWarnMsg("Performance data's magic is broken.");
this->perfAddr = 0;
return;
}
ptrdiff_t ofs = 0;
int name_len = 0;
char *name = NULL;
PerfDataEntry entry;
/* Seek entries head. */
void *readPtr = (void *)(perfAddr + prologue.entry_offset);
/* Search target entries. */
for (int Cnt = 0; Cnt < prologue.num_entries; Cnt++) {
/* Copy entry data. */
ofs = (ptrdiff_t)readPtr;
memcpy(&entry, readPtr, sizeof(PerfDataEntry));
/* Get entry name. */
name_len = entry.data_offset - entry.name_offset;
name = (char *)calloc(name_len + 1, sizeof(char));
if (unlikely(name == NULL)) {
logger->printWarnMsg("Couldn't allocate entry memory!");
break;
}
/* Get entry name and check target entries. */
readPtr = (void *)(ofs + entry.name_offset);
memcpy(name, readPtr, name_len);
for (int i = 0; i < count; i++) {
/* If target entry. */
if ((strcmp(entries[i].entryName, name) == 0) &&
(entry.data_type == entries[i].entryType)) {
/* Store found entry. */
(*entries[i].entryValue) = (void *)(ofs + entry.data_offset);
}
}
/* Clean up and move next entry. */
free(name);
readPtr = (void *)(ofs + entry.entry_length);
}
/* Verify necessary information. */
for (int i = 0; i < count; i++) {
/* If failure get target entry. */
if (unlikely((*entries[i].entryValue) == NULL)) {
/* JEP 220: Modular Run-Time Images */
if (!isAfterJDK9() && (
(strcmp(entries[i].entryName,
"java.property.java.endorsed.dirs") == 0) ||
(strcmp(entries[i].entryName,
"sun.property.sun.boot.class.path") == 0))) {
logger->printWarnMsg(
"Necessary information isn't found in performance data. Entry: %s",
entries[i].entryName);
}
}
}
}
#ifdef USE_VMSTRUCTS
/*!
* \brief Detect GC-informaion address.<br>
* Use external VM structure.
* \sa "jdk/src/share/classes/sun/tools/jstat/resources/jstat_options"
*/
void TJvmInfo::detectInfoAddress(void) {
/* Get performance address. */
this->perfAddr = this->getPerfMemoryAddress();
#else
/*!
* \brief Detect GC-informaion address.<br>
* Use performance data file.
* \param env [in] JNI environment object.
* \sa "jdk/src/share/classes/sun/tools/jstat/resources/jstat_options"
*/
void TJvmInfo::detectInfoAddress(JNIEnv *env) {
/* Get performance address. */
this->perfAddr = this->getPerfMemoryAddress(env);
#endif
/* Check result. */
if (unlikely(this->perfAddr == 0)) {
#ifdef USE_VMSTRUCTS
logger->printWarnMsg("Necessary information isn't found in libjvm.so.");
#else
logger->printWarnMsg(
"Necessary information isn't found in performance file.");
#endif
return;
}
VMStructSearchEntry entries[] = {
{"sun.gc.collector.0.invocations", 'J', (void **)&this->_nowYGC},
{"sun.gc.collector.1.invocations", 'J', (void **)&this->_nowFGC},
{"sun.gc.generation.0.space.0.used", 'J', (void **)&this->_edenSize},
{"sun.gc.generation.0.space.1.used", 'J', (void **)&this->_sur0Size},
{"sun.gc.generation.0.space.2.used", 'J', (void **)&this->_sur1Size},
{"sun.gc.generation.1.space.0.used", 'J', (void **)&this->_oldSize},
{"sun.gc.collector.0.time", 'J', (void **)&this->_YGCTime},
{"sun.gc.collector.1.time", 'J', (void **)&this->_FGCTime},
{"sun.gc.cause", 'B', (void **)&this->_gcCause},
{"sun.rt._sync_Parks", 'J', (void **)&this->_syncPark},
{"java.threads.live", 'J', (void **)&this->_threadLive},
{"sun.rt.safepointTime", 'J', (void **)&this->_safePointTime},
{"sun.rt.safepoints", 'J', (void **)&this->_safePoints}};
int entryCount = sizeof(entries) / sizeof(VMStructSearchEntry);
SearchInfoInVMStruct(entries, entryCount);
/* Refresh log data load flag. */
loadLogFlag = (_syncPark != NULL) && (_threadLive != NULL) &&
(_safePointTime != NULL) && (_safePoints != NULL);
/* Get pointers of PermGen or Metaspace usage / capacity. */
VMStructSearchEntry metaspaceEntry[] = {
{"sun.gc.metaspace.used", 'J', (void **)&this->_metaspaceUsage},
{"sun.gc.metaspace.maxCapacity", 'J',
(void **)&this->_metaspaceCapacity}};
VMStructSearchEntry permGenEntry[] = {
{"sun.gc.generation.2.space.0.used", 'J',
(void **)&this->_metaspaceUsage},
{"sun.gc.generation.2.space.0.maxCapacity", 'J',
(void **)&this->_metaspaceCapacity}};
SearchInfoInVMStruct(this->isAfterCR6964458() ? metaspaceEntry : permGenEntry,
2);
}
/*!
* \brief Detect delayed GC-informaion address.
*/
void TJvmInfo::detectDelayInfoAddress(void) {
/* Check performance data's address. */
if (unlikely(this->perfAddr == 0)) {
return;
}
const int entryCount = 12;
VMStructSearchEntry entries[entryCount] = {
{"sun.os.hrt.frequency", 'J', (void **)&this->_freqTime},
{"java.property.java.vm.version", 'B', (void **)&this->_vmVersion},
{"java.property.java.vm.name", 'B', (void **)&this->_vmName},
{"java.property.java.class.path", 'B', (void **)&this->_classPath},
{"java.property.java.endorsed.dirs", 'B', (void **)&this->_endorsedPath},
{"java.property.java.version", 'B', (void **)&this->_javaVersion},
{"java.property.java.home", 'B', (void **)&this->_javaHome},
{"sun.property.sun.boot.class.path", 'B', (void **)&this->_bootClassPath},
{"java.rt.vmArgs", 'B', (void **)&this->_vmArgs},
{"java.rt.vmFlags", 'B', (void **)&this->_vmFlags},
{"sun.rt.javaCommand", 'B', (void **)&this->_javaCommand},
{"sun.os.hrt.ticks", 'J', (void **)&this->_tickTime}};
SearchInfoInVMStruct(entries, entryCount);
/* Refresh delay log data load flag. */
loadDelayLogFlag = (_freqTime != NULL) && (_vmVersion != NULL) &&
(_vmName != NULL) && (_classPath != NULL) &&
(_javaVersion != NULL) && (_javaHome != NULL) &&
(_vmArgs != NULL) && (_vmFlags != NULL) &&
(_javaCommand != NULL) && (_tickTime != NULL);
/* JEP 220: Modular Run-Time Images */
if (!isAfterJDK9()) {
loadDelayLogFlag &= (_endorsedPath != NULL) && (_bootClassPath != NULL);
}
/* JFR-backported JDK 8 is not supported */
#if USE_PCRE
TPCRERegex versionRegex("^\\d+\\.(\\d+)\\.\\d+_(\\d+)[^0-9]*$", 9);
#else
TCPPRegex versionRegex("^\\d+\\.(\\d+)\\.\\d+_(\\d+)[^0-9]*$");
#endif
if (versionRegex.find(this->_javaVersion)) {
int major = atoi(versionRegex.group(1));
int update = atoi(versionRegex.group(2));
if ((major == 8) && (update >= 262)) {
logger->printWarnMsg("JDK %s is not recommended due to JFR backport", this->_javaVersion);
}
}
}
| 16,653
|
C++
|
.cpp
| 477
| 30.542977
| 96
| 0.637927
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,024
|
logManager.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/logManager.cpp
|
/*!
* \file logManager.cpp
* \brief This file is used collect log information.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <gnu/libc-version.h>
#include <dirent.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/utsname.h>
#include <sys/wait.h>
#include <queue>
#include "globals.hpp"
#include "fsUtil.hpp"
#include "logManager.hpp"
/* Static variables. */
/*!
* \brief Mutex of collect normal log.
*/
pthread_mutex_t TLogManager::logMutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
/*!
* \brief Mutex of archive file.
*/
pthread_mutex_t TLogManager::archiveMutex =
PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
/* Macro defines. */
/*!
* \brief Format string macro for inode number type(ino_t).
*/
#define INODENUM_FORMAT_STR "%lu"
/*!
* \brief Separator string mcaro of between name and value for environment file.
*/
#define ENVIRON_VALUE_SEPARATOR "="
/*!
* \brief Symbol string mcaro of GC log filename.
*/
#define GCLOG_FILENAME_SYMBOL "_ZN9Arguments16_gc_log_filenameE"
/* Util method for log manager. */
/*!
* \brief Convert log cause to integer for file output.
* \param cause [in] Log collect cause.
* \return Number of log cause.
*/
inline int logCauseToInt(TInvokeCause cause) {
/* Convert invoke function cause. */
int logCause;
switch (cause) {
case ResourceExhausted:
case ThreadExhausted:
logCause = 1;
break;
case Signal:
case AnotherSignal:
logCause = 2;
break;
case Interval:
logCause = 3;
break;
case OccurredDeadlock:
logCause = 4;
break;
default:
/* Illegal. */
logCause = 0;
}
return logCause;
}
/* Class method. */
/*!
* \brief TLogManager constructor.
* \param env [in] JNI environment object.
* \param info [in] JVM running performance information.
*/
TLogManager::TLogManager(JNIEnv *env, TJvmInfo *info) {
/* Sanity check. */
if (unlikely(info == NULL)) {
throw "TJvmInfo is NULL.";
}
jvmInfo = info;
jvmCmd = NULL;
arcMaker = NULL;
jniArchiver = NULL;
char *tempdirPath = NULL;
/* Get temporary path of java */
tempdirPath = GetSystemProperty(env, "java.io.tmpdir");
try {
/* Create JVM socket commander. */
jvmCmd = new TJVMSockCmd(tempdirPath);
/* Archive file maker. */
arcMaker = new TCmdArchiver();
/* Archive file maker to use zip library in java. */
jniArchiver = new TJniZipArchiver();
/* Get GC log filename pointer. */
gcLogFilename = (char **)symFinder->findSymbol(GCLOG_FILENAME_SYMBOL);
if (unlikely(gcLogFilename == NULL)) {
throw 1;
}
} catch (...) {
free(tempdirPath);
delete jvmCmd;
delete arcMaker;
delete jniArchiver;
throw "TLogManager initialize failed!";
}
free(tempdirPath);
}
/*!
* \brief TLogManager destructor.
*/
TLogManager::~TLogManager(void) {
/* Destroy instance. */
delete jvmCmd;
delete arcMaker;
delete jniArchiver;
}
/*!
* \brief Collect log.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Invoke function cause.<br>
* E.g. ResourceExhausted, Signal, Interval.
* \param nowTime [in] Log collect time.
* \param description [in] Description of the event.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::collectLog(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause,
TMSecTime nowTime, const char *description) {
int result = 0;
/* Variable store archive file path. */
char arcPath[PATH_MAX] = {0};
/* Switch collecting log type by invoking cause. */
switch (cause) {
case ResourceExhausted:
case ThreadExhausted:
case AnotherSignal:
case OccurredDeadlock: {
/* Collect log about java running environment and etc.. */
int returnCode =
collectAllLog(jvmti, env, cause, nowTime,
(char *)arcPath, PATH_MAX, description);
if (unlikely(returnCode != 0)) {
/* Check and show disk full error. */
result = returnCode;
checkDiskFull(returnCode, "collect log");
}
}
default: {
/* Collect log about java and machine now status. */
int returnCode = collectNormalLog(cause, nowTime, arcPath);
if (unlikely(returnCode != 0)) {
/* Check and show disk full error. */
result = returnCode;
checkDiskFull(returnCode, "collect log");
}
}
}
return result;
}
/*!
* \brief Collect normal log.
* \param cause [in] Invoke function cause.<br>
* E.g. ResourceExhausted, Signal, Interval.
* \param nowTime [in] Log collect time.
* \param archivePath [in] Archive file path.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::collectNormalLog(TInvokeCause cause, TMSecTime nowTime,
char *archivePath) {
int result = EINVAL;
TLargeUInt systime = 0;
TLargeUInt usrtime = 0;
TLargeUInt vmsize = 0;
TLargeUInt rssize = 0;
TMachineTimes cpuTimes = {0};
/* Get java process information. */
if (unlikely(!getProcInfo(&systime, &usrtime, &vmsize, &rssize))) {
logger->printWarnMsg("Failure getting java process information.");
}
/* Get machine cpu times. */
if (unlikely(!getSysTimes(&cpuTimes))) {
logger->printWarnMsg("Failure getting machine cpu times.");
}
/* Make write log line. */
char logData[4097] = {0};
snprintf(logData, 4096,
"%lld,%d" /* Format : Logging information. */
",%llu,%llu,%llu,%llu" /* Format : Java process information. */
",%llu,%llu,%llu" /* Format : Machine CPU times. */
",%llu,%llu,%llu"
",%llu,%llu,%llu"
",%lld,%lld,%lld,%lld" /* Format : JVM running information. */
",%s\n", /* Format : Archive file name. */
/* Params : Logging information. */
nowTime,
logCauseToInt(cause),
/* Params : Java process information. */
usrtime, systime, vmsize, rssize,
/* Params : Machine CPU times. */
cpuTimes.usrTime, cpuTimes.lowUsrTime, cpuTimes.sysTime,
cpuTimes.idleTime, cpuTimes.iowaitTime, cpuTimes.irqTime,
cpuTimes.sortIrqTime, cpuTimes.stealTime, cpuTimes.guestTime,
/* Params : JVM running information. */
(long long int)jvmInfo->getSyncPark(),
(long long int)jvmInfo->getSafepointTime(),
(long long int)jvmInfo->getSafepoints(),
(long long int)jvmInfo->getThreadLive(),
/* Params : Archive file name. */
archivePath);
{
TMutexLocker locker(&logMutex);
/* Open log file. */
int fd = open(conf->HeapLogFile()->get(), O_CREAT | O_WRONLY | O_APPEND,
S_IRUSR | S_IWUSR);
/* If failure open file. */
if (unlikely(fd < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not open log file");
} else {
result = 0;
/* Write line to log file. */
if (unlikely(write(fd, logData, strlen(logData)) < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not write to log file");
}
/* Cleanup. */
if (unlikely(close(fd) < 0 && (result == 0))) {
result = errno;
logger->printWarnMsgWithErrno("Could not close log file");
}
}
}
return result;
}
/*!
* \brief Collect all log.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Invoke function cause.<br>
* E.g. ResourceExhausted, Signal, Interval.
* \param nowTime [in] Log collect time.
* \param archivePath [out] Archive file path.
* \param pathLen [in] Max size of paramter"archivePath".
* \param description [in] Description of the event.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::collectAllLog(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause,
TMSecTime nowTime, char *archivePath,
size_t pathLen, const char *description) {
/* Variable for process result. */
int result = 0;
/* Working directory path. */
char *basePath = NULL;
/* Archive file path. */
char *uniqArcName = NULL;
/* Make directory. */
result = createTempDir(&basePath, conf->LogDir()->get());
if (unlikely(result != 0)) {
logger->printWarnMsg("Failure create working directory.");
return result;
}
try {
/* Create enviroment report file. */
result = makeEnvironFile(basePath, cause, nowTime, description);
if (unlikely(result != 0)) {
logger->printWarnMsg("Failure create enviroment file.");
/* If raise disk full error. */
if (unlikely(isRaisedDiskFull(result))) {
throw 1;
}
}
/* Copy many files. */
result = copyInfoFiles(basePath);
/* If raise disk full error. */
if (unlikely(isRaisedDiskFull(result))) {
throw 1;
}
/* Create thread dump file. */
result = makeThreadDumpFile(jvmti, env, basePath, cause, nowTime);
if (unlikely(result != 0)) {
logger->printWarnMsg("Failure thread dumping.");
/* If raise disk full error. */
if (unlikely(isRaisedDiskFull(result))) {
throw 1;
}
}
/* Copy gc log file. */
result = copyGCLogFile(basePath);
if (unlikely(result != 0)) {
logger->printWarnMsgWithErrno("Could not copy GC log.");
/* If raise disk full error. */
if (unlikely(isRaisedDiskFull(result))) {
throw 1;
}
}
/* Create socket owner file. */
result = makeSocketOwnerFile(basePath);
if (unlikely(result != 0)) {
logger->printWarnMsgWithErrno("Could not create socket owner file.");
/* If raise disk full error. */
if (unlikely(isRaisedDiskFull(result))) {
throw 1;
}
}
} catch (...) {
; /* Failed collect files by disk full. */
}
if (likely(result == 0)) {
/*
* Set value mean failed to create archive,
* For if failed to get "archiveMutex" mutex.
*/
result = -1;
{
TMutexLocker locker(&archiveMutex);
/* Create archive file name. */
uniqArcName = createArchiveName(nowTime);
if (unlikely(uniqArcName == NULL)) {
/* Failure make archive uniq name. */
logger->printWarnMsg("Failure create archive name.");
} else {
/* Execute archive. */
arcMaker->setTarget(basePath);
result = arcMaker->doArchive(env, uniqArcName);
/* If failure create archive file. */
if (unlikely(result != 0)) {
/* Execute archive to use jniArchiver. */
jniArchiver->setTarget(basePath);
result = jniArchiver->doArchive(env, uniqArcName);
}
}
}
/* If failure create archive file yet. */
if (unlikely(result != 0)) {
logger->printWarnMsg("Failure create archive file.");
}
}
char *sendPath = uniqArcName;
bool flagDirectory = false;
/* If archive process is succeed. */
if (likely(result == 0)) {
/* Search last path separator. */
char *filePos = strrchr(uniqArcName, '/');
if (filePos != NULL) {
filePos++;
} else {
filePos = uniqArcName;
}
/* Copy archive file name without directory path. */
strncpy(archivePath, filePos, pathLen);
} else {
/* If failure execute command. */
/* Send working directory path to make up for archive file. */
sendPath = basePath;
flagDirectory = true;
}
/* Send log archive trap. */
if (unlikely(!sendLogArchiveTrap(cause, nowTime, sendPath, flagDirectory))) {
logger->printWarnMsg("Send SNMP log archive trap failed!");
}
/* If execute command is succeed. */
if (likely(result == 0)) {
/* Remove needless working directory. */
removeTempDir(basePath);
}
/* If allocated archive file path. */
if (likely(uniqArcName != NULL)) {
free(uniqArcName);
}
/* Cleanup. */
free(basePath);
return result;
}
/*!
* \brief Create file about JVM running environment.
* \param basePath [in] Path of directory put report file.
* \param cause [in] Invoke function cause.<br>
* E.g. Signal, ResourceExhausted, Interval.
* \param nowTime [in] Log collect time.
* \param description [in] Description of the event.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::makeEnvironFile(char *basePath, TInvokeCause cause,
TMSecTime nowTime, const char *description) {
int raisedErrNum = 0;
/* Invoke OS version function. */
struct utsname uInfo;
memset(&uInfo, 0, sizeof(struct utsname));
if (unlikely(uname(&uInfo) != 0)) {
logger->printWarnMsgWithErrno("Could not get kernel information.");
}
/* Invoke glibc information function. */
const char *glibcVersion = NULL;
const char *glibcRelease = NULL;
glibcVersion = gnu_get_libc_version();
glibcRelease = gnu_get_libc_release();
if (unlikely(glibcVersion == NULL || glibcRelease == NULL)) {
logger->printWarnMsgWithErrno("Could not get glibc version.");
}
/* Create filename. */
char *envInfoName = createFilename(basePath, "envInfo.txt");
/* If failure create file name. */
if (unlikely(envInfoName == NULL)) {
raisedErrNum = errno;
logger->printWarnMsgWithErrno(
"Could not allocate memory for envInfo.txt .");
return raisedErrNum;
}
/* Create envInfo.txt. */
int fd = open(envInfoName, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (unlikely(fd < 0)) {
raisedErrNum = errno;
logger->printWarnMsgWithErrno("Could not create envInfo.txt .");
free(envInfoName);
return raisedErrNum;
}
free(envInfoName);
/* Output enviroment information. */
try {
/* Output list. */
const struct {
const char *colName;
const char *valueFmt;
TMSecTime valueData;
const char *valuePtr;
bool isString;
} envColumnList[] = {
{"CollectionDate", "%lld", nowTime, NULL, false},
{"LogTrigger", "%d", (TMSecTime)logCauseToInt(cause), NULL, false},
{"Description", "%s", 0, description, true},
{"VmVersion", "%s", 0, jvmInfo->getVmVersion(), true},
{"OsRelease", "%s", 0, uInfo.release, true},
{"LibCVersion", "%s", 0, glibcVersion, true},
{"LibCRelease", "%s", 0, glibcRelease, true},
{"VmName", "%s", 0, jvmInfo->getVmName(), true},
{"ClassPath", "%s", 0, jvmInfo->getClassPath(), true},
{"EndorsedPath", "%s", 0, jvmInfo->getEndorsedPath(), true},
{"JavaVersion", "%s", 0, jvmInfo->getJavaVersion(), true},
{"JavaHome", "%s", 0, jvmInfo->getJavaHome(), true},
{"BootClassPath", "%s", 0, jvmInfo->getBootClassPath(), true},
{"VmArgs", "%s", 0, jvmInfo->getVmArgs(), true},
{"VmFlags", "%s", 0, jvmInfo->getVmFlags(), true},
{"JavaCmd", "%s", 0, jvmInfo->getJavaCommand(), true},
{"VmTime", JLONG_FORMAT_STR, (TMSecTime)jvmInfo->getTickTime(), NULL, false},
{NULL, NULL, 0, NULL, '\0'}};
char lineBuf[PATH_MAX + 1] = {0};
char EMPTY_LINE[] = "";
for (int i = 0; envColumnList[i].colName != NULL; i++) {
/* Write column and separator. */
snprintf(lineBuf, PATH_MAX, "%s" ENVIRON_VALUE_SEPARATOR,
envColumnList[i].colName);
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
/* Convert column value to string. */
char const *columnStr = NULL;
if (envColumnList[i].isString) {
columnStr = envColumnList[i].valuePtr;
if (unlikely(columnStr == NULL)) {
columnStr = EMPTY_LINE;
}
} else {
snprintf(lineBuf, PATH_MAX, envColumnList[i].valueFmt,
envColumnList[i].valueData);
columnStr = lineBuf;
}
/* Write column value. */
if (unlikely(write(fd, columnStr, strlen(columnStr)) < 0)) {
throw 1;
}
/* Write line separator. */
snprintf(lineBuf, PATH_MAX, "\n");
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
}
} catch (...) {
/* Stored error number to avoid overwriting by "close". */
raisedErrNum = errno;
logger->printWarnMsgWithErrno("Could not create environment file.");
}
/* Cleanup. */
if (unlikely(close(fd) < 0 && raisedErrNum == 0)) {
raisedErrNum = errno;
logger->printWarnMsgWithErrno("Could not create environment file.");
}
return raisedErrNum;
}
/*!
* \brief Dump thread and stack information to stream.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param fd [in] Output file descriptor.
* \param stackInfo [in] Stack frame of java thread.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::dumpThreadInformation(jvmtiEnv *jvmti, JNIEnv *env, int fd,
jvmtiStackInfo stackInfo) {
/* Get JVMTI capabilities for getting monitor information. */
jvmtiCapabilities capabilities;
jvmti->GetCapabilities(&capabilities);
bool hasCapability = capabilities.can_get_owned_monitor_stack_depth_info &&
capabilities.can_get_current_contended_monitor;
/* Get thread information. */
TJavaThreadInfo threadInfo = {0};
getThreadDetailInfo(jvmti, env, stackInfo.thread, &threadInfo);
char const EMPTY_STR[] = "";
char lineBuf[PATH_MAX + 1] = {0};
/* Output thread information. */
try {
/* Output thread name, thread type and priority. */
snprintf(lineBuf, PATH_MAX, "\"%s\"%s prio=%d\n",
((threadInfo.name != NULL) ? threadInfo.name : EMPTY_STR),
((threadInfo.isDaemon) ? " daemon" : EMPTY_STR),
threadInfo.priority);
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
/* Output thread state. */
snprintf(lineBuf, PATH_MAX, " java.lang.Thread.State: %s\n",
((threadInfo.state != NULL) ? threadInfo.state : EMPTY_STR));
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
} catch (...) {
int raisedErrNum = errno;
logger->printWarnMsgWithErrno("Could not create threaddump through JVMTI.");
free(threadInfo.name);
free(threadInfo.state);
return raisedErrNum;
}
free(threadInfo.name);
free(threadInfo.state);
/* Get thread monitor stack information. */
jint monitorCount = 0;
jvmtiMonitorStackDepthInfo *monitorInfo = NULL;
if (unlikely(
hasCapability &&
isError(jvmti, jvmti->GetOwnedMonitorStackDepthInfo(
stackInfo.thread, &monitorCount, &monitorInfo)))) {
/* Agnet is failed getting monitor info. */
monitorInfo = NULL;
}
int result = 0;
try {
/* Output thread flame trace. */
for (jint flameIdx = 0, flameSize = stackInfo.frame_count;
flameIdx < flameSize; flameIdx++) {
jvmtiFrameInfo frameInfo = stackInfo.frame_buffer[flameIdx];
TJavaStackMethodInfo methodInfo = {0};
/* Get method information. */
getMethodFrameInfo(jvmti, env, frameInfo, &methodInfo);
/* Output method class, name and source file location. */
char *srcLocation = NULL;
if (!methodInfo.isNative) {
char locationBuf[PATH_MAX + 1] = {0};
if (likely(methodInfo.lineNumber >= 0)) {
snprintf(locationBuf, PATH_MAX, "%d", methodInfo.lineNumber);
srcLocation = strdup(locationBuf);
}
snprintf(locationBuf, PATH_MAX, "%s:%s",
(methodInfo.sourceFile != NULL) ? methodInfo.sourceFile
: "UnknownFile",
(srcLocation != NULL) ? srcLocation : "UnknownLine");
free(srcLocation);
srcLocation = strdup(locationBuf);
}
snprintf(lineBuf, PATH_MAX, "\tat %s.%s(%s)\n",
(methodInfo.className != NULL) ? methodInfo.className
: "UnknownClass",
(methodInfo.methodName != NULL) ? methodInfo.methodName
: "UnknownMethod",
(srcLocation != NULL) ? srcLocation : "Native method");
/* Cleanup. */
free(methodInfo.className);
free(methodInfo.methodName);
free(methodInfo.sourceFile);
free(srcLocation);
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
/* If current stack frame. */
if (unlikely(hasCapability && flameIdx == 0)) {
jobject jMonitor = NULL;
jvmti->GetCurrentContendedMonitor(stackInfo.thread, &jMonitor);
/* If contented monitor is existing now. */
if (likely(jMonitor != NULL)) {
jclass monitorClass = NULL;
char *tempStr = NULL;
char ownerThreadName[1025] = "UNKNOWN";
char monitorClsName[1025] = "UNKNOWN";
/* Get monitor class. */
monitorClass = env->GetObjectClass(jMonitor);
if (likely(monitorClass != NULL)) {
/* Get class signature. */
jvmti->GetClassSignature(monitorClass, &tempStr, NULL);
if (likely(tempStr != NULL)) {
snprintf(monitorClsName, 1024, "%s", tempStr);
jvmti->Deallocate((unsigned char *)tempStr);
}
/* Cleanup. */
env->DeleteLocalRef(monitorClass);
}
/* Get monitor owner. */
jvmtiMonitorUsage monitorInfo = {0};
if (unlikely(!isError(jvmti, jvmti->GetObjectMonitorUsage(
jMonitor, &monitorInfo)))) {
/* Get owner thread information. */
getThreadDetailInfo(jvmti, env, monitorInfo.owner, &threadInfo);
if (likely(threadInfo.name != NULL)) {
strncpy(ownerThreadName, threadInfo.name, 1024);
}
/* Cleanup. */
free(threadInfo.name);
free(threadInfo.state);
}
env->DeleteLocalRef(jMonitor);
/* Output contented monitor information. */
snprintf(lineBuf, PATH_MAX, "\t- waiting to lock <owner:%s> (a %s)\n",
ownerThreadName, monitorClsName);
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
}
}
if (likely(monitorInfo != NULL)) {
/* Search monitor. */
jint monitorIdx = 0;
for (; monitorIdx < monitorCount; monitorIdx++) {
if (monitorInfo[monitorIdx].stack_depth == flameIdx) {
break;
}
}
/* If locked monitor is found. */
if (likely(monitorIdx < monitorCount)) {
jobject jMonitor = monitorInfo[monitorIdx].monitor;
jclass monitorClass = NULL;
char *tempStr = NULL;
char monitorClsName[1025] = "UNKNOWN";
/* Get object class. */
monitorClass = env->GetObjectClass(jMonitor);
if (likely(monitorClass != NULL)) {
/* Get class signature. */
jvmti->GetClassSignature(monitorClass, &tempStr, NULL);
if (likely(tempStr != NULL)) {
snprintf(monitorClsName, 1024, "%s", tempStr);
jvmti->Deallocate((unsigned char *)tempStr);
}
env->DeleteLocalRef(monitorClass);
}
/* Output owned monitor information. */
snprintf(lineBuf, PATH_MAX, "\t- locked (a %s)\n", monitorClsName);
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
}
}
}
/* Output separator for each thread. */
snprintf(lineBuf, PATH_MAX, "\n");
if (unlikely(write(fd, lineBuf, strlen(lineBuf)) < 0)) {
throw 1;
}
} catch (...) {
result = errno;
/* Raise write error. */
logger->printWarnMsgWithErrno("Could not create threaddump through JVMTI.");
}
/* Cleanup. */
if (likely(monitorInfo != NULL)) {
for (jint monitorIdx = 0; monitorIdx < monitorCount; monitorIdx++) {
env->DeleteLocalRef(monitorInfo[monitorIdx].monitor);
}
jvmti->Deallocate((unsigned char *)monitorInfo);
}
return result;
}
/*!
* \brief Create thread dump with JVMTI.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param filename [in] Path of thread dump file.
* \param nowTime [in] Log collect time.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::makeJvmtiThreadDump(jvmtiEnv *jvmti, JNIEnv *env,
char *filename, TMSecTime nowTime) {
int result = 0;
/* Open thread dump file. */
int fd = open(filename, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
/* If failure open file. */
if (unlikely(fd < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not create %s", filename);
return result;
}
const jint MAX_STACK_COUNT = 100;
jvmtiStackInfo *stackList = NULL;
jint threadCount = 0;
/* If failure get all stack traces. */
if (unlikely(
isError(jvmti, jvmti->GetAllStackTraces(MAX_STACK_COUNT, &stackList,
&threadCount)))) {
logger->printWarnMsg("Couldn't get thread stack trace.");
close(fd);
return -1;
}
/* Output stack trace. */
for (jint i = 0; i < threadCount; i++) {
jvmtiStackInfo stackInfo = stackList[i];
/* Output thread information. */
result = dumpThreadInformation(jvmti, env, fd, stackInfo);
if (unlikely(result != 0)) {
break;
}
}
/* Cleanup. */
if (unlikely(close(fd) < 0 && result == 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not create threaddump through JVMTI.");
}
jvmti->Deallocate((unsigned char *)stackList);
return result;
}
/*!
* \brief Create thread dump file.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param basePath [in] Path of directory put report file.
* \param cause [in] Invoke function cause.<br>
* E.g. Signal, ResourceExhausted, Interval.
* \param nowTime [in] Log collect time.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::makeThreadDumpFile(jvmtiEnv *jvmti, JNIEnv *env,
char *basePath, TInvokeCause cause,
TMSecTime nowTime) {
/* Dump thread information. */
int result = -1;
/* Create dump filename. */
char *dumpName = createFilename((char *)basePath, "threaddump.txt");
if (unlikely(dumpName == NULL)) {
logger->printWarnMsg("Couldn't allocate thread dump file path.");
} else {
if (unlikely(cause == ThreadExhausted && !jvmCmd->isConnectable())) {
/*
* JVM is aborted when reserve signal SIGQUIT,
* if JVM can't make new thread (e.g. RLIMIT_NPROC).
* So we need avoid to send SIGQUIT signal.
*/
;
} else {
/* Create thread dump file. */
result = jvmCmd->exec("threaddump", dumpName);
}
/* If disk isn't full. */
if (unlikely(!isRaisedDiskFull(result))) {
/* If need original thread dump. */
if (unlikely((result != 0) && (jvmti != NULL))) {
result = makeJvmtiThreadDump(jvmti, env, dumpName, nowTime);
}
}
free(dumpName);
}
return result;
}
/*!
* \brief Getting java process information.
* \param systime [out] System used cpu time in java process.
* \param usrtime [out] User and java used cpu time in java process.
* \param vmsize [out] Virtual memory size of java process.
* \param rssize [out] Memory size of java process on main memory.
* \return Prosess is succeed or failure.
*/
bool TLogManager::getProcInfo(TLargeUInt *systime, TLargeUInt *usrtime,
TLargeUInt *vmsize, TLargeUInt *rssize) {
/* Get page size. */
long pageSize = 0;
/* If failure get page size from sysconf. */
if (unlikely(systemPageSize <= 0)) {
/* Assume page size is 4 KiByte. */
systemPageSize = 1 << 12;
logger->printWarnMsg("System page size not found.");
}
/* Use sysconf return value. */
pageSize = systemPageSize;
/* Initialize. */
*usrtime = -1;
*systime = -1;
*vmsize = -1;
*rssize = -1;
/* Make path of process status file. */
char path[256] = {0};
snprintf(path, 255, "/proc/%d/stat", getpid());
/* Open process status file. */
FILE *proc = fopen(path, "r");
/* If failure open process status file. */
if (unlikely(proc == NULL)) {
logger->printWarnMsgWithErrno("Could not open process status.");
return false;
}
char *line = NULL;
size_t len = 0;
/* Get line from process status file. */
if (likely(getline(&line, &len, proc) > 0)) {
/* Parse line. */
if (likely(
sscanf(
line,
"%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u"
" %*u %*u %*u %llu %llu %*d %*d %*d %*d %*d %*d %*u %llu %llu",
usrtime, systime, vmsize, rssize) == 4)) {
/* Convert real page count to real page size. */
*rssize = *rssize * pageSize;
} else {
/* Kernel may be old or customized. */
logger->printWarnMsg("Process data has shortage.");
}
} else {
logger->printWarnMsg("Couldn't read process status.");
}
/* Cleanup. */
if (likely(line != NULL)) {
free(line);
}
fclose(proc);
return true;
}
/*!
* \brief Getting machine cpu times.
* \param times [out] Machine cpu times information.
* \return Prosess is succeed or failure.
*/
bool TLogManager::getSysTimes(TMachineTimes *times) {
/* Initialize. */
memset(times, 0, sizeof(TMachineTimes));
/* Open machine status file. */
FILE *proc = fopen("/proc/stat", "r");
/* If failure open machine status file. */
if (unlikely(proc == NULL)) {
logger->printWarnMsgWithErrno("Could not open /proc/stat");
return false;
}
char *line = NULL;
size_t len = 0;
bool flagFound = false;
/* Loop for find "cpu" line. */
while (likely(getline(&line, &len, proc) > 0)) {
/* Check line. */
if (unlikely(strncmp(line, "cpu ", 4) != 0)) {
/* This line is non-target. */
continue;
}
/* Parse cpu time information. */
if (unlikely(sscanf(line,
"cpu %llu %llu %llu %llu %llu %llu %llu %llu %llu",
×->usrTime, ×->lowUsrTime, ×->sysTime,
×->idleTime, ×->iowaitTime,
×->sortIrqTime, ×->irqTime, ×->stealTime,
×->guestTime) != 9)) {
/* Maybe the kernel is old version. */
logger->printWarnMsg("CPU status data has shortage.");
}
flagFound = true;
break;
}
/* If not found cpu information. */
if (unlikely(!flagFound)) {
/* Maybe the kernel is modified. */
logger->printWarnMsg("Not found cpu status data.");
}
/* Cleanup. */
if (likely(line != NULL)) {
free(line);
}
fclose(proc);
return flagFound;
}
/*!
* \brief Send log archive trap.
* \param cause [in] Invoke function cause.<br>
* E.g. Signal, ResourceExhausted, Interval.
* \param nowTime [in] Log collect time.
* \param path [in] Archive file or directory path.
* \param isDirectory [in] Param "path" is directory.
* \return Value is true, if process is succeed.
*/
bool TLogManager::sendLogArchiveTrap(TInvokeCause cause, TMSecTime nowTime,
char *path, bool isDirectory) {
/* Return value. */
bool result = true;
/* Get full path. */
char realSendPath[PATH_MAX] = {0};
if (unlikely(realpath(path, realSendPath) == NULL)) {
logger->printWarnMsgWithErrno("Could not get real path of archive file");
return false;
}
/* If path is directory, then append "/" to path. */
if (isDirectory) {
size_t pathSize = strlen(realSendPath);
pathSize = (pathSize >= PATH_MAX) ? PATH_MAX - 1 : pathSize;
realSendPath[pathSize] = '/';
}
/* Output archive file path. */
logger->printInfoMsg("Collecting log has been completed: %s", realSendPath);
if (conf->SnmpSend()->get()) {
/* Trap OID. */
char trapOID[50] = OID_LOGARCHIVE;
oid OID_LOG_PATH[] = {SNMP_OID_LOGARCHIVE, 1};
oid OID_TROUBLE_DATE[] = {SNMP_OID_LOGARCHIVE, 2};
/* Temporary buffer. */
char buff[256] = {0};
try {
/* Send resource trap. */
TTrapSender sender;
/* Setting sysUpTime */
sender.setSysUpTime();
/* Setting trapOID. */
sender.setTrapOID(trapOID);
/* Set log archive path. */
sender.addValue(OID_LOG_PATH, OID_LENGTH(OID_LOG_PATH), realSendPath,
SNMP_VAR_TYPE_STRING);
/* Set date which JVM resource exhausted. */
switch (cause) {
case ResourceExhausted:
case ThreadExhausted:
case OccurredDeadlock:
/* Collect archive by resource or deadlock. */
snprintf(buff, 255, "%llu", nowTime);
break;
default:
/* Collect archive by signal. */
snprintf(buff, 255, "%llu", (TMSecTime)0LL);
}
sender.addValue(OID_TROUBLE_DATE, OID_LENGTH(OID_TROUBLE_DATE), buff,
SNMP_VAR_TYPE_COUNTER64);
/* Send trap. */
result = (sender.sendTrap() == SNMP_PROC_SUCCESS);
if (unlikely(!result)) {
/* Clean up. */
sender.clearValues();
}
} catch (...) {
result = false;
}
}
return result;
}
/*!
* \brief Collect files about JVM enviroment.
* \param basePath [in] Temporary working directory.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::copyInfoFiles(char const *basePath) {
int result = 0;
/* Copy distribution file list. */
const char distFileList[][255] = {/* Distribution release. */
"/etc/redhat-release",
/* For other distribution. */
"/etc/sun-release",
"/etc/mandrake-release",
"/etc/SuSE-release",
"/etc/turbolinux-release",
"/etc/gentoo-release",
"/etc/debian_version",
"/etc/ltib-release",
"/etc/angstrom-version",
"/etc/fedora-release",
"/etc/vine-release",
"/etc/issue",
/* End flag. */
{0}};
bool flagCopyedDistFile = false;
/* Copy distribution file. */
for (int i = 0; strlen(distFileList[i]) > 0; i++) {
result = copyFile(distFileList[i], basePath);
if ((result == 0) || isRaisedDiskFull(result)) {
flagCopyedDistFile = (result == 0);
break;
}
}
/* If failure copy distribution file. */
if (unlikely(!flagCopyedDistFile)) {
logger->printWarnMsgWithErrno("Could not copy distribution release file.");
}
/* If disk is full. */
if (unlikely(isRaisedDiskFull(result))) {
return result;
}
/* Copy file list. */
const char copyFileList[][255] = {/* Process information. */
"/proc/self/smaps",
"/proc/self/limits",
"/proc/self/cmdline",
"/proc/self/status",
/* Netstat infomation. */
"/proc/net/tcp",
"/proc/net/tcp6",
"/proc/net/udp",
"/proc/net/udp6",
/* End flag. */
{0}};
/* Copy files in list. */
for (int i = 0; strlen(copyFileList[i]) > 0; i++) {
/* Copy file. */
result = copyFile(copyFileList[i], basePath);
if (unlikely(result != 0)) {
logger->printWarnMsg("Could not copy file: %s", copyFileList[i]);
/* If disk is full. */
if (unlikely(isRaisedDiskFull(result))) {
return result;
}
}
}
/* Collect Syslog or Systemd-Journald */
/*
* Try to copy syslog at first, because journal daemon will forward all
* received
* log messages to a traditional syslog by default.
*/
result = copyFile("/var/log/messages", basePath);
if (unlikely(result != 0)) {
errno = result;
logger->printWarnMsgWithErrno("Could not copy /var/log/messages");
/* If disk is full. */
if (unlikely(isRaisedDiskFull(result))) {
return result;
}
}
/* Collect systemd-journald instead of syslog when failed to copy syslog, */
if (result != 0) {
/*
* Select vfork() to run journalctl in a separate process. Unlikely
* system(),
* this function does not block SIGINT, et al. Unlikely fork(), this
* function
* does not copy but shares all memory with its parent, including the stack.
*/
pid_t child = vfork();
if (child == 0) {
/* Child process */
/* logfile name shows what command is used to output it.*/
char logfile[PATH_MAX];
sprintf(logfile, "%s%s", basePath,
"/journalctl_-q_--all_--this-boot_--no-pager_-o_verbose.log");
/* Redirect child process' stdout/stderr to logfile */
int fd = open(logfile, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (dup2(fd, 1) < 0) {
close(fd);
_exit(errno);
}
if (dup2(fd, 2) < 0) {
close(fd);
_exit(errno);
}
close(fd);
/* Use execve() for journalctl to prevent command injection */
const char *argv[] = {"journalctl", "-q", "--all", "--this-boot",
"--no-pager", "-o", "verbose", NULL};
extern char **environ;
execve("/bin/journalctl", (char *const *)argv, environ);
/* if execve returns, it has failed */
_exit(errno);
} else if (child < 0) {
/* vfork failed */
result = errno;
logger->printWarnMsgWithErrno(
"Could not collect systemd-journald log by vfork().");
} else {
/* Parent process */
int status;
if (waitpid(child, &status, 0) < 0) {
/* The child process failed. */
result = errno;
logger->printWarnMsgWithErrno(
"Could not collect systemd-journald log by process error.");
/* If disk is full. */
if (unlikely(isRaisedDiskFull(result))) {
return result;
}
}
if (WIFEXITED(status)) {
/* The child exited normally, get the returns as result. */
result = WEXITSTATUS(status);
if (result != 0) {
logger->printWarnMsg("Could not collect systemd-journald log.");
}
} else {
/* The child exited with a signal or unknown exit code. */
logger->printWarnMsg(
"Could not collect systemd-journald log by signal or unknown exit "
"code.");
}
}
}
/* Copy file descriptors, i.e. stdout and stderr, as avoid double work. */
const int fdNum = 2;
const char streamList[fdNum][255] = {/* Standard streams */
"/proc/self/fd/1", "/proc/self/fd/2",
};
const char fdFile[fdNum][10] = {"fd1", "fd2"};
char fdPath[fdNum][PATH_MAX];
struct stat fdStat[fdNum];
for (int i = 0; i < fdNum; i++) {
realpath(streamList[i], fdPath[i]);
if (unlikely(stat(fdPath[i], &fdStat[i]) != 0)) {
/* Failure get file information. */
result = errno;
logger->printWarnMsgWithErrno("Could not get file information (stat).");
} else if (i == 1 && result == 0 && fdStat[0].st_ino == fdStat[1].st_ino) {
/* If stdout and stderr are redirected to same file, no need to copy the
* file again. */
break;
} else {
result = copyFile(streamList[i], basePath, fdFile[i]);
}
/* If catch a failure during the copy process, show warn messages. */
if (unlikely(result != 0)) {
errno = result;
logger->printWarnMsgWithErrno("Could not copy file: %s", streamList[i]);
/* If disk is full. */
if (unlikely(isRaisedDiskFull(result))) {
return result;
}
}
}
return result;
}
/*!
* \brief Copy GC log file.
* \param basePath [in] Path of temporary directory.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::copyGCLogFile(char const *basePath) {
char *aGCLogFile = (*gcLogFilename);
/* If GC log filename isn't specified. */
if (unlikely(aGCLogFile == NULL)) {
return 0;
}
/* Copy file. */
return copyFile(aGCLogFile, basePath);
}
/*!
* \brief Create file about using socket by JVM.
* \param basePath [in] Path of directory put report file.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int TLogManager::makeSocketOwnerFile(char const *basePath) {
int result = 0;
/* Create filename. */
char *sockOwnName = createFilename(basePath, "sockowner");
/* If failure create file name. */
if (unlikely(sockOwnName == NULL)) {
result = errno;
logger->printWarnMsg("Couldn't allocate filename.");
return result;
}
/* Create sockowner. */
int fd = open(sockOwnName, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
free(sockOwnName);
if (unlikely(fd < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not open socket owner file.");
return result;
}
/* Open directory. */
DIR *dir = opendir("/proc/self/fd");
/* If failure open directory. */
if (unlikely(dir == NULL)) {
result = errno;
logger->printWarnMsgWithErrno("Could not open directory: /proc/self/fd");
close(fd);
return result;
}
/* Read file in directory. */
struct dirent *entry = NULL;
while ((entry = readdir(dir)) != NULL) {
/* Check file name. */
if (strcmp(entry->d_name, "..") == 0 || strcmp(entry->d_name, ".") == 0) {
continue;
}
/* Get maybe socket file full path. */
char *socketPath = createFilename("/proc/self/fd", entry->d_name);
if (unlikely(socketPath == NULL)) {
result = errno;
logger->printWarnMsg("Failure allocate working memory.");
break;
}
/* Get file information. */
struct stat st = {0};
if (unlikely(stat(socketPath, &st) != 0)) {
free(socketPath);
continue;
}
free(socketPath);
/* If this file is socket file. */
if ((st.st_mode & S_IFMT) == S_IFSOCK) {
/* Output i-node number of a socket file. */
char buf[256] = {0};
snprintf(buf, 255, INODENUM_FORMAT_STR "\n", st.st_ino);
if (unlikely(write(fd, buf, strlen(buf)) < 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not write to socket owner.");
break;
}
}
}
/* If failure in read directory. */
if (unlikely(close(fd) != 0 && result == 0)) {
result = errno;
logger->printWarnMsgWithErrno("Could not close socket owner.");
}
/* Cleanup. */
closedir(dir);
return result;
}
/*!
* \brief Create archive file path.
* \param nowTime [in] Log collect time.
* \return Return archive file name, if process is succeed.<br>
* Don't forget deallocate memory.<br>
* Process is failure, if value is null.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
char *TLogManager::createArchiveName(TMSecTime nowTime) {
time_t nowTimeSec = 0;
struct tm time_struct = {0};
char time_str[20] = {0};
char arcName[PATH_MAX] = {0};
char extPart[PATH_MAX] = {0};
char namePart[PATH_MAX] = {0};
/* Search extension. */
char *archiveFileName = conf->ArchiveFile()->get();
char *extPos = strrchr(archiveFileName, '.');
if (likely(extPos != NULL)) {
/* Path and extension store each other. */
strncpy(extPart, extPos, PATH_MAX);
strncpy(namePart, archiveFileName, (extPos - archiveFileName));
} else {
/* Not found extension in path. */
strncpy(namePart, archiveFileName, PATH_MAX);
}
/* Get now datetime and convert to string. */
nowTimeSec = (time_t)(nowTime / 1000);
localtime_r((const time_t *)&nowTimeSec, &time_struct);
strftime(time_str, 20, "%y%m%d%H%M%S", &time_struct);
/* Create file name. */
int ret = snprintf(arcName, PATH_MAX, "%s%s%s", namePart, time_str, extPart);
if (ret >= PATH_MAX) {
logger->printCritMsg("Archive name is too long: %s", arcName);
return NULL;
}
/* Create unique file name. */
return createUniquePath(arcName, false);
}
#pragma GCC diagnostic pop
| 46,525
|
C++
|
.cpp
| 1,282
| 29.609984
| 87
| 0.60304
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,025
|
logMain.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/logMain.cpp
|
/*!
* \file logmain.cpp
* \brief This file is used common logging process.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <signal.h>
#include <sched.h>
#ifdef HAVE_ATOMIC
#include <atomic>
#else
#include <cstdatomic>
#endif
#include "globals.hpp"
#include "elapsedTimer.hpp"
#include "util.hpp"
#include "libmain.hpp"
#include "callbackRegister.hpp"
#include "logMain.hpp"
/*!
* \brief Manager of log information.
*/
TLogManager *logManager = NULL;
/*!
* \brief Timer for interval collect log.
*/
TTimer *logTimer = NULL;
/*!
* \brief Signal manager to collect normal log by signal.
*/
TSignalManager *logSignalMngr = NULL;
/*!
* \brief Signal manager to collect all log by signal.
*/
TSignalManager *logAllSignalMngr = NULL;
/*!
* \brief Mutex to avoid conflict in OnResourceExhausted.<br>
* <br>
* This mutex used in below process.<br>
* - OnResourceExhausted @ logMain.cpp<br>
* To read and write to flag mean already collect log
* on resource exhasuted.<br>
*/
pthread_mutex_t errMutex = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
/*!
* \brief Flag of collect normal log for signal.
*/
volatile sig_atomic_t flagLogSignal;
/*!
* \brief Flag of collect all log for signal.
*/
volatile sig_atomic_t flagAllLogSignal;
/*!
* \brief processing flag
*/
static std::atomic_int processing(0);
/*!
* \brief Take log information.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Cause of taking a snapshot.<br>
* e.g. ResourceExhausted, Signal or Interval.
* \param nowTime [in] Mili-second elapsed from 1970/1/1 0:00:00.<br>
* This value express time of call log function.
* \param description [in] Description of the event.
* \return Value is true, if process is succeed.
*/
inline bool TakeLogInfo(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause,
TMSecTime nowTime, const char *description) {
/* Count working time. */
static const char *label = "Take LogInfo";
TElapsedTimer elapsedTime(label);
/* Collect log. */
return (logManager->collectLog(jvmti, env, cause, nowTime, description) == 0);
}
/*!
* \brief Interval collect log.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Cause of taking a snapshot.<br>
* This value is always Interval.
*/
void intervalLogProc(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause) {
TProcessMark mark(processing);
/* Call collect log by interval. */
if (unlikely(!TakeLogInfo(jvmti, env, cause,
(TMSecTime)getNowTimeSec(), ""))) {
logger->printWarnMsg("Failure interval collect log.");
}
}
/*!
* \brief Handle signal express user wanna collect normal log.
* \param signo [in] Number of received signal.
* \param siginfo [in] Information of received signal.
* \param data [in] Data of received signal.
*/
void normalLogProc(int signo, siginfo_t *siginfo, void *data) {
/* Enable flag. */
flagLogSignal = 1;
NOTIFY_CATCH_SIGNAL;
}
/*!
* \brief Handle signal express user wanna collect all log.
* \param signo [in] Number of received signal.
* \param siginfo [in] Information of received signal.
* \param data [in] Data of received signal.
*/
void anotherLogProc(int signo, siginfo_t *siginfo, void *data) {
/* Enable flag. */
flagAllLogSignal = 1;
NOTIFY_CATCH_SIGNAL;
}
/*!
* \brief Interval watching for log signal.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void intervalSigProcForLog(jvmtiEnv *jvmti, JNIEnv *env) {
TProcessMark mark(processing);
/* If catch normal log signal. */
if (unlikely(flagLogSignal != 0)) {
TMSecTime nowTime = (TMSecTime)getNowTimeSec();
flagLogSignal = 0;
if (unlikely(!TakeLogInfo(jvmti, env, Signal, nowTime, ""))) {
logger->printWarnMsg("Failure collect log by normal log signal.");
}
}
/* If catch all log signal. */
if (unlikely(flagAllLogSignal != 0)) {
TMSecTime nowTime = (TMSecTime)getNowTimeSec();
flagAllLogSignal = 0;
if (unlikely(!TakeLogInfo(jvmti, env, AnotherSignal, nowTime, ""))) {
logger->printWarnMsg("Failure collect log by all log signal.");
}
}
}
/*!
* \brief JVM resource exhausted event.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param flags [in] Resource information bit flag.
* \param reserved [in] Reserved variable.
* \param description [in] Description about resource exhausted.
*/
void JNICALL OnResourceExhausted(jvmtiEnv *jvmti, JNIEnv *env, jint flags,
const void *reserved,
const char *description) {
TProcessMark mark(processing);
/* Raise alert. */
logger->printCritMsg("ALERT(RESOURCE): resource was exhausted. info:\"%s\"",
description);
/* Get now date and time. */
TMSecTime nowTime = (TMSecTime)getNowTimeSec();
if (conf->SnmpSend()->get()) {
/* Trap OID. */
char trapOID[50] = OID_RESALERT;
oid OID_RES_FLAG[] = {SNMP_OID_RESALERT, 1};
oid OID_RES_DESC[] = {SNMP_OID_RESALERT, 2};
char buff[256] = {0};
try {
/* Send resource trap. */
TTrapSender sender;
/* Setting sysUpTime */
sender.setSysUpTime();
/* Setting trapOID. */
sender.setTrapOID(trapOID);
/* Set resource inforomation flags. */
snprintf(buff, 255, "%d", flags);
sender.addValue(OID_RES_FLAG, OID_LENGTH(OID_RES_FLAG), buff,
SNMP_VAR_TYPE_INTEGER);
/* Set resource decsription. */
strncpy(buff, description, 255);
sender.addValue(OID_RES_DESC, OID_LENGTH(OID_RES_DESC), buff,
SNMP_VAR_TYPE_STRING);
/* Send trap. */
if (unlikely(sender.sendTrap() != SNMP_PROC_SUCCESS)) {
/* Ouput message and clean up. */
sender.clearValues();
throw 1;
}
} catch (...) {
logger->printWarnMsg("Send SNMP resource exhausted trap failed!");
}
}
bool isCollectLog = true;
{
TMutexLocker locker(&errMutex);
/* If collected already and collect first only. */
if (conf->FirstCollect()->get() && conf->isFirstCollected()) {
/* Skip collect log. */
logger->printWarnMsg("Skip collect all log on JVM resource exhausted.");
isCollectLog = false;
}
conf->setFirstCollected(true);
}
if (isCollectLog) {
/* Setting collect log cause. */
TInvokeCause cause = ResourceExhausted;
if (unlikely((flags & JVMTI_RESOURCE_EXHAUSTED_THREADS) > 0)) {
cause = ThreadExhausted;
}
/* Collect log. */
if (unlikely(!TakeLogInfo(jvmti, env, cause, nowTime, description))) {
logger->printWarnMsg("Failure collect log on resource exhausted.");
}
}
/* If enable to abort JVM by force on resource exhausted. */
if (unlikely(conf->KillOnError()->get())) {
forcedAbortJVM(jvmti, env, "resource exhausted");
}
}
/*!
* \brief Setting enable of JVMTI and extension events for log function.
* \param jvmti [in] JVMTI environment object.
* \param enable [in] Event notification is enable.
* \return Setting process result.
*/
jint setEventEnableForLog(jvmtiEnv *jvmti, bool enable) {
jvmtiEventMode mode = enable ? JVMTI_ENABLE : JVMTI_DISABLE;
/* If collect log when JVM's resource exhausted. */
if (conf->TriggerOnLogError()->get()) {
/* Enable resource exhusted event. */
TResourceExhaustedCallback::switchEventNotification(jvmti, mode);
}
return SUCCESS;
}
/*!
* \brief Setting enable of agent each threads for log function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param enable [in] Event notification is enable.
*/
void setThreadEnableForLog(jvmtiEnv *jvmti, JNIEnv *env, bool enable) {
/* Start or suspend HeapStats agent threads. */
try {
/* Switch interval log timer. */
if (conf->LogInterval()->get() > 0) {
if (enable) {
logTimer->start(jvmti, env, conf->LogInterval()->get() * 1000);
} else {
logTimer->stop();
}
}
/* Reset signal flag even if non-processed signal is exist. */
flagLogSignal = 0;
flagAllLogSignal = 0;
} catch (const char *errMsg) {
logger->printWarnMsg(errMsg);
}
}
/*!
* \brief JVM initialization event for log function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMInitForLog(jvmtiEnv *jvmti, JNIEnv *env) {
/* If failure jni archiver initialization. */
if (unlikely(!TJniZipArchiver::globalInitialize(env))) {
logger->printWarnMsg("Failure jni archiver initialization.");
}
/* Create instance for log function. */
try {
logManager = new TLogManager(env, jvmInfo);
} catch (const char *errMsg) {
logger->printWarnMsg(errMsg);
conf->TriggerOnLogSignal()->set(false);
conf->TriggerOnLogLock()->set(false);
conf->TriggerOnLogError()->set(false);
conf->LogInterval()->set(0);
} catch (...) {
logger->printWarnMsg("AgentThread start failed!");
conf->TriggerOnLogSignal()->set(false);
conf->TriggerOnLogLock()->set(false);
conf->TriggerOnLogError()->set(false);
conf->LogInterval()->set(0);
}
/* Initialize signal flag. */
flagLogSignal = 0;
flagAllLogSignal = 0;
/* Signal handler setup */
if (conf->LogSignalNormal()->get() != NULL) {
try {
logSignalMngr = new TSignalManager(conf->LogSignalNormal()->get());
if (!logSignalMngr->addHandler(&normalLogProc)) {
logger->printWarnMsg("Log normal signal handler setup is failed.");
conf->LogSignalNormal()->set(NULL);
}
} catch (const char *errMsg) {
logger->printWarnMsg(errMsg);
conf->LogSignalNormal()->set(NULL);
} catch (...) {
logger->printWarnMsg("Log normal signal handler setup is failed.");
conf->LogSignalNormal()->set(NULL);
}
}
if (conf->LogSignalAll()->get() != NULL) {
try {
logAllSignalMngr = new TSignalManager(conf->LogSignalAll()->get());
if (!logAllSignalMngr->addHandler(&anotherLogProc)) {
logger->printWarnMsg("Log all signal handler setup is failed.");
conf->LogSignalAll()->set(NULL);
}
} catch (const char *errMsg) {
logger->printWarnMsg(errMsg);
conf->LogSignalAll()->set(NULL);
} catch (...) {
logger->printWarnMsg("Log all signal handler setup is failed.");
conf->LogSignalAll()->set(NULL);
}
}
}
/*!
* \brief JVM finalization event for log function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMDeathForLog(jvmtiEnv *jvmti, JNIEnv *env) {
if (logSignalMngr != NULL) {
delete logSignalMngr;
logSignalMngr = NULL;
}
if (logAllSignalMngr != NULL) {
delete logAllSignalMngr;
logAllSignalMngr = NULL;
}
/*
* ResourceExhausted, MonitorContendedEnter for Deadlock JVMTI event,
* all callee of TakeLogInfo() will not be started at this point.
* So we wait to finish all existed tasks.
*/
while (processing > 0) {
sched_yield();
}
}
/*!
* \brief Agent initialization for log function.
* \return Initialize process result.
*/
jint onAgentInitForLog(void) {
/* Create thread instances that controlled log trigger. */
try {
logTimer = new TTimer(&intervalLogProc, "HeapStats Log Timer");
} catch (const char *errMsg) {
logger->printCritMsg(errMsg);
return AGENT_THREAD_INITIALIZE_FAILED;
} catch (...) {
logger->printCritMsg("AgentThread initialize failed!");
return AGENT_THREAD_INITIALIZE_FAILED;
}
return SUCCESS;
}
/*!
* \brief Agent finalization for log function.
* \param env [in] JNI environment object.
*/
void onAgentFinalForLog(JNIEnv *env) {
/* Destroy signal manager objects. */
delete logSignalMngr;
logSignalMngr = NULL;
delete logAllSignalMngr;
logAllSignalMngr = NULL;
/* Destroy timer object. */
delete logTimer;
logTimer = NULL;
/* Destroy log manager. */
delete logManager;
logManager = NULL;
if (likely(env != NULL)) {
/* Jni archiver finalization. */
TJniZipArchiver::globalFinalize(env);
}
}
| 13,081
|
C++
|
.cpp
| 386
| 29.981865
| 82
| 0.678636
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,026
|
jvmSockCmd.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/jvmSockCmd.cpp
|
/*!
* \file jvmSockCmd.cpp
* \brief This file is used by thread dump.
* Copyright (C) 2011-2018 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <fcntl.h>
#include <signal.h>
#include "globals.hpp"
#include "util.hpp"
#include "jvmSockCmd.hpp"
/*!
* \brief JVM socket command protocol version.
*/
const char JVM_CMD_VERSION[2] = "1";
/*!
* \brief TJVMSockCmd constructor.
* \param temporaryPath [in] Temporary path of JVM.
*/
TJVMSockCmd::TJVMSockCmd(char const* temporaryPath) {
/* Initialize fields. */
memset(socketPath, 0, sizeof(socketPath));
memset(tempPath, 0, sizeof(tempPath));
/* Copy. */
if (likely(temporaryPath != NULL)) {
strncpy(tempPath, temporaryPath, sizeof(tempPath) - 1);
} else {
/* Set default temporary path. */
strcpy(tempPath, "/tmp");
}
/* Create socket file to JVM. */
createJvmSock();
}
/*!
* \brief TJVMSockCmd destructor.
*/
TJVMSockCmd::~TJVMSockCmd(void) { /* None. */ }
/*!
* \brief Execute command without params, and save response.
* \param cmd [in] Execute command string.
* \param filename [in] Output file path.
* \return Response code of execute commad line.<br>
* Execute command is succeed, if value is 0.<br>
* Value is error code, if failure execute command.<br>
* Even so the file was written response data, if failure.
*/
int TJVMSockCmd::exec(char const* cmd, char const* filename) {
/* Empty paramters. */
const TJVMSockCmdArgs conf = {{0}, {0}, {0}};
return execute(cmd, conf, filename);
}
/*!
* \brief Execute command, and save response.
* \param cmd [in] Execute command string.
* \param conf [in] Execute command arguments.
* \param filename [in] Output file path.
* \return Response code of execute commad line.<br>
* Execute command is succeed, if value is 0.<br>
* Value is error code, if failure execute command.<br>
* Even so the file was written response data, if failure.
*/
int TJVMSockCmd::execute(char const* cmd, const TJVMSockCmdArgs conf,
char const* filename) {
/* If don't open socket yet. */
if (unlikely(!isConnectable())) {
/* If failure open JVM socket. */
if (unlikely(!createJvmSock())) {
logger->printWarnMsg("Failure open socket.");
return -1;
}
}
/* Open socket. */
int socketFD = openJvmSock(socketPath);
/* Socket isn't open yet. */
if (unlikely(socketFD < 0)) {
logger->printWarnMsg("Socket isn't open yet.");
return -1;
}
int returnCode = 0;
/* Create response file. */
int fd = open(filename, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (unlikely(fd < 0)) {
returnCode = errno;
logger->printWarnMsgWithErrno("Could not create threaddump file");
close(socketFD);
return returnCode;
}
/*
* About JVM socket command
* format:
* ~version~\0~command~\0~param1~\0~param2~\0~param3~\0
* version:
* Always version is "1".
* command:
* "threaddump" Dump information of threads on JVM.
* "inspectheap" Seems to like "PrintClassHistogram".
* "datadump" Seems to like when press CTRL and \ key.
* "heapdump" Dump heap to file like "jhat".
* etc..
* param1~3:
* paramter is fixed three param.
* If no need paramter , but should write '\0'.
* return:
* '0' Succeed in command and return result data.
* other Raised error and return error messages.
*/
/* Result code variable. */
char result = '\0';
/* Wait socket response. */
const int WAIT_LIMIT = 1000;
int waitCount = 0;
try {
/* Write command protocol version. */
if (unlikely(write(socketFD, JVM_CMD_VERSION, strlen(JVM_CMD_VERSION) + 1) <
0)) {
returnCode = errno;
logger->printWarnMsgWithErrno("Could not send threaddump command to JVM");
throw 1;
}
/* Write command string. */
if (unlikely(write(socketFD, cmd, strlen(cmd) + 1) < 0)) {
returnCode = errno;
logger->printWarnMsgWithErrno("Could not send threaddump command to JVM");
throw 2;
}
/* Write three params */
for (int i = 0; i < 3; i++) {
if (unlikely(write(socketFD, conf[i], strlen(conf[i]) + 1) < 0)) {
returnCode = errno;
logger->printWarnMsgWithErrno(
"Could not send threaddump command to JVM");
throw 3;
}
}
for (; waitCount <= WAIT_LIMIT; waitCount++) {
/* Sleep for 1 milli-second. */
littleSleep(0, 1000000);
/* Check response. */
if (read(socketFD, &result, sizeof(result)) > 0) {
break;
}
}
/* Read respone and Write to file. */
char buff[255];
ssize_t readByte = 0;
while ((readByte = read(socketFD, buff, sizeof(buff))) > 0) {
if (unlikely(write(fd, buff, readByte) < 0)) {
returnCode = errno;
logger->printWarnMsgWithErrno("Could not receive threaddump from JVM");
throw 4;
}
}
} catch (...) {
; /* Failed to write file. */
}
/* Cleanup. */
close(socketFD);
if (unlikely(close(fd) < 0 && returnCode == 0)) {
returnCode = errno;
logger->printWarnMsgWithErrno("Could not close socket to JVM");
}
/* Check command execute result. */
if (unlikely(waitCount > WAIT_LIMIT)) {
/* Maybe JVM is busy. */
logger->printWarnMsg("AttachListener does not respond.");
return -1;
} else if (unlikely(result != '0')) {
/* Illegal command or other error. */
logger->printWarnMsg("Failure execute socket command.");
return result;
}
/* Succeed or file error. */
return returnCode;
}
/*!
* \brief Create JVM socket file.
* \return Process result.
*/
bool TJVMSockCmd::createJvmSock(void) {
/* Socket file path. */
char sockPath[PATH_MAX] = {0};
/* Search jvm socket file. */
if (!findJvmSock((char*)&sockPath, PATH_MAX)) {
/* Attach file path. */
char attachPath[PATH_MAX + 1] = {0};
/* No exists so create socket file. */
if (unlikely(!createAttachFile((char*)&attachPath, PATH_MAX))) {
/* Failure create attach-file or send signal. */
logger->printWarnMsg("Failure create socket.");
if (strlen(attachPath) != 0) {
unlink(attachPath);
}
return false;
} else {
/* Wait for JVM socket file. */
bool isFoundSocket = false;
for (int waitCount = 0; waitCount < 1000; waitCount++) {
/* Sleep for 1 milli-second. */
littleSleep(0, 1000000);
/* Recheck socket exists. */
if (findJvmSock((char*)&sockPath, PATH_MAX)) {
isFoundSocket = true;
break;
}
}
unlink(attachPath);
if (unlikely(!isFoundSocket)) {
/* Not found socket file. */
logger->printWarnMsg("Failure find JVM socket.");
return false;
}
}
}
/* Copy socket path. */
strncpy(socketPath, sockPath, PATH_MAX);
/* Succeed. */
return true;
}
/*!
* \brief Open socket to JVM.
* \param path [in] Path of socket file.
* \return Socket file descriptor.
*/
int TJVMSockCmd::openJvmSock(char* path) {
/* Sanity check. */
if (unlikely(path == NULL || strlen(path) == 0)) {
return -1;
}
/* Socket structure. */
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
/* Create socket. */
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (unlikely(fd < 0)) {
/* Failure create socket. */
return -1;
}
/* Copy socket path. */
strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
/* Connect socket. */
if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
/* Cleanup. */
close(fd);
return -1;
}
/* Return socket file descriptor. */
return fd;
}
/*!
* \brief Find JVM socket file and get path.
* \param path [out] Path of socket file.
* \param pathLen [in] Max length of param "path".
* \return Search result.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-truncation"
bool TJVMSockCmd::findJvmSock(char* path, int pathLen) {
/* Sanity check. */
if (unlikely(path == NULL || pathLen <= 0)) {
return false;
}
/*
* Memo
* Socket file is different path by JDK version.
*
* JDK: Most OracleJDK, OpenJDK.
* Path: "/tmp".
*
* JDK: OracleJDK u23/u24, Same OpenJDK.
* Path: System.getProperity("java.io.tmpdir").
*
* JDK: Few OracleJDK, OpenJDK.
* Path: CWD or "/tmp".
*/
char sockPath[PATH_MAX] = {0};
pid_t selfPid = getpid();
/* Open socket at normally temporary directory. */
snprintf(sockPath, PATH_MAX, "/tmp/.java_pid%d", selfPid);
int fd = openJvmSock(sockPath);
if (fd < 0) {
/* Open socket at designated temporary directory. */
snprintf(sockPath, PATH_MAX, "%s/.java_pid%d", tempPath, selfPid);
fd = openJvmSock(sockPath);
}
if (fd < 0) {
/* Open socket at CWD. */
snprintf(sockPath, PATH_MAX, "/proc/%d/cwd/.java_pid%d", selfPid, selfPid);
fd = openJvmSock(sockPath);
}
/* If no exists sock. */
if (unlikely(fd < 0)) {
return false;
}
/* Cleanup. */
close(fd);
/* Copy path. */
strncpy(path, sockPath, pathLen);
return true;
}
#pragma GCC diagnostic pop
/*!
* \brief Create attach file.
* \param path [out] Path of created attach file.
* \param pathLen [in] Max length of param "path".
* \return Process result.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-truncation"
bool TJVMSockCmd::createAttachFile(char* path, int pathLen) {
/* Sanity check. */
if (unlikely(path == NULL || pathLen <= 0)) {
return false;
}
/*
* Memo
* Attach file is also different path by JDK version.
* JVM dosen't recognize attach file,
* if make attach file under incorrect path.
*
* JDK: Most OracleJDK, OpenJDK
* Path: "/tmp" and CWD.
*
* JDK: OracleJDK u23/u24, Same OpenJDK
* Path: System.getProperity("java.io.tmpdir") and CWD.
*/
char attachPath[PATH_MAX] = {0};
pid_t selfPid = getpid();
int fd = 0;
/* Create attach-file at current directory. */
snprintf(attachPath, PATH_MAX, "/proc/%d/cwd/.attach_pid%d", selfPid,
selfPid);
fd = open(attachPath, O_CREAT | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (unlikely(fd < 0)) {
/* Create attach-file at designated temporary directory. */
snprintf(attachPath, PATH_MAX, "%s/.attach_pid%d", tempPath, selfPid);
fd = open(attachPath, O_CREAT | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
}
if (unlikely(fd < 0)) {
/* Create attach-file at normally temporary directory. */
snprintf(attachPath, PATH_MAX, "/tmp/.attach_pid%d", selfPid);
fd = open(attachPath, O_CREAT | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
}
/* If failure create attach-file. */
if (unlikely(fd < 0)) {
logger->printWarnMsgWithErrno("Could not create attach file");
return false;
}
/* Cleanup and copy attach file path. */
close(fd);
strncpy(path, attachPath, pathLen);
/* Notification means "please create and listen socket" to JVM. */
if (unlikely(kill(selfPid, SIGQUIT) != 0)) {
logger->printWarnMsgWithErrno("Could not send SIGQUIT to JVM");
return false;
}
return true;
}
#pragma GCC diagnostic pop
| 12,042
|
C++
|
.cpp
| 376
| 27.909574
| 82
| 0.641885
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,027
|
trapSender.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/trapSender.cpp
|
/*!
* \file trapSender.cpp
* \brief This file is used to send SNMP trap.
* Copyright (C) 2016-2019 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <set>
#include <sys/time.h>
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <pthread.h>
#include <dlfcn.h>
#include "globals.hpp"
#include "util.hpp"
#include "trapSender.hpp"
/*!
* \brief Datetime of agent initialization.
*/
unsigned long int TTrapSender::initializeTime;
/*!
* \brief Mutex for TTrapSender.<br>
* <br>
* This mutex used in below process.<br>
* - TTrapSender::initialize()
* - TTrapSender::finalize()
* - TTrapSender::~TTrapSender
* - TTrapSender::sendTrap
*/
pthread_mutex_t TTrapSender::senderMutex =
PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
/*!
* \brief Flags whether libnetsnmp.so is loaded.
*/
bool TTrapSender::is_netsnmp_loaded = false;
/*!
* \brief Library handle of libnetsnmp.so .
*/
void * TTrapSender::libnetsnmp_handle = NULL;
/*!
* \brief Functions in NET-SNMP client library.
*/
TNetSNMPFunctions TTrapSender::netSnmpFuncs;
/*!
* \brief SNMP session information.
*/
netsnmp_session TTrapSender::session;
/*!
* \brief TTrapSender initialization.
* \param snmp [in] SNMP version.
* \param pPeer [in] Target of SNMP trap.
* \param pCommName [in] Community name use for SNMP.
* \param port [in] Port used by SNMP trap.
* \return true if succeeded.
*/
// Avoid deprecation warning of snmp_session::remote_port
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
bool TTrapSender::initialize(int snmp, char *pPeer, char *pCommName, int port) {
/* If snmp target is illegal. */
if (pPeer == NULL) {
logger->printWarnMsg("Illegal SNMP target.");
return false;
}
/* Get now date and set time as agent init-time. */
struct timeval tv;
gettimeofday(&tv, NULL);
TTrapSender::initializeTime =
(jlong)tv.tv_sec * 100 + (jlong)tv.tv_usec / 10000;
/* Load functions from libnetsnmp */
if (!getProcAddressFromNetSNMPLib()) {
return false;
}
/* Initialize session. */
{
TMutexLocker locker(&senderMutex);
memset(&session, 0, sizeof(netsnmp_session));
netSnmpFuncs.snmp_sess_init(&session);
session.version = snmp;
session.peername = strdup(pPeer);
session.remote_port = port;
session.community = (u_char *)strdup(pCommName);
session.community_len = (pCommName != NULL) ? strlen(pCommName) : 0;
}
return true;
}
#pragma GCC diagnostic pop
/*!
* \brief TTrapSender global finalization.
*/
void TTrapSender::finalize(void) {
/* Close and free SNMP session. */
{
TMutexLocker locker(&senderMutex);
netSnmpFuncs.snmp_close(&session);
free(session.peername);
free(session.community);
}
/* Unload library */
if (libnetsnmp_handle != NULL) {
dlclose(libnetsnmp_handle);
}
}
/*!
* \brief TrapSender constructor.
*/
TTrapSender::TTrapSender() {
TMutexLocker locker(&senderMutex);
/* Disable NETSNMP logging. */
netSnmpFuncs.netsnmp_register_loghandler(
NETSNMP_LOGHANDLER_NONE, LOG_EMERG);
/* Make a PDU */
pPdu = netSnmpFuncs.snmp_pdu_create(SNMP_MSG_TRAP2);
}
/*!
* \brief TrapSender destructor.
*/
TTrapSender::~TTrapSender(void) {
TMutexLocker locker(&senderMutex);
/* Clear Allocated str. */
clearValues();
/* Free SNMP pdu. */
if (pPdu != NULL) {
netSnmpFuncs.snmp_free_pdu(pPdu);
}
}
/*!
* \brief Add agent running time from initialize to trap.
*/
void TTrapSender::setSysUpTime(void) {
/* OID and buffer. */
oid OID_SYSUPTIME[] = {SNMP_OID_SYSUPTIME, 0};
char buff[255] = {0};
/* Get agent uptime. */
unsigned long int agentUpTime = 0;
struct timeval tv;
gettimeofday(&tv, NULL);
agentUpTime = ((jlong)tv.tv_sec * 100 + (jlong)tv.tv_usec / 10000) -
TTrapSender::initializeTime;
/* Uptime to String. */
sprintf(buff, "%lu", agentUpTime);
/* Setting sysUpTime. */
if (addValue(OID_SYSUPTIME, OID_LENGTH(OID_SYSUPTIME), buff,
SNMP_VAR_TYPE_TIMETICK) == SNMP_PROC_FAILURE) {
logger->printWarnMsg("Couldn't append SysUpTime.");
}
}
/*!
* \brief Add trapOID to send information by trap.
* \param trapOID[] [in] Identifier of trap.
*/
void TTrapSender::setTrapOID(const char *trapOID) {
/* Setting trapOID. */
oid OID_TRAPOID[] = {SNMP_OID_TRAPOID, 0};
/* Add snmpTrapOID. */
if (addValue(OID_TRAPOID, OID_LENGTH(OID_TRAPOID), trapOID,
SNMP_VAR_TYPE_OID) == SNMP_PROC_FAILURE) {
logger->printWarnMsg("Couldn't append TrapOID.");
}
}
/*!
* \brief Add variable as send information by trap.
* \param id[] [in] Identifier of variable.
* \param len [in] Length of param "id".
* \param pValue [in] Variable's data.
* \param type [in] Kind of a variable.
* \return Return process result code.
*/
int TTrapSender::addValue(oid id[], int len, const char *pValue, char type) {
/* Check param. */
if (id == NULL || len <= 0 || pValue == NULL || type < 'A' || type > 'z' ||
(type > 'Z' && type < 'a') || pPdu == NULL) {
logger->printWarnMsg("Illegal SNMP trap parameter!");
return SNMP_PROC_FAILURE;
}
/* Allocate string memory. */
char *pStr = strdup(pValue);
/* If failure allocate value string. */
if (unlikely(pStr == NULL)) {
logger->printWarnMsg("Couldn't allocate variable string memory!");
return SNMP_PROC_FAILURE;
}
/* Append variable. */
int error = netSnmpFuncs.snmp_add_var(pPdu, id, len, type, pStr);
/* Failure append variables. */
if (error) {
free(pStr);
logger->printWarnMsg("Couldn't append variable list!");
return SNMP_PROC_FAILURE;
}
/* Insert allocated string set. */
strSet.insert(pStr);
/* Return success code. */
return SNMP_PROC_SUCCESS;
}
/*!
* \brief Add variable as send information by trap.
* \return Return process result code.
*/
// Avoid deprecation warning of snmp_session::remote_port
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
int TTrapSender::sendTrap(void) {
/* If snmp target is illegal. */
if (pPdu == NULL) {
logger->printWarnMsg("Illegal SNMP target.");
return SNMP_PROC_FAILURE;
}
/* If failure lock to use in multi-thread. */
if (unlikely(pthread_mutex_lock(&senderMutex) != 0)) {
logger->printWarnMsg("Entering mutex failed!");
return SNMP_PROC_FAILURE;
}
SOCK_STARTUP;
/* Open session. */
#ifdef HAVE_NETSNMP_TRANSPORT_OPEN_CLIENT
netsnmp_session *sess = netSnmpFuncs.snmp_add(
&session, netSnmpFuncs.netsnmp_transport_open_client(
"snmptrap", session.peername),
NULL, NULL);
#else
char target[256];
snprintf(target, sizeof(target), "%s:%d", session.peername,
session.remote_port);
netsnmp_session *sess = netSnmpFuncs.snmp_add(
&session, netSnmpFuncs.netsnmp_tdomain_transport(target, 0, "udp"),
NULL, NULL);
#endif
/* If failure open session. */
if (sess == NULL) {
logger->printWarnMsg("Failure open SNMP trap session.");
SOCK_CLEANUP;
/* Unlock to use in multi-thread. */
pthread_mutex_unlock(&senderMutex);
return SNMP_PROC_FAILURE;
}
/*
* Send trap.
* snmp_send() will free pPDU.
*/
int success = netSnmpFuncs.snmp_send(sess, pPdu);
/* Clean up after send trap. */
netSnmpFuncs.snmp_close(sess);
/* If failure send trap. */
if (!success) {
/* Free PDU. */
netSnmpFuncs.snmp_free_pdu(pPdu);
logger->printWarnMsg("Send SNMP trap failed!");
}
pPdu = NULL;
/* Clean up. */
SOCK_CLEANUP;
/* Unlock to use in multi-thread. */
pthread_mutex_unlock(&senderMutex);
clearValues();
return (success) ? SNMP_PROC_SUCCESS : SNMP_PROC_FAILURE;
}
#pragma GCC diagnostic pop
/*!
* \brief Clear PDU and allocated strings.
*/
void TTrapSender::clearValues(void) {
/* Free allocated strings. */
std::set<char *>::iterator it = strSet.begin();
while (it != strSet.end()) {
free((*it));
++it;
}
strSet.clear();
if (pPdu == NULL) {
pPdu = netSnmpFuncs.snmp_pdu_create(SNMP_MSG_TRAP2);
}
}
/*!
* \brief Get function address from libnetsnmp.
* \return true if succeeded.
*/
bool TTrapSender::getProcAddressFromNetSNMPLib(void) {
libnetsnmp_handle = dlopen(conf->SnmpLibPath()->get(), RTLD_NOW);
if (libnetsnmp_handle == NULL) {
logger->printCritMsg("Could not load libnetsnmp: %s", dlerror());
return false;
}
netSnmpFuncs.netsnmp_register_loghandler =
(Tnetsnmp_register_loghandler)dlsym(
libnetsnmp_handle, "netsnmp_register_loghandler");
netSnmpFuncs.snmp_sess_init = (Tsnmp_sess_init)dlsym(
libnetsnmp_handle, "snmp_sess_init");
netSnmpFuncs.snmp_pdu_create = (Tsnmp_pdu_create)dlsym(
libnetsnmp_handle, "snmp_pdu_create");
netSnmpFuncs.snmp_free_pdu = (Tsnmp_free_pdu)dlsym(
libnetsnmp_handle, "snmp_free_pdu");
netSnmpFuncs.snmp_close = (Tsnmp_close)dlsym(libnetsnmp_handle, "snmp_close");
netSnmpFuncs.snmp_add_var = (Tsnmp_add_var)dlsym(
libnetsnmp_handle, "snmp_add_var");
netSnmpFuncs.snmp_add = (Tsnmp_add)dlsym(libnetsnmp_handle, "snmp_add");
netSnmpFuncs.netsnmp_transport_open_client =
(Tnetsnmp_transport_open_client)dlsym(
libnetsnmp_handle, "netsnmp_transport_open_client");
netSnmpFuncs.netsnmp_tdomain_transport = (Tnetsnmp_tdomain_transport)dlsym(
libnetsnmp_handle, "netsnmp_tdomain_transport");
netSnmpFuncs.snmp_send = (Tsnmp_send)dlsym(libnetsnmp_handle, "snmp_send");
if ((netSnmpFuncs.netsnmp_register_loghandler == NULL) ||
(netSnmpFuncs.snmp_sess_init == NULL) ||
(netSnmpFuncs.snmp_pdu_create == NULL) ||
(netSnmpFuncs.snmp_free_pdu == NULL) ||
(netSnmpFuncs.snmp_close == NULL) ||
(netSnmpFuncs.snmp_add_var == NULL) ||
(netSnmpFuncs.snmp_add == NULL) ||
(netSnmpFuncs.netsnmp_transport_open_client == NULL) ||
(netSnmpFuncs.snmp_send == NULL)) {
logger->printCritMsg("Could not load function(s) from libnetsnmp");
return false;
}
return true;
}
| 11,208
|
C++
|
.cpp
| 329
| 29.334347
| 82
| 0.663832
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,028
|
archiveMaker.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/archiveMaker.cpp
|
/*!
* \file archiveMaker.cpp
* \brief This file is used create archive file.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <string.h>
#include "archiveMaker.hpp"
/*!
* \brief TArchiveMaker constructor.
*/
TArchiveMaker::TArchiveMaker(void) {
/* Clear target path. */
memset(sourcePath, 0, sizeof(sourcePath));
}
/*!
* \brief TArchiveMaker destructor.
*/
TArchiveMaker::~TArchiveMaker(void) { /* Do Nothing. */ }
/*!
* \brief Setting target file path.
* \param targetPath [in] Path of archive target file.
*/
void TArchiveMaker::setTarget(char const* targetPath) {
strncpy(sourcePath, targetPath, PATH_MAX);
}
/*!
* \brief Clear archive file data.
*/
void TArchiveMaker::clear(void) { memset(sourcePath, 0, sizeof(sourcePath)); }
/*!
* \brief Getting target file path.
* \return Path of archive target file.
*/
char const* TArchiveMaker::getTarget(void) { return sourcePath; }
| 1,665
|
C++
|
.cpp
| 49
| 32.081633
| 82
| 0.745183
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,029
|
signalManager.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/signalManager.cpp
|
/*!
* \file signalManager.cpp
* \brief This file is used by signal handling.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <signal.h>
#include "globals.hpp"
#include "vmFunctions.hpp"
#include "signalManager.hpp"
static TSignalHandlerChain *sighandlers[NSIG] = {0};
static TSignalMap signalMap[] =
{
{SIGHUP, "SIGHUP"}, {SIGALRM, "SIGALRM"}, {SIGUSR1, "SIGUSR1"},
{SIGUSR2, "SIGUSR2"}, {SIGTSTP, "SIGTSTP"}, {SIGTTIN, "SIGTTIN"},
{SIGTTOU, "SIGTTOU"}, {SIGPOLL, "SIGPOLL"}, {SIGVTALRM, "SIGVTALRM"},
{SIGIOT, "SIGIOT"}, {SIGWINCH, "SIGWINCH"}
};
void SignalHandlerStub(int signo, siginfo_t *siginfo, void *data) {
TSignalHandlerChain *chain = sighandlers[signo];
TVMFunctions *vmFunc = TVMFunctions::getInstance();
while (chain != NULL) {
if ((void *)chain->handler == vmFunc->GetSRHandlerPointer()) {
/* SR handler should be called in HotSpot Thread context. */
if (vmFunc->GetThread() != NULL) {
chain->handler(signo, siginfo, data);
}
} else if (((void *)chain->handler == vmFunc->GetUserHandlerPointer()) &&
(signo == SIGHUP)) {
// This might SHUTDOWN1_SIGNAL handler which is defined in
// java.lang.Terminator . (Unix class)
// We should ignore this signal.
// Do nothing.
} else if ((void *)chain->handler != SIG_IGN) {
chain->handler(signo, siginfo, data);
}
chain = chain->next;
}
}
/* Class methods. */
/*!
* \brief Find signal number from name.
* \param sig Signal name.
* \return Signal number. Return -1 if not found.
*/
int TSignalManager::findSignal(const char *sig) {
for (size_t idx = 0; idx < (sizeof(signalMap) / sizeof(TSignalMap)); idx++) {
if (strcmp(signalMap[idx].name, sig) == 0){
return signalMap[idx].sig;
}
}
return -1;
}
/*!
* \brief TSignalManager constructor.
* \param sig Signal string.
*/
TSignalManager::TSignalManager(const char *sig) {
this->signal = findSignal(sig);
if (this->signal == -1) {
static char errstr[1024];
snprintf(errstr, 1024, "Invalid signal: %s", sig);
throw errstr;
}
}
/*!
* \brief TSignalManager destructor.
*/
TSignalManager::~TSignalManager() {
TSignalHandlerChain *chain = sighandlers[this->signal];
JVM_RegisterSignal(this->signal, (void *)chain->handler);
while (chain != NULL) {
TSignalHandlerChain *next = chain->next;
free(chain);
chain = next;
}
}
/*!
* \brief Add signal handler.
* \param handler [in] Function pointer for signal handler.
* \return true if new signal handler is added.
*/
bool TSignalManager::addHandler(TSignalHandler handler) {
TSignalHandlerChain *chain = sighandlers[this->signal];
if (chain == NULL) {
TSignalHandler oldHandler = (TSignalHandler)JVM_RegisterSignal(
this->signal, (void *)&SignalHandlerStub);
if ((ptrdiff_t)oldHandler == -1L) { // Cannot set
return false;
} else if ((ptrdiff_t)oldHandler == 1L) { // Ignore signal
oldHandler = (TSignalHandler)SIG_IGN;
} else if ((ptrdiff_t)oldHandler == 2L) { // User Handler in HotSpot
oldHandler =
(TSignalHandler)TVMFunctions::getInstance()->GetUserHandlerPointer();
}
chain = (TSignalHandlerChain *)calloc(1, sizeof(TSignalHandlerChain));
if (chain == NULL) {
throw errno;
}
chain->handler = oldHandler;
sighandlers[this->signal] = chain;
}
while (chain->next != NULL) {
chain = chain->next;
}
chain->next = (TSignalHandlerChain *)calloc(1, sizeof(TSignalHandlerChain));
if (chain->next == NULL) {
throw errno;
}
chain->next->handler = handler;
return true;
}
| 4,451
|
C++
|
.cpp
| 126
| 31.31746
| 82
| 0.675512
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,030
|
x86BitMapMarker.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/x86BitMapMarker.cpp
|
/*!
* \file x86BitMapMarker.cpp
* \brief This file is used to store and control of bit map.
* Copyright (C) 2014-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "util.hpp"
#include "x86BitMapMarker.hpp"
/*!
* \brief Mark GC-marked address in this bitmap.
* \param addr [in] Oop address.
*/
void TX86BitMapMarker::setMark(const void *addr) {
/* Sanity check. */
if (unlikely(!this->isInZone(addr))) {
return;
}
/*
* Why I use "ptrdiff_t" ?
* ptrdiff_t is integer representation of pointer. ptrdiff_t size equals
* pointer size. Pointer size equals CPU register size.
* Thus, we use CPU register more effective.
*/
ptrdiff_t *bitmapBlock;
ptrdiff_t bitmapMask;
this->getBlockAndMask(addr, &bitmapBlock, &bitmapMask);
/* Atomic set mark bit flag. */
asm volatile(
#ifdef __LP64__
"lock orq %1, %0;"
#else // __ILP32__
"lock orl %1, %0;"
#endif
: "+m"(*bitmapBlock)
: "r"(bitmapMask)
: "cc", "memory"
);
}
/*!
* \brief Get marked flag of designated pointer.
* \param addr [in] Targer pointer.
* \return Designated pointer is marked.
*/
bool TX86BitMapMarker::isMarked(const void *addr) {
/* Sanity check. */
if (unlikely(!this->isInZone(addr))) {
return false;
}
/* Get block and mask for getting mark flag. */
ptrdiff_t *bitmapBlock;
ptrdiff_t bitmapMask;
this->getBlockAndMask(addr, &bitmapBlock, &bitmapMask);
/* Atomic get mark bit flag. */
register bool result asm("al");
/*
* Intel 64 and IA-32 Architectures Software Developer's Manual.
* Volume 3A: System Programming Guide, Part1
* 8.2.3.8 Locked Instructions Have a Total Order:
* The memory-ordering model ensures that all processors agree
* on a single execution order of all locked instructions,
* including those that are larger than 8 bytes
* or are not naturally aligned.
*/
asm volatile(
"test %1, %2;"
"setneb %0;"
: "=r"(result)
: "m"(*bitmapBlock), "r"(bitmapMask)
: "cc", "memory"
);
return result;
}
/*!
* \brief Check address which is already marked and set mark.
* \param addr [in] Oop address.
* \return Designated pointer is marked.
*/
bool TX86BitMapMarker::checkAndMark(const void *addr) {
/* Sanity check. */
if (unlikely(!this->isInZone(addr))) {
return false;
}
/* Get block and mask for getting mark flag. */
ptrdiff_t *bitmapBlock;
ptrdiff_t bitmapMask;
this->getBlockAndMask(addr, &bitmapBlock, &bitmapMask);
/* Get and set mark. */
register bool result asm("al");
asm volatile(
#ifdef __amd64__
"bsfq %1, %%rbx;"
"lock btsq %%rbx, %2;"
#else // __i386__
"bsfl %1, %%edx;"
"lock btsl %%edx, %2;"
#endif
"setbb %0;"
: "=r"(result)
: "r"(bitmapMask), "m"(*bitmapBlock)
:
#ifdef __amd64__
"%rbx",
#else // __i386__
"%edx",
#endif
"cc", "memory"
);
return result;
}
| 3,605
|
C++
|
.cpp
| 123
| 26.292683
| 82
| 0.676852
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,031
|
sse2BitMapMarker.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/sse2/sse2BitMapMarker.cpp
|
/*!
* \file sse2BitMapMarker.cpp
* \brief Storeing and Controlling G1 marking bitmap.
* This source is optimized for SSE2 instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <sys/mman.h>
#include "sse2BitMapMarker.hpp"
/*!
* \brief Clear bitmap flag.
*/
void TSSE2BitMapMarker::clear(void) {
/*
* Linux memory page size = 4KB.
* So top address of _bitmap is 16byte aligned.
* _size is ditto.
*
* memset() in glibc sets 128bytes per loop.
*
*******************************************************
* Intel 64 and IA-32 Architectures Optimization Reference Manual
* Assembler/Compiler Coding Rule 12:
* All branch targets should be 16-byte aligned.
*/
/* Temporary advise to zero-clear with sequential access. */
madvise(this->bitmapAddr, this->bitmapSize, MADV_SEQUENTIAL);
asm volatile(
"pxor %%xmm0, %%xmm0;"
".align 16;"
".LSSE2_LOOP:" /* memset 128bytes per LOOP. */
"movntdq %%xmm0, -0x80(%1, %0, 1);"
"movntdq %%xmm0, -0x70(%1, %0, 1);"
"movntdq %%xmm0, -0x60(%1, %0, 1);"
"movntdq %%xmm0, -0x50(%1, %0, 1);"
"movntdq %%xmm0, -0x40(%1, %0, 1);"
"movntdq %%xmm0, -0x30(%1, %0, 1);"
"movntdq %%xmm0, -0x20(%1, %0, 1);"
"movntdq %%xmm0, -0x10(%1, %0, 1);"
#ifdef __amd64__
"subq $0x80, %0;"
#else // __i386__
"subl $0x80, %0;"
#endif
"jnz .LSSE2_LOOP;"
:
: "r"(this->bitmapSize), "r"(this->bitmapAddr)
: "cc", "%xmm0"
);
/* Reset advise. */
madvise(this->bitmapAddr, this->bitmapSize, MADV_RANDOM);
}
| 2,284
|
C++
|
.cpp
| 66
| 31.439394
| 82
| 0.648282
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,032
|
avxBitMapMarker.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/avx/avxBitMapMarker.cpp
|
/*!
* \file avxBitMapMarker.cpp
* \brief Storeing and Controlling G1 marking bitmap.
* This source is optimized for AVX instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <sys/mman.h>
#include "avxBitMapMarker.hpp"
/*!
* \brief Clear bitmap flag with AVX instruction set.
*/
void TAVXBitMapMarker::clear(void) {
/*
* Linux memory page size = 4KB.
* So top address of _bitmap is 16byte aligned.
* _size is ditto.
*
* memset() in glibc sets 128bytes per loop.
*
*******************************************************
* Intel 64 and IA-32 Architectures Optimization Reference Manual
* Assembler/Compiler Coding Rule 12:
* All branch targets should be 16-byte aligned.
*/
/* Temporary advise to zero-clear with sequential access. */
madvise(this->bitmapAddr, this->bitmapSize, MADV_SEQUENTIAL);
asm volatile(
"vxorpd %%ymm0, %%ymm0, %%ymm0;"
".align 16;"
".LAVX_LOOP:" /* memset 128bytes per LOOP. */
"vmovntdq %%ymm0, -0x80(%1, %0, 1);"
"vmovntdq %%ymm0, -0x60(%1, %0, 1);"
"vmovntdq %%ymm0, -0x40(%1, %0, 1);"
"vmovntdq %%ymm0, -0x20(%1, %0, 1);"
#ifdef __amd64__
"subq $0x80, %0;"
#else // __i386__
"subl $0x80, %0;"
#endif
"jnz .LAVX_LOOP;"
:
: "r"(this->bitmapSize), "r"(this->bitmapAddr)
: "cc" /*, "%ymm0" */
);
/* Reset advise. */
madvise(this->bitmapAddr, this->bitmapSize, MADV_RANDOM);
}
| 2,163
|
C++
|
.cpp
| 62
| 31.83871
| 82
| 0.662053
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,033
|
armBitMapMarker.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/armBitMapMarker.cpp
|
/*!
* \file armBitMapMarker.cpp
* \brief This file is used to store and control of bit map.
* Copyright (C) 2015-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "util.hpp"
#include "armBitMapMarker.hpp"
/*!
* \brief Mark GC-marked address in this bitmap.
* \param addr [in] Oop address.
*/
void TARMBitMapMarker::setMark(const void *addr) {
/* Sanity check. */
if (unlikely(!this->isInZone(addr))) {
return;
}
/*
* Why I use "ptrdiff_t" ?
* ptrdiff_t is integer representation of pointer. ptrdiff_t size equals
* pointer size. Pointer size equals CPU register size.
* Thus, we use CPU register more effective.
*/
ptrdiff_t *bitmapBlock;
ptrdiff_t bitmapMask;
this->getBlockAndMask(addr, &bitmapBlock, &bitmapMask);
asm volatile(
"1:"
" ldrex %%r0, [%0];"
" orr %%r0, %1;"
" strex %%r1, %%r0, [%0];"
" tst %%r1, %%r1;"
" bne 1b;"
:
: "r"(bitmapBlock), "r"(bitmapMask)
: "cc", "memory", "%r0", "%r1"
);
}
/*!
* \brief Check address which is already marked and set mark.
* \param addr [in] Oop address.
* \return Designated pointer is marked.
*/
bool TARMBitMapMarker::checkAndMark(const void *addr) {
/* Sanity check. */
if (unlikely(!this->isInZone(addr))) {
return false;
}
/* Get block and mask for getting mark flag. */
ptrdiff_t *bitmapBlock;
ptrdiff_t bitmapMask;
this->getBlockAndMask(addr, &bitmapBlock, &bitmapMask);
bool result = false;
asm volatile(
"mov %%r1, #1;"
"1:"
" ldrex %%r0, [%1];"
" tst %%r0, %2;"
" movne %0, #1;"
" orrne %%r0, %2;"
" strexne %%r1, %%r0, [%1];"
" tst %%r1, %%r1;"
" bne 1b;"
: "+r"(result)
: "r"(bitmapBlock), "r"(bitmapMask)
: "cc", "memory", "%r0", "%r1"
);
return result;
}
| 2,533
|
C++
|
.cpp
| 83
| 27.337349
| 82
| 0.647011
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,034
|
neonBitMapMarker.cpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/neon/neonBitMapMarker.cpp
|
/*!
* \file neonBitMapMarker.cpp
* \brief Storeing and Controlling G1 marking bitmap.
* This source is optimized for NEON instruction set.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <stddef.h>
#include <sys/mman.h>
#include "neonBitMapMarker.hpp"
/*!
* \brief Clear bitmap flag with NEON instruction set.
*/
void TNeonBitMapMarker::clear(void) {
/*
* Linux memory page size = 4KB.
* So top address of _bitmap is 16byte aligned.
* _size is ditto.
*
* memset() in glibc sets 128bytes per loop.
*/
ptrdiff_t end_addr = (ptrdiff_t) this->bitmapAddr + this->bitmapSize;
/* Temporary advise to zero-clear with sequential access. */
madvise(this->bitmapAddr, this->bitmapSize, MADV_SEQUENTIAL);
asm volatile(
"vbic.I64 %%q0, %%q0, %%q0;"
"1:"
" vst1.8 {%%q0}, [%0]!;"
" vst1.8 {%%q0}, [%0]!;"
" vst1.8 {%%q0}, [%0]!;"
" vst1.8 {%%q0}, [%0]!;"
" vst1.8 {%%q0}, [%0]!;"
" vst1.8 {%%q0}, [%0]!;"
" vst1.8 {%%q0}, [%0]!;"
" vst1.8 {%%q0}, [%0]!;"
" cmp %0, %1;"
" bne 1b;"
:
: "r"(this->bitmapAddr), "r"(end_addr)
: "cc"
);
/* Reset advise. */
madvise(this->bitmapAddr, this->bitmapSize, MADV_RANDOM);
}
| 1,950
|
C++
|
.cpp
| 58
| 30.5
| 82
| 0.653581
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,035
|
heapstats_md_x86.cpp
|
HeapStats_heapstats/agent/src/arch/x86/heapstats_md_x86.cpp
|
/*!
* \file heapstats_md_x86.cpp
* \brief Proxy library for HeapStats backend.
* This file implements x86 specific code for loading backend library.
* Copyright (C) 2014-2018 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <link.h>
#include <libgen.h>
#include <stdio.h>
#include <dlfcn.h>
#include <limits.h>
#include <stddef.h>
#include <string.h>
#include "heapstats_md.hpp"
#include "heapstats_md_x86.hpp"
/*!
* \brief Check CPU instruction.
* \return Max level of instruction.
*/
static const char *checkInstructionSet(void) {
int cFlag = 0;
int dFlag = 0;
#ifdef __amd64__
asm volatile("cpuid;" : "=c"(cFlag), "=d"(dFlag) : "a"(1) : "cc", "%ebx");
#else // i386
/* Evacuate EBX because EBX is PIC register. */
asm volatile(
"pushl %%ebx;"
"cpuid;"
"popl %%ebx;"
: "=c"(cFlag), "=d"(dFlag)
: "a"(1)
: "cc"
);
#endif
#ifdef AVX
if ((cFlag >> 28) & 1) {
return OPTIMIZE_AVX;
} else
#endif
#ifdef SSE4
if (((cFlag >> 20) & 1) || ((cFlag >> 19) & 1)) {
return OPTIMIZE_SSE4;
} else
#endif
#ifdef SSE2
if ((dFlag >> 26) & 1) {
return OPTIMIZE_SSE2;
} else
#endif
{
return OPTIMIZE_NONE;
}
}
/*!
* \brief Callback function for dl_iterate_phdr to find HeapStats library.
*/
static int findHeapStatsCallback(struct dl_phdr_info *info, size_t size,
void *data) {
ptrdiff_t this_func_addr = (ptrdiff_t)&findHeapStatsCallback;
for (int idx = 0; idx < info->dlpi_phnum; idx++) {
ptrdiff_t base_addr = info->dlpi_addr + info->dlpi_phdr[idx].p_vaddr;
if ((this_func_addr >= base_addr) &&
(this_func_addr <= base_addr +
(ptrdiff_t)info->dlpi_phdr[idx].p_memsz)) {
strcpy((char *)data, dirname((char *)info->dlpi_name));
return 1;
}
}
return 0;
}
/*!
* \brief Load HeapStats engine.
* \return Library handle which is used in dlsym(). NULL if error occurred.
*/
void *loadHeapStatsEngine(void) {
char engine_path[PATH_MAX];
char heapstats_path[PATH_MAX];
int found = dl_iterate_phdr(&findHeapStatsCallback, heapstats_path);
if (found == 0) {
fprintf(stderr, "HeapStats shared library is not found!\n");
return NULL;
}
int ret = snprintf(engine_path, PATH_MAX,
"%s/heapstats-engines/libheapstats-engine-%s-"
HEAPSTATS_MAJOR_VERSION ".so",
heapstats_path, checkInstructionSet());
if (ret >= PATH_MAX) {
fprintf(stderr,
"HeapStats engine could not be loaded: engine path is too long\n");
return NULL;
}
void *hEngine = dlopen(engine_path, RTLD_NOW);
if (hEngine == NULL) {
fprintf(stderr,
"HeapStats engine could not be loaded: library: %s, cause: %s\n",
engine_path, dlerror());
return NULL;
}
return hEngine;
}
| 3,614
|
C++
|
.cpp
| 119
| 26.260504
| 82
| 0.652874
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,036
|
heapstats_md_arm.cpp
|
HeapStats_heapstats/agent/src/arch/arm/heapstats_md_arm.cpp
|
/*!
* \file heapstats_md_arm.cpp
* \brief Proxy library for HeapStats backend.
* This file implements ARM specific code for loading backend library.
* Copyright (C) 2015-2018 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <link.h>
#include <libgen.h>
#include <stdio.h>
#include <dlfcn.h>
#include <limits.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include <asm/hwcap.h>
#ifdef HAVE_SYS_AUXV_H
#include <sys/auxv.h>
#else
#include <fcntl.h>
#include <elf.h>
#endif
#include "heapstats_md.hpp"
/*!
* \brief Callback function for dl_iterate_phdr to find HeapStats library.
*/
static int findHeapStatsCallback(struct dl_phdr_info *info, size_t size,
void *data) {
uintptr_t this_func_addr = (uintptr_t)&findHeapStatsCallback;
for (int idx = 0; idx < info->dlpi_phnum; idx++) {
uintptr_t base_addr = info->dlpi_addr + info->dlpi_phdr[idx].p_vaddr;
if ((this_func_addr >= base_addr) &&
(this_func_addr <= base_addr + info->dlpi_phdr[idx].p_memsz)) {
strcpy((char *)data, dirname((char *)info->dlpi_name));
return 1;
}
}
return 0;
}
#ifdef HAVE_SYS_AUXV_H
/*!
* \brief check NEON support.
* http://community.arm.com/groups/android-community/blog/2014/10/10/runtime-detection-of-cpu-features-on-an-armv8-a-cpu
* \return true if NEON is supported.
*/
static bool checkNEON(void) { return getauxval(AT_HWCAP) & HWCAP_NEON; }
#else
static bool checkNEON(void) {
int fd = open("/proc/self/auxv", O_RDONLY);
if (fd == -1) {
return false;
}
Elf32_auxv_t aux;
bool result = false;
while (read(fd, &aux, sizeof(Elf32_auxv_t)) > 0) {
if ((aux.a_type == AT_HWCAP) && ((aux.a_un.a_val & HWCAP_NEON) != 0)) {
result = true;
break;
}
}
close(fd);
return result;
}
#endif
/*!
* \brief Load HeapStats engine.
* \return Library handle which is used in dlsym(). NULL if error occurred.
*/
void *loadHeapStatsEngine(void) {
char engine_path[PATH_MAX];
char heapstats_path[PATH_MAX];
int found = dl_iterate_phdr(&findHeapStatsCallback, heapstats_path);
if (found == 0) {
fprintf(stderr, "HeapStats shared library is not found!\n");
return NULL;
}
sprintf(engine_path, "%s/heapstats-engines/libheapstats-engine-%s-%s.so",
heapstats_path, checkNEON() ? "neon" : "none",
HEAPSTATS_MAJOR_VERSION);
void *hEngine = dlopen(engine_path, RTLD_NOW);
if (hEngine == NULL) {
fprintf(stderr,
"HeapStats engine could not be loaded: library: %s, cause: %s\n",
engine_path, dlerror());
return NULL;
}
return hEngine;
}
| 3,393
|
C++
|
.cpp
| 105
| 29.019048
| 127
| 0.68664
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,037
|
heapstats-mbean.h
|
HeapStats_heapstats/mbean/native/heapstats-mbean.h
|
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class jp_co_ntt_oss_heapstats_mbean_HeapStats */
#ifndef _Included_jp_co_ntt_oss_heapstats_mbean_HeapStats
#define _Included_jp_co_ntt_oss_heapstats_mbean_HeapStats
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: jp_co_ntt_oss_heapstats_mbean_HeapStats
* Method: registerNatives
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_jp_co_ntt_oss_heapstats_mbean_HeapStats_registerNatives
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
| 541
|
C++
|
.h
| 19
| 27.052632
| 83
| 0.753846
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
755,038
|
run-libjvm.hpp
|
HeapStats_heapstats/agent/test/gtest/src/run-libjvm.hpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <pthread.h>
#include <jni.h>
#include <gtest/gtest.h>
class RunLibJVMTest : public testing::Test{
private:
static pthread_t java_driver;
protected:
static void GetJVM(JavaVM **vm, JNIEnv **env);
static void SetUpTestCase();
static void TearDownTestCase();
public:
static void *java_driver_main(void *data);
char *GetSystemProperty(const char *key);
};
| 1,195
|
C++
|
.h
| 32
| 34.6875
| 82
| 0.749352
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,039
|
heapStatsEnvironment.hpp
|
HeapStats_heapstats/agent/test/gtest/src/heapStatsEnvironment.hpp
|
/*!
* Copyright (C) 2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <gtest/gtest.h>
#include <heapstats-engines/globals.hpp>
class HeapStatsEnvironment : public testing::Environment{
public:
virtual ~HeapStatsEnvironment(){};
virtual void SetUp();
virtual void TearDown();
};
| 1,033
|
C++
|
.h
| 26
| 37.384615
| 82
| 0.760718
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,040
|
heapstats.hpp
|
HeapStats_heapstats/agent/src/heapstats.hpp
|
/*!
* \file heapstats.hpp
* \brief Proxy library for HeapStats backend.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef HEAPSTATS_HPP
#define HEAPSTATS_HPP
#include <jni.h>
#include <jvmti.h>
/* Function pointer prototypes */
typedef jint (*TAgentOnLoadFunc)(JavaVM *vm, char *options, void *reserved);
typedef jint (*TAgentOnAttachFunc)(JavaVM *vm, char *options, void *reserved);
typedef jint (*TAgentOnUnloadFunc)(JavaVM *vm);
/* Define export function for calling from external. */
extern "C" {
/*!
* \brief Agent attach entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Attach initialization result code.
*/
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved);
/*!
* \brief Common agent unload entry points.
* \param vm [in] JavaVM object.
*/
JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm);
/*!
* \brief Ondemand attach's entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Ondemand-attach initialization result code.
*/
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM *vm, char *options, void *reserved);
};
#endif // HEAPSTATS_HPP
| 2,046
|
C++
|
.h
| 54
| 35.240741
| 82
| 0.72796
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,041
|
heapstats_md.hpp
|
HeapStats_heapstats/agent/src/heapstats_md.hpp
|
/*!
* \file heapstats_md.hpp
* \brief Proxy library for HeapStats backend.
* This file defines machine-dependent (md) types/functions.
* Each md source in "arch" should be implemented functions
* in this file.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef HEAPSTATS_MD_HPP
#define HEAPSTATS_MD_HPP
#include <jni.h>
#include <jvmti.h>
/* Function pointer prototypes */
typedef jint (*TAgentOnLoadFunc)(JavaVM *vm, char *options, void *reserved);
typedef jint (*TAgentOnAttachFunc)(JavaVM *vm, char *options, void *reserved);
typedef jint (*TAgentOnUnloadFunc)(JavaVM *vm);
/*!
* \brief Load HeapStats engine.
* \return Library handle which is used in dlsym(). NULL if error occurred.
*/
void *loadHeapStatsEngine(void);
#endif // HEAPSTATS_MD_HPP
| 1,511
|
C++
|
.h
| 37
| 39.027027
| 82
| 0.748128
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,042
|
vmStructScanner.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/vmStructScanner.hpp
|
/*!
* \file vmStructScanner.hpp
* \brief This file is used to getting JVM structure information.<br>
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _VMSCANNER_HPP
#define _VMSCANNER_HPP
#include <stdint.h>
#include <sys/types.h>
#include "symbolFinder.hpp"
/* Type define. */
/* Structure for VMStruct. */
/* from hotspot/src/share/vm/runtime/vmStructs.hpp */
/*!
* \brief Hotspot JVM information structure.
*/
typedef struct {
const char *typeName;
/*!< The type name containing the given field. (example: "Klass") */
const char *fieldName;
/*!< The field name within the type. (example: "_name") */
const char *typeString;
/*!< Quoted name of the type of this field. (example: "symbolOopDesc*")<br>
Parsed in Java to ensure type correctness. */
int32_t isStatic;
/*!< Indicates whether following field is an offset or an address. */
uint64_t offset;
/*!< Offset of field within structure; only used for nonstatic fields. */
void *address;
/*!< Address of field; only used for static fields. <br>
("offset" can not be reused because of apparent SparcWorks compiler bug
in generation of initializer data) */
} VMStructEntry;
/*!
* \brief Hotspot's inner class information structure.
*/
typedef struct {
const char *typeName;
/*!< Type name. (example: "methodOopDesc") */
const char *superclassName;
/*!< Superclass name, or null if none. (example: "oopDesc") */
int32_t isOopType;
/*!< Does this type represent an oop typedef. <br>
(i.e., "methodOop" or "klassOop", but NOT "methodOopDesc") */
int32_t isIntegerType;
/*!< Does this type represent an integer type. (of arbitrary size) */
int32_t isUnsigned;
/*!< If so, is it unsigned. */
uint64_t size;
/*!< Size, in bytes, of the type. */
} VMTypeEntry;
/*!
* \brief Hotspot constant integer information structure.
*/
typedef struct {
const char *name;
/*!< Name of constant. (example: "_thread_in_native") */
int32_t value;
/*!< Value of constant. */
} VMIntConstantEntry;
/*!
* \brief Hotspot constant long integer information structure.
*/
typedef struct {
const char *name;
/*!< Name of constant. (example: "_thread_in_native") */
uint64_t value;
/*!< Value of constant. */
} VMLongConstantEntry;
/* Structure for TVMStructScanner. */
/*!
* \brief Field offset/pointer information structure.
*/
typedef struct {
const char *className;
/*!< String of target class name. */
const char *fieldName;
/*!< String of target class's field name. */
off_t *ofs;
/*!< Offset of target field.(If target field is dynamic) */
void **addr;
/*!< Pointer of target field.(If target field is static) */
} TOffsetNameMap;
/*!
* \brief Type size structure.
*/
typedef struct {
const char *typeName;
/*!< String of target class name. */
uint64_t *size;
/*!< Size of target class type. */
} TTypeSizeMap;
/*!
* \brief Constant integer structure.
*/
typedef struct {
const char *name;
/*!< String of target integer constant name. */
int32_t *value;
/*!< Value of interger constant. */
} TIntConstMap;
/*!
* \brief Constant long integer structure.
*/
typedef struct {
const char *name;
/*!< String of target long integer constant name. */
uint64_t *value;
/*!< Value of long interger constant. */
} TLongConstMap;
/* Class define. */
/*!
* \brief This class is used to search JVM inner information.<br>
* E.g. VMStruct, inner-class, etc...
*/
class TVMStructScanner {
public:
/*!
* \brief TVMStructScanner constructor.
* \param finder [in] Symbol search object.
*/
TVMStructScanner(TSymbolFinder *finder);
/*!
* \brief Get offset data from JVM inner struct.
* \param ofsMap [out] Map of search offset target.
*/
void GetDataFromVMStructs(TOffsetNameMap *ofsMap);
/*!
* \brief Get type size data from JVM inner struct.
* \param typeMap [out] Map of search constant target.
*/
void GetDataFromVMTypes(TTypeSizeMap *typeMap);
/*!
* \brief Get int constant data from JVM inner struct.
* \param constMap [out] Map of search constant target.
*/
void GetDataFromVMIntConstants(TIntConstMap *constMap);
/*!
* \brief Get long constant data from JVM inner struct.
* \param constMap [out] Map of search constant target.
*/
void GetDataFromVMLongConstants(TLongConstMap *constMap);
protected:
/*!
* \brief Pointer of Hotspot JVM information.
*/
static VMStructEntry **vmStructEntries;
/*!
* \brief Pointer of hotspot's inner class information.
*/
static VMTypeEntry **vmTypeEntries;
/*!
* \brief Pointer of hotspot constant integer information.
*/
static VMIntConstantEntry **vmIntConstEntries;
/*!
* \brief Pointer of hotspot constant long integer information.
*/
static VMLongConstantEntry **vmLongConstEntries;
};
#endif // _VMSCANNER_HPP
| 5,611
|
C++
|
.h
| 176
| 29.181818
| 82
| 0.708295
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,043
|
agentThread.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/agentThread.hpp
|
/*!
* \file agentThread.hpp
* \brief This file is used to work on Jthread.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef AGENT_THREAD_HPP
#define AGENT_THREAD_HPP
#include <jvmti.h>
#include <jni.h>
#include <pthread.h>
/*!
* \brief Entry point function type for jThread.
* \param jvmti [in] JVMTI environment information.
* \param name [in] Raw Monitor name.
* \param userData [in] Pointer of user data.
*/
typedef void(JNICALL *TThreadEntryPoint)(jvmtiEnv *jvmti, JNIEnv *jni,
void *userData);
/*!
* \brief This class is base class for parallel work using by jthread.
*/
class TAgentThread {
public:
/*!
* \brief TAgentThread constructor.
* \param name [in] Thread name.
*/
TAgentThread(const char *name);
/*!
* \brief TAgentThread destructor.
*/
virtual ~TAgentThread(void);
/*!
* \brief Make and begin Jthread.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param entryPoint [in] Entry point for jThread.
* \param conf [in] Pointer of user data.
* \param prio [in] Jthread priority.
*/
virtual void start(jvmtiEnv *jvmti, JNIEnv *env, TThreadEntryPoint entryPoint,
void *conf, jint prio);
/*!
* \brief Notify timing to this thread from other thread.
*/
virtual void notify(void);
/*!
* \brief Notify stopping to this thread from other thread.
*/
virtual void stop(void);
/*!
* \brief Notify termination to this thread from other thread.
*/
virtual void terminate(void);
protected:
/*!
* \brief Number of request.
*/
volatile int _numRequests;
/*!
* \brief Flag of exists termination request.
*/
volatile bool _terminateRequest;
/*!
* \brief Flag of jThread flag.
*/
volatile bool _isRunning;
/*!
* \brief Pthread mutex for thread.
*/
pthread_mutex_t mutex;
/*!
* \brief Pthread mutex condition for thread.
*/
pthread_cond_t mutexCond;
/*!
* \brief Thread name for java thread.
*/
char *threadName;
};
#endif
| 2,866
|
C++
|
.h
| 96
| 26.416667
| 82
| 0.687907
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,044
|
jvmInfo.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/jvmInfo.hpp
|
/*!
* \file jvmInfo.hpp
* \brief This file is used to get JVM performance information.
* Copyright (C) 2011-2018 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef JVMINFO_H
#define JVMINFO_H
#include <jvmti.h>
#include <jni.h>
#include <stddef.h>
/*!
* \brief Make HotSpot version
*/
#define MAKE_HS_VERSION(afterJDK9, major, minor, micro, build) \
(((afterJDK9) << 30) | ((major) << 24) | ((minor) << 16) | ((micro) << 8) | (build))
/*!
* \brief JVM performance header info.
*/
typedef struct {
jint magic; /*!< Magic number. - 0xcafec0c0 (bigEndian) */
jbyte byte_order; /*!< Byte order of the buffer. */
jbyte major_version; /*!< Major version numbers. */
jbyte minor_version; /*!< Minor version numbers. */
jbyte accessible; /*!< Ready to access. */
jint used; /*!< Number of PerfData memory bytes used. */
jint overflow; /*!< Number of bytes of overflow. */
jlong mod_time_stamp; /*!< Time stamp of last structural modification. */
jint entry_offset; /*!< Offset of the first PerfDataEntry. */
jint num_entries; /*!< Number of allocated PerfData entries. */
} PerfDataPrologue;
/*!
* \brief Entry of JVM performance informations.
*/
typedef struct {
jint entry_length; /*!< Entry length in bytes. */
jint name_offset; /*!< Offset of the data item name. */
jint vector_length; /*!< Length of the vector. If 0, then scalar. */
jbyte data_type; /*!< Type of the data item. -
'B','Z','J','I','S','C','D','F','V','L','[' */
jbyte flags; /*!< Flags indicating misc attributes. */
jbyte data_units; /*!< Unit of measure for the data type. */
jbyte data_variability; /*!< Variability classification of data type. */
jint data_offset; /*!< Offset of the data item. */
} PerfDataEntry;
/*!
* \brief Search entry of JVM performance informations in vmstruct.
*/
typedef struct {
const char *entryName; /*!< Entry name string. */
const char entryType; /*!< Entry type char. */
void **entryValue; /*!< Pointer of store variable. */
} VMStructSearchEntry;
/*!
* \brief Function type definition for JVM internal functions.<br>
* JVM_MaxMemory() / JVM_TotalMemory() / etc...
* \return Memory size.
*/
typedef jlong(JNICALL *TGetMemoryFunc)(void);
/*!
* \brief Value of gc cause when failure get GC cause.
*/
const static char UNKNOWN_GC_CAUSE[16]
__attribute__((aligned(16))) = "unknown GCCause";
/*!
* \brief Size of GC cause.
*/
const static int MAXSIZE_GC_CAUSE = 80;
/*!
* \brief This class is used to get JVM performance information.
*/
class TJvmInfo {
public:
/*!
* \brief TJvmInfo constructor.
*/
TJvmInfo(void);
/*!
* \brief TJvmInfo destructor.
*/
virtual ~TJvmInfo();
/*!
* \brief Get heap memory size (New + Old)
* through the JVM internal function.
* \return Heap memory size.
*/
inline jlong getMaxMemory(void) {
return (this->maxMemFunc == NULL) ? -1 : (*this->maxMemFunc)();
}
/*!
* \brief Get total allocated heap memory size.
* \return Heap memory size.
* \warning CAUTION!!: This function must be called
* after "VMInit" JVMTI event!<br>
* JVM_TotalMemory() is used "JavaThread" object.
*/
inline jlong getTotalMemory(void) {
return (this->totalMemFunc == NULL) ? -1 : (*this->totalMemFunc)();
}
/*!
* \brief Get new generation size.
* \return Size of new generation of heap.
*/
inline jlong getNewAreaSize(void) {
return (this->_edenSize != NULL && this->_sur0Size != NULL &&
this->_sur1Size != NULL)
? *this->_edenSize + *this->_sur0Size + *this->_sur1Size
: -1;
};
/*!
* \brief Get tenured generation size.
* \return Size of tenured generation of heap.
*/
inline jlong getOldAreaSize(void) {
return (this->_oldSize != NULL) ? *this->_oldSize : -1;
};
/*!
* \brief Get PermGen or Metaspace usage.
* \return Usage of PermGen or Metaspace.
*/
inline jlong getMetaspaceUsage(void) {
return (this->_metaspaceUsage != NULL) ? *this->_metaspaceUsage : -1;
};
/*!
* \brief Get PermGen or Metaspace capacity.
* \return Max capacity of PermGen or Metaspace.
*/
inline jlong getMetaspaceCapacity(void) {
return (this->_metaspaceCapacity != NULL) ? *this->_metaspaceCapacity : -1;
};
/*!
* \brief Get raised full-GC count.
* \return Raised full-GC count.
*/
inline jlong getFGCCount(void) {
return (this->_nowFGC != NULL) ? *this->_nowFGC : -1;
};
/*!
* \brief Get raised young-GC count.
* \return Raised young-GC count.
*/
inline jlong getYGCCount(void) {
return (this->_nowYGC != NULL) ? *this->_nowYGC : -1;
};
/*!
* \brief Load string of GC cause.
*/
void loadGCCause(void);
/*!
* \brief Reset stored gc information.
*/
inline void resumeGCinfo(void) {
/* Reset gc cause string. */
this->SetUnknownGCCause();
/* Refresh elapsed GC work time. */
elapFGCTime = (this->_FGCTime != NULL) ? *this->_FGCTime : -1;
elapYGCTime = (this->_YGCTime != NULL) ? *this->_YGCTime : -1;
/* Reset full-GC flag. */
this->fullgcFlag = false;
};
/*!
* \brief Get GC cause string.
* \return GC cause string.
*/
inline char *getGCCause(void) { return this->gcCause; };
/*!
* \brief Get last GC worktime(msec).
* \return Last GC work time.
*/
inline jlong getGCWorktime(void) {
jlong nowTime;
jlong result = 0;
/* Get time tick frequency. */
jlong freqTime = (this->_freqTime != NULL) ? (*this->_freqTime / 1000) : 1;
/* Check GC type. */
if (fullgcFlag) {
nowTime = (this->_FGCTime != NULL) ? *this->_FGCTime : 0;
result = (nowTime >= 0) ? nowTime - elapFGCTime : 0;
} else {
nowTime = (this->_YGCTime != NULL) ? *this->_YGCTime : 0;
result = (nowTime >= 0) ? nowTime - elapYGCTime : 0;
}
/* Calculate work time. */
return (result / freqTime);
};
/*!
* \brief Set full-GC flag.
* \param isFullGC [in] Is raised full-GC ?
*/
inline void setFullGCFlag(bool isFullGC) { this->fullgcFlag = isFullGC; }
/*!
* \brief Detect delayed GC-informaion address.
*/
void detectDelayInfoAddress(void);
/*!
* \brief Get finished conflict count.
* \return It's count of finished conflict of monitor.
*/
inline jlong getSyncPark(void) {
return ((_syncPark == NULL) ? -1 : *_syncPark);
}
/*!
* \brief Get live thread count.
* \return Now living thread count.
*/
inline jlong getThreadLive(void) {
return ((_threadLive == NULL) ? -1 : *_threadLive);
}
/*!
* \brief Get safepoint time.
* \return Total work time in safepoint.
*/
inline jlong getSafepointTime(void) {
/* Get time tick frequency. */
jlong freqTime = (this->_freqTime != NULL) ? (*this->_freqTime / 1000) : 1;
return ((_safePointTime == NULL) ? -1 : *_safePointTime / freqTime);
}
/*!
* \brief Get safepoint count.
* \return Count of work in safepoint.
*/
inline jlong getSafepoints(void) {
return ((_safePoints == NULL) ? -1 : *_safePoints);
}
/*!
* \brief Get JVM version.
* \return JVM version.
*/
inline char *getVmVersion(void) { return this->_vmVersion; }
/*!
* \brief Set JVM version from system property (java.vm.version) .
* \param jvmti [in] JVMTI Environment.
* \return Process result.
*/
bool setHSVersion(jvmtiEnv *jvmti);
/*!
* \brief Get JVM version as uint value.
*/
inline unsigned int getHSVersion(void) { return this->_hsVersion; }
/*!
* \brief Get JVM name.
* \return JVM name.
*/
inline char *getVmName(void) { return this->_vmName; }
/*!
* \brief Get JVM class path.
* \return JVM class path.
*/
inline char *getClassPath(void) { return this->_classPath; }
/*!
* \brief Get JVM endorsed path.
* \return JVM endorsed path.
*/
inline char *getEndorsedPath(void) { return this->_endorsedPath; }
/*!
* \brief Decision for JDK-7046558: G1: concurrent marking optimizations.
* https://bugs.openjdk.java.net/browse/JDK-7046558
* http://hg.openjdk.java.net/hsx/hotspot-gc/hotspot/rev/842b840e67db
*/
inline bool isAfterCR7046558(void) {
// hs22.0-b03
return (this->_hsVersion >= MAKE_HS_VERSION(0, 22, 0, 0, 3));
}
/*!
* \brief Decision for JDK-7017732: move static fields into Class to prepare
* for perm gen removal
* https://bugs.openjdk.java.net/browse/JDK-7017732
*/
inline bool isAfterCR7017732(void) {
// hs21.0-b06
return (this->_hsVersion >= MAKE_HS_VERSION(0, 21, 0, 0, 6));
}
/*!
* \brief Decision for JDK-6964458: Reimplement class meta-data storage to use
* native memory
* (PermGen Removal)
* https://bugs.openjdk.java.net/browse/JDK-6964458
* http://hg.openjdk.java.net/hsx/hotspot-rt-gate/hotspot/rev/da91efe96a93
*/
inline bool isAfterCR6964458(void) {
// hs25.0-b01
return (this->_hsVersion >= MAKE_HS_VERSION(0, 25, 0, 0, 1));
}
/*!
* \brief Decision for JDK-8000213: NPG: Should have renamed arrayKlass and
* typeArrayKlass
* https://bugs.openjdk.java.net/browse/JDK-8000213
* http://hg.openjdk.java.net/hsx/hotspot-rt/hotspot/rev/d8ce2825b193
*/
inline bool isAfterCR8000213(void) {
// hs25.0-b04
return (this->_hsVersion >= MAKE_HS_VERSION(0, 25, 0, 0, 4));
}
/*!
* \brief Decision for JDK-8027746: Remove do_gen_barrier template parameter
* in G1ParCopyClosure
* https://bugs.openjdk.java.net/browse/JDK-8027746
*/
inline bool isAfterCR8027746(void) {
// hs25.20-b02
return (this->_hsVersion >= MAKE_HS_VERSION(0, 25, 20, 0, 2));
}
/*!
* \brief Decision for JDK-8049421: G1 Class Unloading after completing a
* concurrent mark cycle
* https://bugs.openjdk.java.net/browse/JDK-8049421
* http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/rev/2c6ef90f030a
*/
inline bool isAfterCR8049421(void) {
// hs25.40-b05
return (this->_hsVersion >= MAKE_HS_VERSION(0, 25, 40, 0, 5));
}
/*!
* \brief Decision for JDK-8004883: NPG: clean up anonymous class fix
* https://bugs.openjdk.java.net/browse/JDK-8004883
*/
inline bool isAfterCR8004883(void) {
// hs25.0-b14
return (this->_hsVersion >= MAKE_HS_VERSION(0, 25, 0, 0, 14));
}
/*!
* \brief Decision for JDK-8003424: Enable Class Data Sharing for
* CompressedOops
* https://bugs.openjdk.java.net/browse/JDK-8003424
* http://hg.openjdk.java.net/hsx/hotspot-rt/hotspot/rev/740e263c80c6
*/
inline bool isAfterCR8003424(void) {
// hs25.0-b46
return (this->_hsVersion >= MAKE_HS_VERSION(0, 25, 0, 0, 46));
}
/*!
* \brief Decision for JDK-8015107: NPG: Use consistent naming for metaspace
* concepts
* https://bugs.openjdk.java.net/browse/JDK-8015107
*/
inline bool isAfterCR8015107(void) {
// hs25.0-b51
return (this->_hsVersion >= MAKE_HS_VERSION(0, 25, 0, 0, 51));
}
/*!
* \brief Running on JDK 9
*/
inline bool isAfterJDK9(void) {
return (this->_hsVersion >= MAKE_HS_VERSION(1, 9, 0, 0, 0));
}
/*!
* \brief Running on JDK 10 or later
*/
inline bool isAfterJDK10(void) {
return (this->_hsVersion >= MAKE_HS_VERSION(1, 10, 0, 0, 0));
}
/*!
* \brief Get Java version.
* \return Java version.
*/
inline char *getJavaVersion(void) { return this->_javaVersion; }
/*!
* \brief Get JAVA_HOME.
* \return JAVA_HOME.
*/
inline char *getJavaHome(void) { return this->_javaHome; }
/*!
* \brief Get JVM boot class path.
* \return JVM boot class path.
*/
inline char *getBootClassPath(void) { return this->_bootClassPath; }
/*!
* \brief Get JVM arguments.
* \return JVM arguments.
*/
inline char *getVmArgs(void) { return this->_vmArgs; }
/*!
* \brief Get JVM flags.
* \return JVM flags.
*/
inline char *getVmFlags(void) { return this->_vmFlags; }
/*!
* \brief Get Java application arguments.
* \return Java application arguments.
*/
inline char *getJavaCommand(void) { return this->_javaCommand; }
/*!
* \brief Get JVM running timetick.
* \return JVM running timetick.
*/
inline jlong getTickTime(void) {
/* Get time tick frequency. */
jlong freqTime = (this->_freqTime != NULL) ? (*this->_freqTime / 1000) : 1;
return ((_tickTime == NULL) ? -1 : *_tickTime / freqTime);
}
#ifdef USE_VMSTRUCTS
/*!
* \brief Detect GC-informaion address.<br>
* Use external VM structure.
* \sa "jdk/src/share/classes/sun/tools/jstat/resources/jstat_options"
*/
void detectInfoAddress(void);
#else
/*!
* \brief Detect GC-informaion address.<br>
* Use performance data file.
* \param env [in] JNI environment object.
* \sa "jdk/src/share/classes/sun/tools/jstat/resources/jstat_options"
*/
void detectInfoAddress(JNIEnv *env);
#endif
void SetUnknownGCCause(void);
protected:
/*!
* \brief Address of java.lang.getMaxMemory().
*/
TGetMemoryFunc maxMemFunc;
/*!
* \brief Address of java.lang.getTotalMemory().
*/
TGetMemoryFunc totalMemFunc;
#ifdef USE_VMSTRUCTS
/*!
* \brief Get JVM performance data address.<br>
* Use external VM structure.
* \return JVM performance data address.
*/
virtual ptrdiff_t getPerfMemoryAddress(void);
#else
/*!
* \brief Search JVM performance data address in memory.
* \param path [in] Path of hsperfdata.
* \return JVM performance data address.
*/
ptrdiff_t findPerfMemoryAddress(char *path);
/*!
* \brief Get JVM performance data address.<br>
* Use performance data file.
* \param env [in] JNI environment object.
* \return JVM performance data address.
*/
virtual ptrdiff_t getPerfMemoryAddress(JNIEnv *env);
#endif
/*!
* \brief Search GC-informaion address.
* \param entries [in,out] List of search target entries.
* \param count [in] Count of search target list.
*/
virtual void SearchInfoInVMStruct(VMStructSearchEntry *entries, int count);
private:
/*!
* \brief JVM running performance data pointer.
*/
ptrdiff_t perfAddr;
/*!
* \brief Now Full-GC count.
*/
jlong *_nowFGC;
/*!
* \brief Now Young-GC count.
*/
jlong *_nowYGC;
/*!
* \brief Now eden space size.
*/
jlong *_edenSize;
/*!
* \brief Now survivor 0 space size.
*/
jlong *_sur0Size;
/*!
* \brief Now survivor 1 space size.
*/
jlong *_sur1Size;
/*!
* \brief Tenured generation space size.
*/
jlong *_oldSize;
/*!
* \brief PermGen or Metaspace usage.
*/
jlong *_metaspaceUsage;
/*!
* \brief PermGen or Metaspace capacity.
*/
jlong *_metaspaceCapacity;
/*!
* \brief Total Full-GC work time.
*/
jlong *_FGCTime;
/*!
* \brief Total Young-GC work time.
*/
jlong *_YGCTime;
/*!
* \brief Elapsed Full-GC work time.
*/
jlong elapFGCTime;
/*!
* \brief Elapsed Young-GC work time.
*/
jlong elapYGCTime;
/*!
* \brief Frequency timetick.
*/
jlong *_freqTime;
/*!
* \brief GC cause.
*/
char *_gcCause;
/*!
* \brief Stored GC cause.
*/
char *gcCause;
/*!
* \brief Full-GC flag. Used by getGCWorktime().
*/
bool fullgcFlag;
/*!
* \brief Log data loaded flag.
*/
bool loadLogFlag;
/*!
* \brief Delay log data loaded flag.
*/
bool loadDelayLogFlag;
/*!
* \brief It's count of finished conflict of monitor.
*/
jlong *_syncPark;
/*!
* \brief Now living thread count.
*/
jlong *_threadLive;
/*!
* \brief Total work time in safepoint.
*/
jlong *_safePointTime;
/*!
* \brief Count of work in safepoint.
*/
jlong *_safePoints;
/*!
* \brief JVM version as uint
*/
unsigned int _hsVersion;
/*!
* \brief JVM version.
*/
char *_vmVersion;
/*!
* \brief JVM name.
*/
char *_vmName;
/*!
* \brief JVM class path.
*/
char *_classPath;
/*!
* \brief JVM endorsed path.
*/
char *_endorsedPath;
/*!
* \brief Java version.
*/
char *_javaVersion;
/*!
* \brief JAVA_HOME.
*/
char *_javaHome;
/*!
* \brief JVM boot class path.
*/
char *_bootClassPath;
/*!
* \brief JVM arguments.
*/
char *_vmArgs;
/*!
* \brief JVM flags.
*/
char *_vmFlags;
/*!
* \brief Java application arguments.
*/
char *_javaCommand;
/*!
* \brief JVM running timetick.
*/
jlong *_tickTime;
};
/* Include optimized inline functions. */
#ifdef AVX
#include "arch/x86/avx/jvmInfo.inline.hpp"
#elif defined(SSE4) || defined(SSE2)
#include "arch/x86/sse2/jvmInfo.inline.hpp"
#elif defined(NEON)
#include "arch/arm/neon/jvmInfo.inline.hpp"
#else
inline void TJvmInfo::loadGCCause(void) {
__builtin_memcpy(this->gcCause, this->_gcCause, MAXSIZE_GC_CAUSE);
};
inline void TJvmInfo::SetUnknownGCCause(void) {
__builtin_memcpy(this->gcCause, UNKNOWN_GC_CAUSE, 16);
}
#endif
#endif // JVMINFO_H
| 17,995
|
C++
|
.h
| 616
| 25.613636
| 86
| 0.636532
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,045
|
snapShotProcessor.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/snapShotProcessor.hpp
|
/*!
* \file snapShotProcessor.hpp
* \brief This file is used to output ranking and call snapshot function.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef SNAPSHOT_PROCESSOR_HPP
#define SNAPSHOT_PROCESSOR_HPP
#include <jvmti.h>
#include <jni.h>
#include "agentThread.hpp"
#include "snapShotContainer.hpp"
#include "classContainer.hpp"
/*!
* \brief This class control take snapshot and show ranking.
*/
class TSnapShotProcessor : public TAgentThread {
public:
/*!
* \brief TSnapShotProcessor constructor.
* \param clsContainer [in] Class container object.
* \param info [in] JVM running performance information.
*/
TSnapShotProcessor(TClassContainer *clsContainer, TJvmInfo *info);
/*!
* \brief TSnapShotProcessor destructor.
*/
virtual ~TSnapShotProcessor(void);
using TAgentThread::start;
/*!
* \brief Start parallel work by JThread.
* \param jvmti [in] JVMTI environment information.
* \param env [in] JNI environment information.
*/
void start(jvmtiEnv *jvmti, JNIEnv *env);
using TAgentThread::notify;
/*!
* \brief Notify output snapshot to this thread from other thread.
* \param snapshot [in] Output snapshot instance.
*/
virtual void notify(TSnapShotContainer *snapshot);
protected:
/*!
* \brief Parallel work function by JThread.
* \param jvmti [in] JVMTI environment information.
* \param jni [in] JNI environment information.
* \param data [in] Monitor-object for class-container.
*/
static void JNICALL entryPoint(jvmtiEnv *jvmti, JNIEnv *jni, void *data);
/*!
* \brief Show ranking.
* \param hdr [in] Snapshot file information.
* \param data [in] All class-data.
*/
virtual void showRanking(const TSnapShotFileHeader *hdr,
TSorter<THeapDelta> *data);
RELEASE_ONLY(private :)
/*!
* \brief Class counter container.
*/
TClassContainer *_container;
/*!
* \brief JVM running performance information.
*/
TJvmInfo *jvmInfo;
/*!
* \brief Unprocessed snapshot queue.
*/
TSnapShotQueue snapQueue;
};
#endif
| 2,856
|
C++
|
.h
| 85
| 30.352941
| 82
| 0.727141
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,046
|
libmain.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/libmain.hpp
|
/*!
* \file libmain.hpp
* \brief This file is used to common works.<br>
* e.g. initialization, finalization, etc...
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef LIBMAIN_HPP
#define LIBMAIN_HPP
/* Define export function for calling from external. */
extern "C" {
/*!
* \brief Agent attach entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Attach initialization result code.
*/
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved);
/*!
* \brief Common agent unload entry points.
* \param vm [in] JavaVM object.
*/
JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *vm);
/*!
* \brief Ondemand attach's entry points.
* \param vm [in] JavaVM object.
* \param options [in] Commandline arguments.
* \param reserved [in] Reserved.
* \return Ondemand-attach initialization result code.
*/
JNIEXPORT jint JNICALL
Agent_OnAttach(JavaVM *vm, char *options, void *reserved);
};
/*!
* \brief Abort JVM by force on illegal status.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param causeMsg [in] Message about cause of aborting JVM.
* \warning This function is always no return.
*/
void forcedAbortJVM(jvmtiEnv *jvmti, JNIEnv *env, const char *causeMsg);
#endif // LIBMAIN_HPP
| 2,183
|
C++
|
.h
| 57
| 35.631579
| 82
| 0.71934
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,047
|
sorter.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/sorter.hpp
|
/*!
* \file sorter.hpp
* \brief This file is used sorting class datas.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef SORTER_HPP
#define SORTER_HPP
/*!
* \brief This structure use stored sorting data.
*/
template <typename T>
struct Node {
struct Node<T> *prev; /*!< Previoue node data. */
struct Node<T> *next; /*!< Next node data. */
T value; /*!< Pointer of sort target. */
};
/*!
* \brief Comparator for TSorter.
* \param arg1 [in] Target of comparison.
* \param arg2 [in] Target of comparison.
* \return Difference of arg1 and arg2.
*/
typedef int (*TComparator)(const void *arg1, const void *arg2);
/*!
* \brief This class is used sorting data defined by <T>.
*/
template <typename T>
class TSorter {
private:
/*!
* \brief Max sorted data count.
*/
int _max;
/*!
* \brief Now tree having node count.<br>
* This value is never large more than '_max'.<br>
* Tree will remove smallest data in everytime,
* if add many data to tree beyond limit.
*/
int _nowIdx;
/*!
* \brief Sorter holding objects.
*/
struct Node<T> *container;
/*!
* \brief The node is held node first.
*/
struct Node<T> *_top;
/*!
* \brief Comparator used by tree.
*/
TComparator cmp;
public:
/*!
* \brief TSorter constructor.
* \param max [in] Max array size.
* \param comparator [in] Comparator used compare sorting data.
*/
TSorter(int max, TComparator comparator)
: _max(max), _nowIdx(-1), _top(NULL), cmp(comparator) {
/* Allocate sort array. */
this->container = new struct Node<T>[this->_max];
}
/*!
* \brief TSorter destructor.
*/
virtual ~TSorter() {
/* Free allcated array. */
delete[] this->container;
}
/*!
* \brief Add data that need sorting.
* \param val [in] add target data.
*/
virtual void push(T val) {
struct Node<T> *tmpTop, *newNode;
/* If count is less than 1. */
if (unlikely(this->_max <= 0)) {
return;
}
/* Push data. */
if (this->_nowIdx < (this->_max - 1)) {
/* If count of holding element is smaller than array size. */
this->_nowIdx++;
this->container[this->_nowIdx].prev = NULL;
this->container[this->_nowIdx].next = NULL;
this->container[this->_nowIdx].value = val;
/* If holds none. */
if (this->_nowIdx == 0) {
this->_top = this->container;
return;
}
tmpTop = this->_top;
newNode = &this->container[this->_nowIdx];
} else if ((*this->cmp)(&this->_top->value, &val) < 0) {
/* If added element is bigger than smallest element in array. */
/* If holds only 1 element. */
if (this->_top->next == NULL) {
this->_top->value = val;
return;
}
/* Setting element. */
tmpTop = this->_top->next;
tmpTop->prev = NULL;
this->_top->prev = NULL;
this->_top->next = NULL;
this->_top->value = val;
newNode = this->_top;
this->_top = tmpTop;
} else {
/* If don't need to refresh array. */
return;
}
/* Rebuild node array. */
struct Node<T> *tmpNode = tmpTop;
while (true) {
/* Compare element in array. */
if ((*this->cmp)(&newNode->value, &tmpNode->value) < 0) {
/* If added element is smaller than certain element in array. */
/* Setting chain. */
newNode->prev = tmpNode->prev;
newNode->next = tmpNode;
tmpNode->prev = newNode;
/* If first node. */
if (newNode->prev == NULL) {
this->_top = newNode;
} else {
newNode->prev->next = newNode;
}
return;
} else if (tmpNode->next == NULL) {
/* If added element is bigger than biggest element in array. */
/* Insert top. */
tmpNode->next = newNode;
newNode->prev = tmpNode;
return;
} else {
/* If added element is bigger than a certain element in array. */
/* Move next element. */
tmpNode = tmpNode->next;
}
}
}
/*!
* \brief Get sorted first data.
* \return Head object in sorted array.
*/
inline struct Node<T> *topNode(void) { return this->_top; };
/*!
* \brief Get sorted last data.
* \return Last object in sorted array.
*/
inline struct Node<T> *lastNode(void) {
/* Get array head. */
struct Node<T> *node = this->_top;
/* If array is empty. */
if (node == NULL) {
return NULL;
}
/* Move to last. */
while (node->next != NULL) {
node = node->next;
}
/* Return last node. */
return node;
}
/*!
* \brief Get count of element in array.
* \return element count.
*/
inline int
getCount(void) {
return _nowIdx + 1;
}
};
#endif // SORTER
| 5,587
|
C++
|
.h
| 191
| 24.481675
| 82
| 0.601826
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,048
|
timer.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/timer.hpp
|
/*!
* \file timer.hpp
* \brief This file is used to take interval snapshot.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef TIMER_HPP
#define TIMER_HPP
#include <semaphore.h>
#include "util.hpp"
#include "agentThread.hpp"
/*!
* \brief This type is callback to periodic calling by timer.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Cause of invoke function.<br>Maybe "Interval".
*/
typedef void (*TTimerEventFunc)(jvmtiEnv *jvmti, JNIEnv *env,
TInvokeCause cause);
/*!
* \brief This class is used to take interval snapshot.
*/
class TTimer : public TAgentThread {
public:
/*!
* \brief TTimer constructor.
* \param event [in] Callback is used by interval calling.
* \param timerName [in] Unique name of timer.
*/
TTimer(TTimerEventFunc event, const char *timerName);
/*!
* \brief TTimer destructor.
*/
virtual ~TTimer(void);
using TAgentThread::start;
/*!
* \brief Make and begin Jthread.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param interval [in] Interval of invoke timer event.
*/
void start(jvmtiEnv *jvmti, JNIEnv *env, jlong interval);
/*!
* \brief Notify reset timing to this thread from other thread.
*/
void notify(void);
/*!
* \brief Notify stop to this thread from other thread.
*/
void stop(void);
protected:
/*!
* \brief JThread entry point called by interval or nofity.
* \param jvmti [in] JVMTI environment object.
* \param jni [in] JNI environment object.
* \param data [in] Pointer of TTimer.
*/
static void JNICALL entryPoint(jvmtiEnv *jvmti, JNIEnv *jni, void *data);
/*!
* \brief JThread entry point called by notify only.
* \param jvmti [in] JVMTI environment object.
* \param jni [in] JNI environment object.
* \param data [in] Pointer of TTimer.
*/
static void JNICALL
entryPointByCall(jvmtiEnv *jvmti, JNIEnv *jni, void *data);
/*!
* \brief Callback for periodic calling by timer.
*/
TTimerEventFunc _eventFunc;
/*!
* \brief Interval of timer.
*/
jlong timerInterval;
/*!
* \brief Timer interrupt flag.
*/
volatile bool _isInterrupted;
/*!
* \brief Timer semphore.
*/
sem_t timerSem;
};
#endif
| 3,113
|
C++
|
.h
| 98
| 28.479592
| 82
| 0.700533
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,049
|
archiveMaker.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/archiveMaker.hpp
|
/*!
* \file archiveMaker.hpp
* \brief This file is used create archive file.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _ARCHIVE_MAKER_H
#define _ARCHIVE_MAKER_H
#include <jvmti.h>
#include <jni.h>
#include <limits.h>
/*!
* \brief This class create archive file.
*/
class TArchiveMaker {
public:
/*!
* \brief TArchiveMaker constructor.
*/
TArchiveMaker(void);
/*!
* \brief TArchiveMaker destructor.
*/
virtual ~TArchiveMaker(void);
/*!
* \brief Setting target file path.
* \param targetPath [in] Path of archive target file.
*/
void setTarget(char const* targetPath);
/*!
* \brief Do file archive and create archive file.
* \param env [in] JNI environment object.
* \param archiveFile [in] archive file name.
* \return Response code of execute commad line.
*/
virtual int doArchive(JNIEnv* env, char const* archiveFile) = 0;
/*!
* \brief Clear archive file data.
*/
void clear(void);
protected:
/*!
* \brief Getting target file path.
* \return Path of archive target file.
*/
char const* getTarget(void);
private:
/*!
* \brief Path of archive source file.
*/
char sourcePath[PATH_MAX + 1];
};
#endif // _ARCHIVE_MAKER_H
| 1,995
|
C++
|
.h
| 67
| 27
| 82
| 0.712722
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,050
|
overrider.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/overrider.hpp
|
/*!
* \file overrider.hpp
* \brief Controller of overriding functions in HotSpot VM.
* Copyright (C) 2014-2018 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef OVERRIDER_H
#define OVERRIDER_H
#include <stddef.h>
/*!
* \brief Override function information structure.
*/
typedef struct {
const char *vtableSymbol; /*!< Symbol string of target class. */
void **vtable; /*!< Pointer of C++ vtable. */
const char *funcSymbol; /*!< Symbol string of target function. */
void *overrideFunc; /*!< Pointer of override function. */
void *originalFunc; /*!< Original callback target. */
void **originalFuncPtr; /*!< Pointer of original callback target. */
void *enterFunc; /*!< Enter event for hook target. */
void **enterFuncPtr; /*!< Pointer of enter event for hook target. */
bool isVTableWritable; /*!< Is vtable already writable? */
} THookFunctionInfo;
/*!
* \brief This structure is expressing garbage collector state.
*/
typedef enum {
gcStart = 1, /*!< Garbage collector is start. */
gcFinish = 2, /*!< Garbage collector is finished. */
gcLast = 3, /*!< Garbage collector is tarminating on JVM death. */
} TGCState;
/* Variable for CMS collector state. */
/*!
* \brief CMS collector is idling.
*/
#define CMS_IDLING 2
/*!
* \brief CMS collector is initial-marking phase.
*/
#define CMS_INITIALMARKING 3
/*!
* \brief CMS collector is marking phase.
*/
#define CMS_MARKING 4
/*!
* \brief CMS collector is final-making phase.
*/
#define CMS_FINALMARKING 7
/*!
* \brief CMS collector is sweep phase.
*/
#define CMS_SWEEPING 8
/* Macro to define overriding functions. */
/*!
* \brief Convert to THookFunctionInfo macro.
*/
#define HOOK_FUNC(prefix, num, vtableSym, funcSym, enterFunc) \
{ \
vtableSym, NULL, funcSym, &prefix##_override_func_##num, NULL, \
&prefix##_original_func_##num, (void *)enterFunc, \
&prefix##_enter_hook_##num, false \
}
/*!
* \brief Enf flag for THookFunctionInfo macro.
*/
#define HOOK_FUNC_END \
{ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, false }
#define DEFINE_OVERRIDE_FUNC_N(prefix, num) \
extern "C" void *prefix##_override_func_##num; \
extern "C" { \
void *prefix##_original_func_##num; \
void *prefix##_enter_hook_##num; \
};
#define DEFINE_OVERRIDE_FUNC_1(prefix) DEFINE_OVERRIDE_FUNC_N(prefix, 0)
#define DEFINE_OVERRIDE_FUNC_2(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1)
#define DEFINE_OVERRIDE_FUNC_3(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2)
#define DEFINE_OVERRIDE_FUNC_4(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3)
#define DEFINE_OVERRIDE_FUNC_5(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3) \
DEFINE_OVERRIDE_FUNC_N(prefix, 4)
#define DEFINE_OVERRIDE_FUNC_7(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3) \
DEFINE_OVERRIDE_FUNC_N(prefix, 4) \
DEFINE_OVERRIDE_FUNC_N(prefix, 5) \
DEFINE_OVERRIDE_FUNC_N(prefix, 6)
#define DEFINE_OVERRIDE_FUNC_8(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3) \
DEFINE_OVERRIDE_FUNC_N(prefix, 4) \
DEFINE_OVERRIDE_FUNC_N(prefix, 5) \
DEFINE_OVERRIDE_FUNC_N(prefix, 6) \
DEFINE_OVERRIDE_FUNC_N(prefix, 7)
#define DEFINE_OVERRIDE_FUNC_9(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3) \
DEFINE_OVERRIDE_FUNC_N(prefix, 4) \
DEFINE_OVERRIDE_FUNC_N(prefix, 5) \
DEFINE_OVERRIDE_FUNC_N(prefix, 6) \
DEFINE_OVERRIDE_FUNC_N(prefix, 7) \
DEFINE_OVERRIDE_FUNC_N(prefix, 8)
#define DEFINE_OVERRIDE_FUNC_11(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3) \
DEFINE_OVERRIDE_FUNC_N(prefix, 4) \
DEFINE_OVERRIDE_FUNC_N(prefix, 5) \
DEFINE_OVERRIDE_FUNC_N(prefix, 6) \
DEFINE_OVERRIDE_FUNC_N(prefix, 7) \
DEFINE_OVERRIDE_FUNC_N(prefix, 8) \
DEFINE_OVERRIDE_FUNC_N(prefix, 9) \
DEFINE_OVERRIDE_FUNC_N(prefix, 10)
#define DEFINE_OVERRIDE_FUNC_12(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3) \
DEFINE_OVERRIDE_FUNC_N(prefix, 4) \
DEFINE_OVERRIDE_FUNC_N(prefix, 5) \
DEFINE_OVERRIDE_FUNC_N(prefix, 6) \
DEFINE_OVERRIDE_FUNC_N(prefix, 7) \
DEFINE_OVERRIDE_FUNC_N(prefix, 8) \
DEFINE_OVERRIDE_FUNC_N(prefix, 9) \
DEFINE_OVERRIDE_FUNC_N(prefix, 10) \
DEFINE_OVERRIDE_FUNC_N(prefix, 11)
#define DEFINE_OVERRIDE_FUNC_19(prefix) \
DEFINE_OVERRIDE_FUNC_N(prefix, 0) \
DEFINE_OVERRIDE_FUNC_N(prefix, 1) \
DEFINE_OVERRIDE_FUNC_N(prefix, 2) \
DEFINE_OVERRIDE_FUNC_N(prefix, 3) \
DEFINE_OVERRIDE_FUNC_N(prefix, 4) \
DEFINE_OVERRIDE_FUNC_N(prefix, 5) \
DEFINE_OVERRIDE_FUNC_N(prefix, 6) \
DEFINE_OVERRIDE_FUNC_N(prefix, 7) \
DEFINE_OVERRIDE_FUNC_N(prefix, 8) \
DEFINE_OVERRIDE_FUNC_N(prefix, 9) \
DEFINE_OVERRIDE_FUNC_N(prefix, 10) \
DEFINE_OVERRIDE_FUNC_N(prefix, 11) \
DEFINE_OVERRIDE_FUNC_N(prefix, 12) \
DEFINE_OVERRIDE_FUNC_N(prefix, 13) \
DEFINE_OVERRIDE_FUNC_N(prefix, 14) \
DEFINE_OVERRIDE_FUNC_N(prefix, 15) \
DEFINE_OVERRIDE_FUNC_N(prefix, 16) \
DEFINE_OVERRIDE_FUNC_N(prefix, 17) \
DEFINE_OVERRIDE_FUNC_N(prefix, 18)
/*!
* \brief Macro to select override function with CR.
*/
#define SELECT_HOOK_FUNCS(prefix) \
if (jvmInfo->isAfterJDK10()) { \
prefix##_hook = jdk10_##prefix##_hook; \
} else if (jvmInfo->isAfterJDK9()) { \
prefix##_hook = jdk9_##prefix##_hook; \
} else if (jvmInfo->isAfterCR8049421()) { \
prefix##_hook = CR8049421_##prefix##_hook; \
} else if (jvmInfo->isAfterCR8027746()) { \
prefix##_hook = CR8027746_##prefix##_hook; \
} else if (jvmInfo->isAfterCR8000213()) { \
prefix##_hook = CR8000213_##prefix##_hook; \
} else if (jvmInfo->isAfterCR6964458()) { \
prefix##_hook = CR6964458_##prefix##_hook; \
} else { \
prefix##_hook = default_##prefix##_hook; \
}
/* Macro for deciding class type. */
/*!
* \brief Header macro for array array class. Chars of "[[".
*/
#define HEADER_KLASS_ARRAY_ARRAY 0x5b5b
/*!
* \brief Header macro for object array class. Chars of "[L".
*/
#ifdef WORDS_BIGENDIAN
#define HEADER_KLASS_OBJ_ARRAY 0x5b4c
#else
#define HEADER_KLASS_OBJ_ARRAY 0x4c5b
#endif
/*!
* \brief Header macro for array class. Chars of "[".
*/
#define HEADER_KLASS_ARRAY 0x5b
/* Callback function type. */
/*!
* \brief This function is for heap object callback.
* \param oop [in] Java heap object(Inner class format).
* \param data [in] User expected data. Always this value is NULL.
*/
typedef void (*THeapObjectCallback)(void *oop, void *data);
/*!
* \brief This function is for class oop adjust callback by GC.
* \param oldOop [in] Old pointer of java class object(KlassOopDesc).
* \param newOop [in] New pointer of java class object(KlassOopDesc).
*/
typedef void (*TKlassAdjustCallback)(void *oldOop, void *newOop);
/*!
* \brief This function type is for common callback.
*/
typedef void (*TCommonCallback)(void);
/*!
* \brief This function is for get classloader.<br>
* E.g. instanceKlass::class_loader()<br>
* objArrayKlass::class_loader()<br>
* \param klassOop [in] Pointer of java class object(KlassOopDesc).
* \return Java heap object which is class loader load expected the class.
*/
typedef void *(*TGetClassLoader)(void *klassOop);
/* extern functions (for overriding) */
extern "C" void callbackForParallel(void *oop);
extern "C" void callbackForParallelWithMarkCheck(void *oop);
extern "C" void callbackForParOld(void *oop);
extern "C" void callbackForDoOop(void **oop);
extern "C" void callbackForDoOopWithMarkCheck(void **oop);
extern "C" void callbackForDoNarrowOop(unsigned int *narrowOop);
extern "C" void callbackForDoNarrowOopWithMarkCheck(unsigned int *narrowOop);
extern "C" void callbackForIterate(void *oop);
extern "C" void callbackForSweep(void *oop);
extern "C" void callbackForAdjustPtr(void *oop);
extern "C" void callbackForDoAddr(void *oop);
extern "C" void callbackForUpdatePtr(void *oop);
extern "C" void callbackForJvmtiIterate(void *oop);
extern "C" void callbackForG1Cleanup(void *thisptr);
extern "C" void callbackForG1Full(void *thisptr);
extern "C" void callbackForG1FullReturn(void *thisptr);
extern "C" void callbackForInnerGCStart(void);
extern "C" void callbackForWatcherThreadRun(void);
/* Functions to be provided from this file. */
/*!
* \brief Initialize override functions.
* \return Process result.
*/
bool initOverrider(void);
/*!
* \brief Cleanup override functions.
*/
void cleanupOverrider(void);
/*!
* \brief Setup hooking.
* \warning Please this function call at after Agent_OnLoad.
* \param funcOnGC [in] Pointer of GC callback function.
* \param funcOnCMS [in] Pointer of CMSGC callback function.
* \param funcOnJVMTI [in] Pointer of JVMTI callback function.
* \param funcOnAdjust [in] Pointer of adjust class callback function.
* \param funcOnG1GC [in] Pointer of event callback on G1GC finished.
* \param maxMemSize [in] Allocatable maximum memory size of JVM.
* \return Process result.
*/
bool setupHook(THeapObjectCallback funcOnGC, THeapObjectCallback funcOnCMS,
THeapObjectCallback funcOnJVMTI,
TKlassAdjustCallback funcOnAdjust, TCommonCallback funcOnG1GC,
size_t maxMemSize);
/*!
* \brief Setup hooking for inner GC event.
* \warning Please this function call at after Agent_OnLoad.
* \param enableHook [in] Flag of enable hooking to function.
* \param interruptEvent [in] Event callback on many times GC interupt.
* \return Process result.
*/
bool setupHookForInnerGCEvent(bool enableHook, TCommonCallback interruptEvent);
/*!
* \brief Setup override funtion.
* \param list [in] List of hooking information.
* \return Process result.
*/
bool setupOverrideFunction(THookFunctionInfo *list);
/*!
* \brief Setting GC hooking enable.
* \param enable [in] Is GC hook enable.
* \return Process result.
*/
bool setGCHookState(bool enable);
/*!
* \brief Setting JVMTI hooking enable.
* \param enable [in] Is JVMTI hook enable.
* \return Process result.
*/
bool setJvmtiHookState(bool enable);
/*!
* \brief Switching override function enable state.
* \param list [in] List of hooking information.
* \param enable [in] Enable of override function.
* \return Process result.
*/
bool switchOverrideFunction(THookFunctionInfo *list, bool enable);
/*!
* \brief Check CMS garbage collector state.
* \param state [in] State of CMS garbage collector.
* \param needSnapShot [out] Is need snapshot now.
* \return CMS collector state.
* \warning Please don't forget call on JVM death.
*/
int checkCMSState(TGCState state, bool *needSnapShot);
#endif // OVERRIDER_H
| 12,716
|
C++
|
.h
| 325
| 36.695385
| 82
| 0.68187
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,051
|
signalManager.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/signalManager.hpp
|
/*!
* \file signalManager.hpp
* \brief This file is used by signal handling.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _SIGNAL_MNGR_H
#define _SIGNAL_MNGR_H
#include <jni.h>
#include <signal.h>
#include "util.hpp"
/*!
* \brief This type is signal callback by TSignalManager.
* \param signo [in] Number of received signal.
* \param siginfo [in] Informantion of received signal.<br>
* But this value is always null.
* \param data [in] Data of received signal.<br>
* But this value is always null.
* \warning Function must be signal-safe.
*/
typedef void (*TSignalHandler)(int signo, siginfo_t *siginfo, void *data);
typedef struct structSignalHandlerChain {
TSignalHandler handler;
structSignalHandlerChain *next;
} TSignalHandlerChain;
typedef struct {
int sig;
const char *name;
} TSignalMap;
/*!
* \brief This class is handling signal.
*/
class TSignalManager {
private:
/*!
* \brief Signal number for this instance.
*/
int signal;
/*!
* \brief SR_Handler in HotSpot VM
*/
static TSignalHandler SR_Handler;
public:
/*!
* \brief Find signal number from name.
* \param sig Signal name.
* \return Signal number. Return -1 if not found.
*/
static int findSignal(const char *sig);
/*!
* \brief TSignalManager constructor.
* \param sig Signal string.
*/
TSignalManager(const char *sig);
/*!
* \brief TSignalManager destructor.
*/
virtual ~TSignalManager(void);
/*!
* \brief Add signal handler.
* \param handler [in] Function pointer for signal handler.
* \return true if new signal handler is added.
*/
bool addHandler(TSignalHandler handler);
};
#endif // _SIGNAL_MNGR_H
| 2,550
|
C++
|
.h
| 80
| 28.5125
| 82
| 0.699389
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,052
|
elapsedTimer.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/elapsedTimer.hpp
|
/*!
* \file elapsedTimer.hpp
* \brief This file is used to measure elapsed time.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef ELAPSED_TIMER_H
#define ELAPSED_TIMER_H
#include <sys/times.h>
/*!
* \brief This class measure elapsed time by processed working.
*/
class TElapsedTimer {
public:
/*!
* \brief TElapsedTimer's clock frequency.<br>
* Please set this value from external.<br>
* e.g. "sysconf(_SC_CLK_TCK)"
*/
static long clock_ticks;
/*!
* \brief TElapsedTimer constructor.
* \param label [in] Working process name.
*/
TElapsedTimer(const char *label) {
/* Stored process start time. */
this->_start_clock = times(&this->_start_tms);
this->_label = label;
}
/*!
* \brief TElapsedTimer destructor.
*/
~TElapsedTimer() {
/* Get process end time. */
struct tms _end_tms;
clock_t _end_clock = times(&_end_tms);
if (this->_label != NULL) {
logger->printInfoMsg(
"Elapsed Time (in %s): %f sec (user = %f, sys = %f)", this->_label,
this->calcClockToSec(this->_start_clock, _end_clock),
this->calcClockToSec(this->_start_tms.tms_utime, _end_tms.tms_utime),
this->calcClockToSec(this->_start_tms.tms_stime, _end_tms.tms_stime));
} else {
logger->printInfoMsg(
"Elapsed Time: %f sec (user = %f, sys = %f)",
this->calcClockToSec(this->_start_clock, _end_clock),
this->calcClockToSec(this->_start_tms.tms_utime, _end_tms.tms_utime),
this->calcClockToSec(this->_start_tms.tms_stime, _end_tms.tms_stime));
}
}
private:
/*!
* \brief Working process name.
*/
const char *_label;
/*!
* \brief Process start simple time.
*/
clock_t _start_clock;
/*!
* \brief Process start detail time.
*/
struct tms _start_tms;
/*!
* \brief Calculate time between start and end.
* \param start [in] Time of process begin.
* \param end [in] Time of process finished.
* \return Elapsed time.
*/
inline double calcClockToSec(const clock_t start, const clock_t end) {
return (double)(end - start) / (double)clock_ticks;
}
};
#endif
| 2,919
|
C++
|
.h
| 88
| 29.238636
| 82
| 0.667966
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,053
|
logger.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/logger.hpp
|
/*!
* \file logger.hpp
* \brief Logger class to stdout/err .
* Copyright (C) 2014-2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef LOGGER_HPP
#define LOGGER_HPP
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include "util.hpp"
/*!
* \brief Logging Level.
*/
typedef enum {
CRIT = 1,
/*!< Level for FATAL error log. This's displayed by all means. */
WARN = 2,
/*!< Level for runnable error log. e.g. Heap-Alert */
INFO = 3,
/*!< Level for normal info log. e.g. Heap-Ranking */
DEBUG = 4
/*!< Level for debug info log. */
} TLogLevel;
class TLogger {
private:
FILE *out;
FILE *err;
TLogLevel logLevel;
/*!
* \brief Print message to stream.
* \param stream: Output stream.
* \param header: Message header. This value should be loglevel.
* \param isNewLine: If this value sets to true, this function will add
* newline character at end of message.
* \param format: String format to print.
* \param ap: va_list for "format".
*/
inline void printMessageInternal(FILE *stream, const char *header,
bool isNewLine, const char *format,
va_list ap) {
fprintf(stream, "heapstats %s: ", header);
vfprintf(stream, format, ap);
if (isNewLine) {
fputc('\n', stream);
}
}
public:
TLogger() : logLevel(INFO) {
out = stdout;
err = stderr;
}
TLogger(TLogLevel level) : logLevel(level) {
out = stdout;
err = stderr;
}
virtual ~TLogger() {
flush();
if (out != stdout && out != NULL) {
fclose(out);
}
}
/*!
* \brief Flush stdout and stderr.
*/
inline void flush() {
fflush(out);
if (err != out) {
fflush(err);
}
}
/*!
* \brief Setter of logLevel.
* \param level: Log level.
*/
inline void setLogLevel(TLogLevel level) { this->logLevel = level; }
/*!
* \brief Setter for logFile.
* \param logfile: Console log filename.
*/
inline void setLogFile(char *logfile) {
if (logfile != NULL && strlen(logfile) != 0) {
out = fopen(logfile, "a");
if (unlikely(out == NULL)) {
// If cannot open file.
this->printWarnMsgWithErrno(
"Could not open console log file: %s. Agent always output to "
"console.",
logfile);
out = stdout;
} else {
err = out;
}
}
}
/*!
* \brief Print critical error message.
* This function treats arguments as printf(3).
*/
inline void printCritMsg(const char *format, ...) {
if (this->logLevel >= CRIT) {
va_list ap;
va_start(ap, format);
this->printMessageInternal(err, "CRIT", true, format, ap);
va_end(ap);
}
}
/*!
* \brief Print warning error message.
* This function treats arguments as printf(3).
*/
inline void printWarnMsg(const char *format, ...) {
if (this->logLevel >= WARN) {
va_list ap;
va_start(ap, format);
this->printMessageInternal(err, "WARN", true, format, ap);
va_end(ap);
}
}
/*!
* \brief Print warning error message with current errno.
* This function treats arguments as printf(3).
*/
inline void printWarnMsgWithErrno(const char *format, ...) {
if (this->logLevel >= WARN) {
char error_string[1024];
char *output_message = strerror_wrapper(error_string, 1024);
va_list ap;
va_start(ap, format);
this->printMessageInternal(err, "WARN", false, format, ap);
va_end(ap);
fprintf(err, " cause: %s\n", output_message);
}
}
/*!
* \brief Print information message.
* This function treats arguments as printf(3).
*/
inline void printInfoMsg(const char *format, ...) {
if (this->logLevel >= INFO) {
va_list ap;
va_start(ap, format);
this->printMessageInternal(out, "INFO", true, format, ap);
va_end(ap);
}
}
/*!
* \brief Print debug message.
* This function treats arguments as printf(3).
*/
inline void printDebugMsg(const char *format, ...) {
if (this->logLevel >= DEBUG) {
va_list ap;
va_start(ap, format);
this->printMessageInternal(out, "DEBUG", true, format, ap);
va_end(ap);
}
}
};
#endif // LOGGER_HPP
| 5,125
|
C++
|
.h
| 177
| 24.327684
| 82
| 0.61359
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,054
|
globals.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/globals.hpp
|
/*!
* \file globals.hpp
* \brief Definitions of global variables.
* Copyright (C) 2015-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef GLOBALS_HPP
#define GLOBALS_HPP
#include <pthread.h>
#include "jvmInfo.hpp"
extern TJvmInfo *jvmInfo;
#include "configuration.hpp"
extern TConfiguration *conf;
#include "logger.hpp"
extern TLogger *logger;
#include "signalManager.hpp"
extern TSignalManager *reloadSigMngr;
extern TSignalManager *logSignalMngr;
extern TSignalManager *logAllSignalMngr;
#include "timer.hpp"
extern TTimer *intervalSigTimer;
extern TTimer *logTimer;
extern TTimer *timer;
#include "symbolFinder.hpp"
extern TSymbolFinder *symFinder;
#include "vmStructScanner.hpp"
extern TVMStructScanner *vmScanner;
#include "logManager.hpp"
extern TLogManager *logManager;
#include "classContainer.hpp"
extern TClassContainer *clsContainer;
#include "snapShotProcessor.hpp"
extern TSnapShotProcessor *snapShotProcessor;
#include "gcWatcher.hpp"
extern TGCWatcher *gcWatcher;
/*!
* \brief Mutex of working directory.
*/
extern pthread_mutex_t directoryMutex;
/*!
* \brief Page size got from sysconf.
*/
extern long systemPageSize;
#endif // GLOBALS_HPP
| 1,888
|
C++
|
.h
| 58
| 30.87931
| 82
| 0.796031
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,055
|
heapstatsMBean.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/heapstatsMBean.hpp
|
/*!
* \file heapstatsMBean.hpp
* \brief JNI implementation for HeapStatsMBean.
* Copyright (C) 2014-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef HEAPSTATSMBEAN_HPP
#define HEAPSTATSMBEAN_HPP
#include <jni.h>
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL RegisterHeapStatsNative(JNIEnv *env, jclass cls);
JNIEXPORT jstring JNICALL GetHeapStatsVersion(JNIEnv *env, jobject obj);
JNIEXPORT jobject JNICALL
GetConfiguration(JNIEnv *env, jobject obj, jstring key);
JNIEXPORT jobject JNICALL GetConfigurationList(JNIEnv *env, jobject obj);
JNIEXPORT jboolean JNICALL
ChangeConfiguration(JNIEnv *env, jobject obj, jstring key, jobject value);
JNIEXPORT jboolean JNICALL InvokeLogCollection(JNIEnv *env, jobject obj);
JNIEXPORT jboolean JNICALL InvokeAllLogCollection(JNIEnv *env, jobject obj);
#ifdef __cplusplus
}
#endif
void UnregisterHeapStatsNatives(JNIEnv *env);
#endif // HEAPSTATSMBEAN_HPP
| 1,657
|
C++
|
.h
| 40
| 39.125
| 82
| 0.783851
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,056
|
oopUtil.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/oopUtil.hpp
|
/*!
* \file oopUtil.hpp
* \brief This file is used to getting information inner JVM.<br>
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _OOP_UTIL_H
#define _OOP_UTIL_H
#include "overrider.hpp"
#include "vmVariables.hpp"
/*!
* \brief This structure is expressing java heap object type.
*/
typedef enum {
otIllegal = 0, /*!< The Object is unknown class type. */
otInstance = 1, /*!< The Object is object instance class. */
otArray = 2, /*!< The Object is single array class. */
otObjArarry = 3, /*!< The Object is object array class. */
otArrayArray = 4, /*!< The Object is multi array class. */
} TOopType;
/*!
* \brief This structure is inner "OopMapBlock" class stub.<br/>
* This struct is used by get following class information.
* \sa hotspot/src/share/vm/oops/instanceKlass.hpp
*/
typedef struct {
int offset; /*!< Byte offset of the first oop mapped. */
unsigned int count; /*!< Count of oops mapped in this block. */
} TOopMapBlock;
/* Function for init/final. */
/*!
* \brief Initialization of this util.
* \param jvmti [in] JVMTI environment object.
* \return Process result.
*/
bool oopUtilInitialize(jvmtiEnv *jvmti);
/*!
* \brief Finailization of this util.
*/
void oopUtilFinalize(void);
/* Function for oop util. */
/*!
* \brief Getting oop's class information(It's "Klass", not "KlassOop").
* \param klassOop [in] Java heap object(Inner "KlassOop" class).
* \return Class information object(Inner "Klass" class).
*/
void *getKlassFromKlassOop(void *klassOop);
/*!
* \brief Getting oop's class information(It's "Klass", not "KlassOop").
* \param oop [in] Java heap object(Inner class format).
* \return Class information object.
* \sa oopDesc::klass()<br>
* at hotspot/src/share/vm/oops/oop.inline.hpp in JDK.
*/
void *getKlassOopFromOop(void *oop);
/*!
* \brief Getting class's name form java inner class.
* \param klass [in] Java class object(Inner class format).
* \return String of object class name.<br>
* Don't forget deallocate if value isn't null.
*/
char *getClassName(void *klass);
/*!
* \brief Get class loader that loaded expected class as KlassOop.
* \param klassName [in] String of target class name (JNI class format).
* \return Java heap object which is class loader load expected the class.
*/
TOopType getClassType(const char *klassName);
/*!
* \brief Get class loader that loaded expected class as KlassOop.
* \param klassOop [in] Class information object(Inner "Klass" class).
* \param type [in] KlassOop type.
* \return Java heap object which is class loader load expected the class.
*/
void *getClassLoader(void *klassOop, const TOopType type);
/*!
* \brief Generate oop field offset cache.
* \param klassOop [in] Target class object(klassOop format).
* \param oopType [in] Type of inner "Klass" type.
* \param offsets [out] Field offset array.<br />
* Please don't forget deallocate this value.
* \param count [out] Count of field offset array.
*/
void generateIterateFieldOffsets(void *klassOop, TOopType oopType,
TOopMapBlock **offsets, int *count);
/*!
* \brief Iterate oop's field oops.
* \param event [in] Callback function.
* \param oop [in] Itearate target object(OopDesc format).
* \param oopType [in] Type of oop's class.
* \param ofsData [in,out] Cache data for iterate oop fields.<br />
* If value is null, then create and set cache data.
* \param ofsDataSize [in,out] Cache data count.<br />
* If value is null, then set count of "ofsData".
* \param data [in,out] User expected data for callback.
*/
void iterateFieldObject(THeapObjectCallback event, void *oop, TOopType oopType,
TOopMapBlock **ofsData, int *ofsDataSize, void *data);
/* Function for other. */
/*!
* \brief Convert COOP(narrowOop) to wide Oop(normally Oop).
* \param narrowOop [in] Java heap object(compressed format Oop).
* \return Wide OopDesc object.
*/
inline void *getWideOop(unsigned int narrowOop) {
TVMVariables *vmVal = TVMVariables::getInstance();
/*
* narrow oop decoding is defined in
* inline oop oopDesc::decode_heap_oop_not_null(narrowOop v)
* hotspot/src/share/vm/oops/oop.inline.hpp
*/
return (void *)(vmVal->getNarrowOffsetBase() +
((ptrdiff_t)narrowOop << vmVal->getNarrowOffsetShift()));
}
/*!
* \brief Get oop forward address.
* \param oop [in] Java heap object.
* \return Wide OopDesc object.
*/
inline void *getForwardAddr(void *oop) {
TVMVariables *vmVal = TVMVariables::getInstance();
/* Sanity check. */
if (unlikely(oop == NULL)) {
return NULL;
}
/* Get OopDesc::_mark field. */
ptrdiff_t markOop = *(ptrdiff_t *)incAddress(oop, vmVal->getOfsMarkAtOop());
return (void *)(markOop & ~vmVal->getLockMaskInPlaceMarkOop());
}
/*!
* \brief Get oop field exists.
* \return Does oop have oop field.
*/
inline bool hasOopField(const TOopType oopType) {
return (oopType == otInstance || oopType == otObjArarry);
}
#endif // _OOP_UTIL_H
| 5,929
|
C++
|
.h
| 151
| 36.715232
| 82
| 0.693952
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,057
|
jniCallbackRegister.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/jniCallbackRegister.hpp
|
/*!
* \file jniCallbackRegister.hpp
* \brief Handling JNI function callback.
* Copyright (C) 2015-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef JNI_CALLBACK_REGISTER_HPP
#define JNI_CALLBACK_REGISTER_HPP
#include <jvmti.h>
#include <jni.h>
#include <pthread.h>
#include <list>
/* Type definition for JNI functions. */
typedef void (*TJVM_Sleep)(JNIEnv *env, jclass threadClass, jlong millis);
typedef void (*TUnsafe_Park)(JNIEnv *env, jobject unsafe, jboolean isAbsolute,
jlong time);
/* Import functions from libjvm.so */
extern "C" void JVM_Sleep(JNIEnv *env, jclass threadClass, jlong millis);
/*!
* \brief Base class of callback for JNI functions.
*/
template <typename T>
class TJNICallbackRegister {
protected:
/*!
* \brief Callback function list before calling JNI function.
*/
static std::list<T> prologueCallbackList;
/*!
* \brief Callback function list after calling JNI function.
*/
static std::list<T> epilogueCallbackList;
/*!
* \brief Read-Write lock for callback container.
*/
static pthread_rwlock_t callbackLock;
public:
/*!
* \brief Register callbacks for JNI function.
*
* \param prologue [in] Callback before calling JNI function.
* \param epilogue [in] Callback after calling JNI function.
*/
static void registerCallback(T prologue, T epilogue) {
pthread_rwlock_wrlock(&callbackLock);
{
if (prologue != NULL) {
prologueCallbackList.push_back(prologue);
}
if (epilogue != NULL) {
epilogueCallbackList.push_back(epilogue);
}
}
pthread_rwlock_unlock(&callbackLock);
};
/*!
* \brief Unegister callbacks for JNI function.
*
* \param prologue [in] Callback before calling JNI function.
* \param epilogue [in] Callback after calling JNI function.
*/
static void unregisterCallback(T prologue, T epilogue) {
pthread_rwlock_wrlock(&callbackLock);
{
if (prologue != NULL) {
#ifdef USE_N2350
// C++11 support
auto prologue_begin = prologueCallbackList.cbegin();
auto prologue_end = prologueCallbackList.cend();
#else
auto prologue_begin = prologueCallbackList.begin();
auto prologue_end = prologueCallbackList.end();
#endif
for (auto itr = prologue_begin; itr != prologue_end; itr++) {
if (prologue == *itr) {
prologueCallbackList.erase(itr);
break;
}
}
}
if (epilogue != NULL) {
#ifdef USE_N2350
// C++11 support
auto epilogue_begin = prologueCallbackList.cbegin();
auto epilogue_end = prologueCallbackList.cend();
#else
auto epilogue_begin = prologueCallbackList.begin();
auto epilogue_end = prologueCallbackList.end();
#endif
for (auto itr = epilogue_begin; itr != epilogue_end; itr++) {
if (epilogue == *itr) {
epilogueCallbackList.erase(itr);
break;
}
}
}
}
pthread_rwlock_unlock(&callbackLock);
};
};
/*!
* \brief JNI callbacks for prologue.
*/
template <typename T>
std::list<T> TJNICallbackRegister<T>::prologueCallbackList;
/*!
* \brief JNI callbacks for epilogue.
*/
template <typename T>
std::list<T> TJNICallbackRegister<T>::epilogueCallbackList;
/*!
* \brief Read-Write lock for callback container.
*/
template <typename T>
pthread_rwlock_t TJNICallbackRegister<T>::callbackLock =
PTHREAD_RWLOCK_INITIALIZER;
#define ITERATE_JNI_CALLBACK_CHAIN(type, originalFunc, ...) \
std::list<type>::iterator itr; \
\
pthread_rwlock_rdlock(&callbackLock); \
{ \
for (itr = prologueCallbackList.begin(); \
itr != prologueCallbackList.end(); itr++) { \
(*itr)(__VA_ARGS__); \
} \
} \
pthread_rwlock_unlock(&callbackLock); \
\
originalFunc(__VA_ARGS__); \
\
pthread_rwlock_rdlock(&callbackLock); \
{ \
for (itr = epilogueCallbackList.begin(); \
itr != epilogueCallbackList.end(); itr++) { \
(*itr)(__VA_ARGS__); \
} \
} \
pthread_rwlock_unlock(&callbackLock);
/*!
* \brief JVM_Sleep callback (java.lang.System#sleep())
*/
class TJVMSleepCallback : public TJNICallbackRegister<TJVM_Sleep> {
public:
static void JNICALL
callbackStub(JNIEnv *env, jclass threadClass, jlong millis){
ITERATE_JNI_CALLBACK_CHAIN(TJVM_Sleep, JVM_Sleep, env, threadClass,
millis)};
static bool switchCallback(JNIEnv *env, bool isEnable) {
jclass threadClass = env->FindClass("java/lang/Thread");
JNINativeMethod sleepMethod;
sleepMethod.name = (char *)"sleep";
sleepMethod.signature = (char *)"(J)V";
sleepMethod.fnPtr = isEnable ? (void *)&callbackStub : (void *)&JVM_Sleep;
return (env->RegisterNatives(threadClass, &sleepMethod, 1) == 0);
}
};
/*!
* \brief Unsafe_Park callback (sun.misc.Unsafe#park())
*/
class TUnsafeParkCallback : public TJNICallbackRegister<TUnsafe_Park> {
public:
static void JNICALL callbackStub(JNIEnv *env, jobject unsafe,
jboolean isAbsolute, jlong time){
ITERATE_JNI_CALLBACK_CHAIN(TUnsafe_Park,
TVMFunctions::getInstance()->Unsafe_Park, env,
unsafe, isAbsolute, time)};
static bool switchCallback(JNIEnv *env, bool isEnable) {
jclass unsafeClass = env->FindClass("sun/misc/Unsafe");
JNINativeMethod parkMethod;
parkMethod.name = (char *)"park";
parkMethod.signature = (char *)"(ZJ)V";
parkMethod.fnPtr =
isEnable ? (void *)&callbackStub
: TVMFunctions::getInstance()->GetUnsafe_ParkPointer();
return (env->RegisterNatives(unsafeClass, &parkMethod, 1) == 0);
}
};
#endif // JNI_CALLBACK_REGISTER_HPP
| 7,645
|
C++
|
.h
| 192
| 33.354167
| 82
| 0.567793
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,058
|
jniZipArchiver.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/jniZipArchiver.hpp
|
/*!
* \file jniZipArchiver.hpp
* \brief This file is used create archive file to use java zip library.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _JNI_ZIP_ARCHIVER_H
#define _JNI_ZIP_ARCHIVER_H
#include <jvmti.h>
#include <jni.h>
#include "archiveMaker.hpp"
/*!
* \brief This class create archive file.
*/
class TJniZipArchiver : public TArchiveMaker {
public:
/*!
* \brief TJniZipArchiver constructor.
*/
TJniZipArchiver(void);
/*!
* \brief TJniZipArchiver destructor.
*/
~TJniZipArchiver(void);
/*!
* \brief Do file archive and create archive file.
* \param env [in] JNI environment object.
* \param archiveFile [in] archive file name.
* \return Response code of execute commad line.
*/
int doArchive(JNIEnv* env, char const* archiveFile);
/*!
* \brief Global initialization.
* \param env [in] JNI environment object.
* \return Process is succeed, if value is true.<br>
* Process is failure, if value is false.
* \warning Please call only once from main thread.
*/
static bool globalInitialize(JNIEnv* env);
/*!
* \brief Global finalize.
* \param env [in] JNI environment object.
* \return Process is succeed, if value is true.<br>
* Process is failure, if value is false.
* \warning Please call only once from main thread.
*/
static bool globalFinalize(JNIEnv* env);
protected:
/*!
* \brief Execute archive.
* \param env [in] JNI environment object.
* \param archiveFile [in] archive file name.
* \return Response code of execute archive.
*/
virtual int execute(JNIEnv* env, char const* archiveFile);
/*!
* \brief Write files to archive.
* \param env [in] JNI environment object.
* \param jZipStream [in] JNI zip archive stream object.
* \return Response code of execute archive.
*/
virtual int writeFiles(JNIEnv* env, jobject jZipStream);
private:
/*!
* \brief Refference of "BufferedOutputStream" class data.
*/
static jclass clsBuffOutStrm;
/*!
* \brief Refference of "BufferedOutputStream" class constructer.
*/
static jmethodID clsBuffOutStrm_init;
/*!
* \brief Refference of "FileOutputStream" class data.
*/
static jclass clsFileOutStrm;
/*!
* \brief Refference of "FileOutputStream" class constructer.
*/
static jmethodID clsFileOutStrm_init;
/*!
* \brief Refference of "ZipOutputStream" class data.
*/
static jclass clsZipOutStrm;
/*!
* \brief Refference of "ZipOutputStream" class constructer.
*/
static jmethodID clsZipOutStrm_init;
/*!
* \brief Refference of "ZipEntry" class data.
*/
static jclass clsZipEntry;
/*!
* \brief Refference of "ZipEntry" class constructer.
*/
static jmethodID clsZipEntry_init;
/*!
* \brief Refference of "ZipOutputStream" class method "close".
*/
static jmethodID clsZipOutStrm_close;
/*!
* \brief Refference of "ZipOutputStream" class method "closeEntry".
*/
static jmethodID clsZipOutStrm_closeEntry;
/*!
* \brief Refference of "ZipOutputStream" class method "putNextEntry".
*/
static jmethodID clsZipOutStrm_putNextEntry;
/*!
* \brief Refference of "ZipOutputStream" class method "write".
*/
static jmethodID clsZipOutStrm_write;
/*!
* \brief Refference of "ZipOutputStream" class method "flush".
* \sa FilterOutputStream::flush
*/
static jmethodID clsZipOutStrm_flush;
/*!
* \brief Flag of load initialize data.
*/
static bool loadFlag;
};
#endif // _JNI_ZIP_ARCHIVER_H
| 4,318
|
C++
|
.h
| 136
| 28.455882
| 82
| 0.7114
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,059
|
logManager.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/logManager.hpp
|
/*!
* \file logManager.hpp
* \brief This file is used collect log information.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _LOG_MANAGER_H
#define _LOG_MANAGER_H
#include <queue>
#include "cmdArchiver.hpp"
#include "jniZipArchiver.hpp"
#include "jvmSockCmd.hpp"
#include "jvmInfo.hpp"
#include "util.hpp"
/*!
* \brief This structure is used to get and store machine cpu time.
*/
typedef struct {
TLargeUInt usrTime; /*!< Time used by user work. */
TLargeUInt lowUsrTime; /*!< Time used by user work under low priority. */
TLargeUInt sysTime; /*!< Time used by kernel work. */
TLargeUInt idleTime; /*!< Time used by waiting task work. */
TLargeUInt iowaitTime; /*!< Time used by waiting IO work. */
TLargeUInt sortIrqTime; /*!< Time used by sort intercept work. */
TLargeUInt irqTime; /*!< Time used by intercept work. */
TLargeUInt stealTime; /*!< Time used by other OS. */
TLargeUInt guestTime; /*!< Time used by guest OS under kernel control. */
} TMachineTimes;
/*!
* \brief This class collect and make log.
*/
class TLogManager {
public:
/*!
* \brief TLogManager constructor.
* \param env [in] JNI environment object.
* \param info [in] JVM running performance information.
*/
TLogManager(JNIEnv *env, TJvmInfo *info);
/*!
* \brief TLogManager destructor.
*/
virtual ~TLogManager(void);
/*!
* \brief Collect log.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Invoke function cause.<br>
* E.g. ResourceExhausted, Signal, Interval.
* \param nowTime [in] Log collect time.
* \param description [in] Description of the event.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int collectLog(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause,
TMSecTime nowTime, const char *description);
protected:
/*!
* \brief Collect normal log.
* \param cause [in] Invoke function cause.<br>
* E.g. ResourceExhausted, Signal, Interval.
* \param nowTime [in] Log collect time.
* \param archivePath [in] Archive file path.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int collectNormalLog(TInvokeCause cause, TMSecTime nowTime,
char *archivePath);
/*!
* \brief Collect all log.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Invoke function cause.<br>
* E.g. ResourceExhausted, Signal, Interval.
* \param nowTime [in] Log collect time.
* \param archivePath [out] Archive file path.
* \param pathLen [in] Max size of paramter"archivePath".
* \param description [in] Description of the event.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int collectAllLog(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause,
TMSecTime nowTime, char *archivePath,
size_t pathLen, const char *description);
RELEASE_ONLY(private :)
/*!
* \brief Create file about JVM running environment.
* \param basePath [in] Path of directory put report file.
* \param cause [in] Invoke function cause.<br>
* E.g. Signal, ResourceExhausted, Interval.
* \param nowTime [in] Log collect time.
* \param description [in] Description of the event.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int makeEnvironFile(char *basePath, TInvokeCause cause,
TMSecTime nowTime, const char *description);
/*!
* \brief Dump thread and stack information to stream.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param fd [in] Output file descriptor.
* \param stackInfo [in] Stack frame of java thread.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int dumpThreadInformation(jvmtiEnv *jvmti, JNIEnv *env, int fd,
jvmtiStackInfo stackInfo);
/*!
* \brief Create thread dump with JVMTI.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param filename [in] Path of thread dump file.
* \param nowTime [in] Log collect time.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int makeJvmtiThreadDump(jvmtiEnv *jvmti, JNIEnv *env, char *filename,
TMSecTime nowTime);
/*!
* \brief Create thread dump file.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param basePath [in] Path of directory put report file.
* \param cause [in] Invoke function cause.<br>
* E.g. Signal, ResourceExhausted, Interval.
* \param nowTime [in] Log collect time.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int makeThreadDumpFile(jvmtiEnv *jvmti, JNIEnv *env, char *basePath,
TInvokeCause cause, TMSecTime nowTime);
/*!
* \brief Getting java process information.
* \param systime [out] System used cpu time in java process.
* \param usrtime [out] User and java used cpu time in java process.
* \param vmsize [out] Virtual memory size of java process.
* \param rssize [out] Memory size of java process on main memory.
* \return Prosess is succeed or failure.
*/
virtual bool getProcInfo(TLargeUInt *systime, TLargeUInt *usrtime,
TLargeUInt *vmsize, TLargeUInt *rssize);
/*!
* \brief Getting machine cpu times.
* \param times [out] Machine cpu times information.
* \return Prosess is succeed or failure.
*/
virtual bool getSysTimes(TMachineTimes *times);
/*!
* \brief Send log archive trap.
* \param cause [in] Invoke function cause.<br>
* E.g. Signal, ResourceExhausted, Interval.
* \param nowTime [in] Log collect time.
* \param path [in] Archive file or directory path.
* \param isDirectory [in] Param "path" is directory.
* \return Value is true, if process is succeed.
*/
virtual bool sendLogArchiveTrap(TInvokeCause cause, TMSecTime nowTime,
char *path, bool isDirectory);
/*!
* \brief Collect files about JVM enviroment.
* \param basePath [in] Temporary working directory.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int copyInfoFiles(char const *basePath);
/*!
* \brief Copy GC log file.
* \param basePath [in] Path of temporary directory.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int copyGCLogFile(char const *basePath);
/*!
* \brief Create file about using socket by JVM.
* \param basePath [in] Path of directory put report file.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int makeSocketOwnerFile(char const *basePath);
/*!
* \brief Create archive file path.
* \param nowTime [in] Log collect time.
* \return Return archive file name, if process is succeed.<br>
* Don't forget deallocate memory.<br>
* Process is failure, if value is null.
*/
virtual char *createArchiveName(TMSecTime nowTime);
/*!
* \brief Mutex of collect normal log.
*/
static pthread_mutex_t logMutex;
/*!
* \brief Mutex of archive file.
*/
static pthread_mutex_t archiveMutex;
/*!
* \brief Archive file maker.
*/
TCmdArchiver *arcMaker;
/*!
* \brief Archive file maker to use zip library in java.
*/
TJniZipArchiver *jniArchiver;
/*!
* \brief Dump thread information object.
*/
TJVMSockCmd *jvmCmd;
/*!
* \brief JVM running performance information.
*/
TJvmInfo *jvmInfo;
/*!
* \brief Pointer of string of GC log file path.
*/
char **gcLogFilename;
};
#endif // _LOG_MANAGER_H
| 9,682
|
C++
|
.h
| 232
| 37.116379
| 82
| 0.648233
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,060
|
cmdArchiver.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/cmdArchiver.hpp
|
/*!
* \file cmdArchiver.hpp
* \brief This file is used create archive file by command line.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _CMD_ARCHIVER_H
#define _CMD_ARCHIVER_H
#include "archiveMaker.hpp"
#include "cmdArchiver.hpp"
/*!
* \brief This class create archive file.
*/
class TCmdArchiver : public TArchiveMaker {
public:
/*!
* \brief TCmdArchiver constructor.
*/
TCmdArchiver(void);
/*!
* \brief TCmdArchiver destructor.
*/
~TCmdArchiver(void);
/*!
* \brief Do file archive and create archive file.
* \param env [in] JNI environment object.
* \param archiveFile [in] archive file name.
* \return Process result code of create archive.
*/
int doArchive(JNIEnv *env, char const *archiveFile);
protected:
/*!
* \brief Convert string separated by space to string array.
* \param str [in] Separated string by space.
* \return Arrayed string.<br>Don't forget deallocate.<br>
* Value is null, if process failure or param is illegal.
*/
char **strToArray(char *str);
/*!
* \brief Execute command line.
* \param cmdline [in] String of execute command.
* \return Response code of execute commad line.
*/
virtual int execute(char *cmdline);
};
#endif // _CMD_ARCHIVER_H
| 2,035
|
C++
|
.h
| 60
| 31.2
| 82
| 0.721686
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,061
|
vmFunctions.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/vmFunctions.hpp
|
/*!
* \file vmFunctions.hpp
* \brief This file includes functions in HotSpot VM.
* Copyright (C) 2014-2018 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef VMFUNCTIONS_H
#define VMVARIABLES_H
#include <jni.h>
#include "symbolFinder.hpp"
/* Macros for symbol */
/*!
* \brief String of symbol which is "is_in_permanent" function on parallel GC.
*/
#define IS_IN_PERM_ON_PARALLEL_GC_SYMBOL \
"_ZNK20ParallelScavengeHeap15is_in_permanentEPKv"
/*!
* \brief String of symbol which is "is_in_permanent" function on other GC.
*/
#define IS_IN_PERM_ON_OTHER_GC_SYMBOL "_ZNK10SharedHeap15is_in_permanentEPKv"
/*!
* \brief Symbol of Generation::is_in()
*/
#define IS_IN_SYMBOL "_ZNK10Generation5is_inEPKv"
/*!
* \brief Symbol of "JvmtiEnv::GetObjectSize" macro.
*/
#ifdef __x86_64__
#define SYMBOL_GETOBJCTSIZE "_ZN8JvmtiEnv13GetObjectSizeEP8_jobjectPl"
#else
#define SYMBOL_GETOBJCTSIZE "_ZN8JvmtiEnv13GetObjectSizeEP8_jobjectPx"
#endif
/*!
* \brief String of symbol which is "java.lang.Class.as_klassOop" function.
*/
#define AS_KLASSOOP_SYMBOL "_ZN15java_lang_Class11as_klassOopEP7oopDesc"
/*!
* \brief String of symbol which is "java.lang.Class.as_klass" function.<br />
* This function is for after CR6964458.
*/
#define AS_KLASS_SYMBOL "_ZN15java_lang_Class8as_KlassEP7oopDesc"
/*!
* \brief String of symbol which is function get class loader for instance.
*/
#define GET_CLSLOADER_FOR_INSTANCE_SYMBOL "_ZNK13instanceKlass12class_loaderEv"
/*!
* \brief String of symbol which is function get class loader for instance
* after CR#8004883.
*/
#define CR8004883_GET_CLSLOADER_FOR_INSTANCE_SYMBOL \
"_ZNK13InstanceKlass12klass_holderEv"
/*!
* \brief String of symbol which is function get class loader for object array.
*/
#define GET_CLSLOADER_FOR_OBJARY_SYMBOL "_ZNK13objArrayKlass12class_loaderEv"
/*!
* \brief String of symbol which is function get class loader for object array
* after CR#8004883.
*/
#define CR8004883_GET_CLSLOADER_FOR_OBJARY_SYMBOL "_ZNK5Klass12klass_holderEv"
/*!
* \brief Symbol of java_lang_Thread::thread_id()
*/
#define GET_THREAD_ID_SYMBOL "_ZN16java_lang_Thread9thread_idEP7oopDesc"
/*!
* \brief Symbol of Unsafe_Park()
*/
#define UNSAFE_PARK_SYMBOL "Unsafe_Park"
/*!
* \brief Symbol of get_thread()
*/
#define GET_THREAD_SYMBOL "get_thread"
/*!
* \brief Symbol of ThreadLocalStorage::thread()
*/
#define THREADLOCALSTORAGE_THREAD_SYMBOL "_ZN18ThreadLocalStorage6threadEv"
/*!
* \brief Symbol of UserHandler()
*/
#define USERHANDLER_SYMBOL "_ZL11UserHandleriPvS_"
#define USERHANDLER_SYMBOL_JDK6 "_Z11UserHandleriPvS_"
/*!
* \brief Symbol of SR_handler()
*/
#define SR_HANDLER_SYMBOL "_ZL10SR_handleriP7siginfoP8ucontext"
/*
* Adapt to rename siginfo to siginfo_t
* https://sourceware.org/git/?p=glibc.git;a=commit;h=87df4a4b09abdb1b1af41c9c398b86ecdedcb635
*/
#define SR_HANDLER_SYMBOL_FALLBACK "_ZL10SR_handleriP9siginfo_tP8ucontext"
/*
* Adapt to old C++ compiler
* (Sun/Oracle JDK 6 FCS, etc)
*/
#define SR_HANDLER_SYMBOL_JDK6 "_Z10SR_handleriP7siginfoP8ucontext"
/*
* Adapt to rename ucontext to ucontext_t
* https://sourceware.org/bugzilla/show_bug.cgi?id=21457
*/
#define SR_HANDLER_SYMBOL_FALLBACK2 "_ZL10SR_handleriP9siginfo_tP10ucontext_t"
/*!
* \brief Symbol of ThreadSafepointState::create().
*/
#define THREADSAFEPOINTSTATE_CREATE_SYMBOL \
"_ZN20ThreadSafepointState6createEP10JavaThread"
/*!
* \brief Symbol of ThreadSafepointState::destroy().
*/
#define THREADSAFEPOINTSTATE_DESTROY_SYMBOL \
"_ZN20ThreadSafepointState7destroyEP10JavaThread"
/*!
* \brief Symbol of Monitor::lock().
*/
#define MONITOR_LOCK_SYMBOL "_ZN7Monitor4lockEv"
/*!
* \brief Symbol of Monitor::lock_without_safepoint_check().
*/
#define MONITOR_LOCK_WTIHOUT_SAFEPOINT_CHECK_SYMBOL \
"_ZN7Monitor28lock_without_safepoint_checkEv"
/*!
* \brief Symbol of Monitor::unlock().
*/
#define MONITOR_UNLOCK_SYMBOL "_ZN7Monitor6unlockEv"
/*!
* \brief Symbol of Monitor::owned_by_self().
*/
#define MONITOR_OWNED_BY_SELF_SYMBOL "_ZNK7Monitor13owned_by_selfEv"
/* Function type definition */
/*!
* \brief This function is C++ heap class member.<br>
* So 1st arg must be set instance.
* \param thisptr [in] Instance of Java memory region.
* \param oop [in] Java object.
* \return true if oop is in this region.
*/
typedef bool (*THeap_IsIn)(const void *thisptr, const void *oop);
/*!
* \brief This function is C++ JvmtiEnv class member.<br>
* So 1st arg must be set instance.<br>
* jvmtiError JvmtiEnv::GetObjectSize(jobject object, jlong* size_ptr)
* \param thisptr [in] JvmtiEnv object instance.
* \param object [in] Java object.
* \param size_ptr [out] Pointer of java object's size.
* \return Java object's size.
*/
typedef int (*TJvmtiEnv_GetObjectSize)(void *thisptr, jobject object,
jlong *size_ptr);
/*!
* \brief This function is java_lang_Class class member.<br>
* void *java_lang_Class::as_klassOop(void *mirror);
* \param mirror [in] Java object mirror.
* \return KlassOop of java object mirror.
*/
typedef void *(*TJavaLangClass_AsKlassOop)(void *mirror);
/*!
* \brief This function is for get classloader.<br>
* E.g. instanceKlass::class_loader()<br>
* objArrayKlass::class_loader()<br>
* \param klassOop [in] Pointer of java class object(KlassOopDesc).
* \return Java heap object which is class loader load expected the class.
*/
typedef void *(*TGetClassLoader)(void *klassOop);
/*!
* \brief Get thread ID (Thread#getId()) from oop.
* \param oop [in] oop of java.lang.Thread .
* \return Thread ID
*/
typedef jlong (*TGetThreadId)(void *oop);
/*!
* \brief Get JavaThread from oop.
* \param oop [in] oop of java.lang.Thread .
* \return Pointer of JavaThread
*/
typedef void *(*TGetThread)(void *oop);
/*!
* \brief JNI function of sun.misc.Unsafe#park() .
* \param env [in] JNI environment.
* \param unsafe [in] Unsafe object.
* \param isAbsolute [in] absolute.
* \param time [in] Park time.
*/
typedef void (*TUnsafe_Park)(JNIEnv *env, jobject unsafe, jboolean isAbsolute,
jlong time);
/*!
* \brief JNI function of sun.misc.Unsafe#park() .
* \param env [in] JNI environment.
* \param unsafe [in] Unsafe object.
* \param isAbsolute [in] absolute.
* \param time [in] Park time.
*/
typedef void (*TUnsafe_Park)(JNIEnv *env, jobject unsafe, jboolean isAbsolute,
jlong time);
/*!
* \brief Get C++ Thread instance.
* \return C++ Thread instance of this thread context.
*/
typedef void *(*TGet_thread)();
/*!
* \brief User signal handler for HotSpot.
* \param sig Signal number.
* \param siginfo Signal information.
* \param context Thread context.
*/
typedef void (*TUserHandler)(int sig, void *siginfo, void *context);
/*!
* \brief Thread suspend/resume signal handler in HotSpot.
* \param sig Signal number.
* \param siginfo Signal information.
* \param context Thread context.
*/
typedef void (*TSR_Handler)(int sig, siginfo_t *siginfo, ucontext_t *context);
/*!
* \brief function type of common thread operation.
* \param thread [in] Target thread object is inner JVM class instance.
*/
typedef void (*TVMThreadFunction)(void *thread);
/*!
* \brief function type of common monitor operation.
* \param monitor_oop [in] Target monitor oop.
*/
typedef void (*TVMMonitorFunction)(void *monitor_oop);
/*!
* \brief function type of common monitor operation.
* \param monitor_oop [in] Target monitor oop.
* \return Thread is owned monitor.
*/
typedef bool (*TOwnedBySelf)(void *monitor_oop);
/* Exported function in libjvm.so */
extern "C" void *JVM_RegisterSignal(jint sig, void *handler);
/* extern variables */
extern "C" void *VTableForTypeArrayOopClosure[2];
extern "C" THeap_IsIn is_in_permanent;
/*!
* \brief This class gathers/provides functions in HotSpot VM.
*/
class TVMFunctions {
private:
/*!
* \brief Function pointer for "JvmtiEnv::GetObjectSize".
*/
TJvmtiEnv_GetObjectSize getObjectSize;
/*!
* \brief Function pointer for "Generation::is_in".
*/
THeap_IsIn is_in;
/*!
* \brief Function pointer for "java_lang_Class::as_klassOop".
*/
TJavaLangClass_AsKlassOop asKlassOop;
/*!
* \brief Function pointer for "instanceKlass::class_loader()".
*/
TGetClassLoader getClassLoaderForInstanceKlass;
/*!
* \brief Function pointer for "objArrayKlass::class_loader()".
*/
TGetClassLoader getClassLoaderForObjArrayKlass;
/*!
* \brief Function pointer for "java_lang_Thread::thread_id()".
*/
TGetThreadId getThreadId;
/*!
* \brief Function pointer for "Unsafe_Park()".
*/
TUnsafe_Park unsafePark;
/*!
* \brief Function pointer for "get_thread()".
*/
TGet_thread get_thread;
/*!
* \brief Function pointer for "UserHandler".
*/
TUserHandler userHandler;
/*!
* \brief Function pointer for "SR_handler".
*/
TSR_Handler sr_handler;
/*!
* \brief Function pointer for "ThreadSafepointState::create()".
*/
TVMThreadFunction threadSafepointStateCreate;
/*!
* \brief Function pointer for "ThreadSafepointState::destroy()".
*/
TVMThreadFunction threadSafepointStateDestroy;
/*!
* \brief Function pointer for "Monitor::lock()"
*/
TVMMonitorFunction monitor_lock;
/*!
* \brief Function pointer for "Monitor::lock_without_safepoint_check()".
*/
TVMMonitorFunction monitor_lock_without_safepoint_check;
/*!
* \brief Function pointer for "Monitor::unlock()".
*/
TVMMonitorFunction monitor_unlock;
/*!
* \brief Function pointer for "Monitor::owned_by_self()".
*/
TOwnedBySelf monitor_owned_by_self;
/* Class of HeapStats for scanning variables in HotSpot VM */
TSymbolFinder *symFinder;
/*!
* \brief Singleton instance of TVMFunctions.
*/
static TVMFunctions *inst;
protected:
/*!
* \brief Get HotSpot functions through symbol table.
* \return Result of this function.
*/
bool getFunctionsFromSymbol(void);
/*!
* \brief Get vtable through symbol table which is related to G1.
* \return Result of this function.
*/
bool getG1VTableFromSymbol(void);
public:
/*
* Constructor of TVMFunctions.
* \param sym [in] Symbol finder of libjvm.so .
*/
TVMFunctions(TSymbolFinder *sym) : symFinder(sym){};
/*!
* \brief Instance initializer.
* \param sym [in] Symbol finder of libjvm.so .
* \return Singleton instance of TVMFunctions.
*/
static TVMFunctions *initialize(TSymbolFinder *sym);
/*!
* \brief Get singleton instance of TVMFunctions.
* \return Singleton instance of TVMFunctions.
*/
static TVMFunctions *getInstance() { return inst; };
/* Delegators to HotSpot VM */
inline int GetObjectSize(void *thisptr, jobject object, jlong *size_ptr) {
return getObjectSize(thisptr, object, size_ptr);
}
inline bool IsInYoung(const void *oop) {
return is_in(TVMVariables::getInstance()->getYoungGen(), oop);
}
inline void *AsKlassOop(void *mirror) { return asKlassOop(mirror); }
inline void *GetClassLoaderForInstanceKlass(void *klassOop) {
return getClassLoaderForInstanceKlass(klassOop);
}
inline void *GetClassLoaderForObjArrayKlass(void *klassOop) {
return getClassLoaderForObjArrayKlass(klassOop);
}
inline jlong GetThreadId(void *oop) { return getThreadId(oop); }
inline void Unsafe_Park(JNIEnv *env, jobject unsafe, jboolean isAbsolute,
jlong time) {
return unsafePark(env, unsafe, isAbsolute, time);
}
inline void *GetUnsafe_ParkPointer(void) { return (void *)unsafePark; }
inline void *GetThread(void) {
return get_thread();
}
inline void *GetUserHandlerPointer(void) { return (void *)userHandler; }
inline void *GetSRHandlerPointer(void) { return (void *)sr_handler; }
inline void ThreadSafepointStateCreate(void *thread) {
threadSafepointStateCreate(thread);
}
inline void ThreadSafepointStateDestroy(void *thread) {
threadSafepointStateDestroy(thread);
}
inline void MonitorLock(void *monitor_oop) {
monitor_lock(monitor_oop);
}
inline void MonitorLockWithoutSafepointCheck(void *monitor_oop) {
monitor_lock_without_safepoint_check(monitor_oop);
}
inline void MonitorUnlock(void *monitor_oop) {
monitor_unlock(monitor_oop);
}
/*!
* \brief Function pointer for "Monitor::owned_by_self()".
*/
inline bool MonitorOwnedBySelf(void *monitor_oop) {
return monitor_owned_by_self(monitor_oop);
}
};
#endif // VMFUNCTIONS_H
| 13,314
|
C++
|
.h
| 397
| 30.695214
| 96
| 0.724487
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,062
|
snapShotMain.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/snapShotMain.hpp
|
/*!
* \file snapShotMain.hpp
* \brief This file is used to take snapshot.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _SNAPSHOT_MAIN_HPP
#define _SNAPSHOT_MAIN_HPP
#include <jvmti.h>
#include <jni.h>
#include "util.hpp"
/* Define export function for calling from external. */
extern "C" {
/*!
* \brief Take a heap information snapshot.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Cause of taking a snapshot.<br>
* e.g. GC, DumpRequest or Interval.
*/
void TakeSnapShot(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause);
};
/* Event for logging function. */
/*!
* \brief Setting enable of JVMTI and extension events for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param enable [in] Event notification is enable.
* \return Setting process result.
*/
jint setEventEnableForSnapShot(jvmtiEnv *jvmti, bool enable);
/*!
* \brief Setting enable of agent each threads for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param enable [in] Event notification is enable.
*/
void setThreadEnableForSnapShot(jvmtiEnv *jvmti, JNIEnv *env, bool enable);
/*!
* \brief Clear current SnapShot.
*/
void clearCurrentSnapShot();
/*!
* \brief JVM initialization event for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMInitForSnapShot(jvmtiEnv *jvmti, JNIEnv *env);
/*!
* \brief JVM finalization event for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMDeathForSnapShot(jvmtiEnv *jvmti, JNIEnv *env);
/*!
* \brief Agent initialization for snapshot function.
* \param jvmti [in] JVMTI environment object.
* \return Initialize process result.
*/
jint onAgentInitForSnapShot(jvmtiEnv *jvmti);
/*!
* \brief Agent finalization for snapshot function.
* \param env [in] JNI environment object.
*/
void onAgentFinalForSnapShot(JNIEnv *env);
/* JVMTI events. */
/*!
* \brief New class loaded event.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param thread [in] Java thread object.
* \param klass [in] Newly loaded class object.
*/
void JNICALL
OnClassPrepare(jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jclass klass);
/*!
* \brief Before garbage collection event.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnGarbageCollectionStart(jvmtiEnv *jvmti);
/*!
* \brief After garbage collection event.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnGarbageCollectionFinish(jvmtiEnv *jvmti);
/*!
* \brief Event of before garbage collection by CMS collector.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnCMSGCStart(jvmtiEnv *jvmti);
/*!
* \brief Event of after garbage collection by CMS collector.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnCMSGCFinish(jvmtiEnv *jvmti);
/*!
* \brief Data dump request event for snapshot.
* \param jvmti [in] JVMTI environment object.
*/
void JNICALL OnDataDumpRequestForSnapShot(jvmtiEnv *jvmti);
#endif // _SNAPSHOT_MAIN_HPP
| 4,029
|
C++
|
.h
| 114
| 33.403509
| 82
| 0.744544
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,063
|
trapSender.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/trapSender.hpp
|
/*!
* \file trapSender.hpp
* \brief This file is used to send SNMP trap.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _TRAP_SENDER_H
#define _TRAP_SENDER_H
#include <set>
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <pthread.h>
/* Process return code. */
/*!
* \brief Failure SNMP process.
*/
#define SNMP_PROC_FAILURE -1
/*!
* \brief SNMP process is succeed.
*/
#define SNMP_PROC_SUCCESS 0
/* SNMP variable types. */
/*!
* \brief 32bit signed Integer.
*/
#define SNMP_VAR_TYPE_INTEGER 'i'
/*!
* \brief 32bit unsigned Integer.
*/
#define SNMP_VAR_TYPE_UNSIGNED 'u'
/*!
* \brief 32bit Counter.
*/
#define SNMP_VAR_TYPE_COUNTER32 'c'
/*!
* \brief 64bit Counter.
*/
#define SNMP_VAR_TYPE_COUNTER64 'C'
/*!
* \brief String.
*/
#define SNMP_VAR_TYPE_STRING 's'
/*!
* \brief Null object.
*/
#define SNMP_VAR_TYPE_NULL 'n'
/*!
* \brief OID.
*/
#define SNMP_VAR_TYPE_OID 'o'
/*!
* \brief Time-tick.
*/
#define SNMP_VAR_TYPE_TIMETICK 't'
/* SNMP OID. */
/*!
* \brief OID of SysUpTimes.
*/
#define SNMP_OID_SYSUPTIME 1, 3, 6, 1, 2, 1, 1, 3
/*!
* \brief OID of SnmpTrapOid.
*/
#define SNMP_OID_TRAPOID 1, 3, 6, 1, 6, 3, 1, 1, 4, 1
/*!
* \brief OID of Enterpirce.
*/
#define SNMP_OID_ENTERPRICE 1, 3, 6, 1, 4, 1
/*!
* \brief OID of heapstats's PEN.
*/
#define SNMP_OID_PEN SNMP_OID_ENTERPRICE, 45156
/*!
* \brief OID of heap alert trap.
*/
#define SNMP_OID_HEAPALERT SNMP_OID_PEN, 1
/*!
* \brief OID of resource exhasted alert trap.
*/
#define SNMP_OID_RESALERT SNMP_OID_PEN, 2
/*!
* \brief OID of log archive trap.
*/
#define SNMP_OID_LOGARCHIVE SNMP_OID_PEN, 3
/*!
* \brief OID of deadlock alert trap.
*/
#define SNMP_OID_DEADLOCKALERT SNMP_OID_PEN, 4
/*!
* \brief OID of java heap usage alert trap.
*/
#define SNMP_OID_JAVAHEAPALERT SNMP_OID_PEN, 5
/*!
* \brief OID of metaspace usage alert trap.
*/
#define SNMP_OID_METASPACEALERT SNMP_OID_PEN, 6
/*!
* \brief OID string of enterprice.
*/
#define OID_PEN "1.3.6.1.4.1.45156"
/*!
* \brief OID string of heap alert trap.
*/
#define OID_HEAPALERT OID_PEN ".1.0"
/*!
* \brief OID string of resource exhasted alert trap.
*/
#define OID_RESALERT OID_PEN ".2.0"
/*!
* \brief OID string of log archive trap.
*/
#define OID_LOGARCHIVE OID_PEN ".3.0"
/*!
* \brief OID string of deadlock alert trap.
*/
#define OID_DEADLOCKALERT OID_PEN ".4.0"
/*!
* \brief OID string of java heap usage alert trap.
*/
#define OID_JAVAHEAPALERT OID_PEN ".5.0"
/*!
* \brief OID string of java heap usage alert trap.
*/
#define OID_METASPACEALERT OID_PEN ".6.0"
/* Function type definition for NET-SNMP client library. */
typedef netsnmp_log_handler *(*Tnetsnmp_register_loghandler)(int type, int pri);
typedef void (*Tsnmp_sess_init)(netsnmp_session *);
typedef netsnmp_pdu *(*Tsnmp_pdu_create)(int type);
typedef void (*Tsnmp_free_pdu)(netsnmp_pdu *pdu);
typedef int (*Tsnmp_close)(netsnmp_session *);
typedef int (*Tsnmp_add_var)(netsnmp_pdu *, const oid *, size_t,
char, const char *);
typedef netsnmp_session *(*Tsnmp_add)(netsnmp_session *,
struct netsnmp_transport_s *,
int (*fpre_parse) (netsnmp_session *,
struct netsnmp_transport_s
*, void *, int),
int (*fpost_parse) (netsnmp_session *,
netsnmp_pdu *, int));
typedef netsnmp_transport *(*Tnetsnmp_transport_open_client)
(const char* application, const char* str);
typedef netsnmp_transport *(*Tnetsnmp_tdomain_transport)(const char *str,
int local,
const char *default_domain);
typedef int (*Tsnmp_send)(netsnmp_session *, netsnmp_pdu *);
/*!
* \brief Structure for functions in NET-SNMP client library.
*/
typedef struct {
Tnetsnmp_register_loghandler netsnmp_register_loghandler;
Tsnmp_sess_init snmp_sess_init;
Tsnmp_pdu_create snmp_pdu_create;
Tsnmp_free_pdu snmp_free_pdu;
Tsnmp_close snmp_close;
Tsnmp_add_var snmp_add_var;
Tsnmp_add snmp_add;
Tnetsnmp_transport_open_client netsnmp_transport_open_client;
Tnetsnmp_tdomain_transport netsnmp_tdomain_transport;
Tsnmp_send snmp_send;
} TNetSNMPFunctions;
/*!
* \brief This class is send trap to SNMP Manager.
*/
class TTrapSender {
public:
/*!
* \brief Datetime of agent initialization.
*/
static unsigned long int initializeTime;
/*!
* \brief Mutex for TTrapSender.<br>
*/
static pthread_mutex_t senderMutex;
/*!
* \brief TTrapSender initialization.
* \param snmp [in] SNMP version.
* \param pPeer [in] Target of SNMP trap.
* \param pCommName [in] Community name use for SNMP.
* \param port [in] Port used by SNMP trap.
* \return true if succeeded.
*/
static bool initialize(int snmp, char *pPeer, char *pCommName, int port);
/*!
* \brief TTrapSender global finalization.
*/
static void finalize(void);
/*!
* \brief TrapSender constructor.
*/
TTrapSender(void);
/*!
* \brief TrapSender destructor.
*/
~TTrapSender(void);
/*!
* \brief Add agent running time from initialize to trap.
*/
void setSysUpTime(void);
/*!
* \brief Add trapOID to send information by trap.
* \param trapOID[] [in] Identifier of trap.
*/
void setTrapOID(const char *trapOID);
/*!
* \brief Add variable as send information by trap.
* \param id[] [in] Identifier of variable.
* \param len [in] Length of param "id".
* \param pValue [in] Variable's data.
* \param type [in] Kind of a variable.
* \return Return process result code.
*/
int addValue(oid id[], int len, const char *pValue, char type);
/*!
* \brief Add variable as send information by trap.
* \return Return process result code.
*/
int sendTrap(void);
/*!
* \brief Clear PDU and allocated strings.
*/
void clearValues(void);
/*!
* \brief Get SNMP session information.
* \return Session information.
*/
netsnmp_session getSession(void) { return this->session; }
/*!
* \brief Get SNMP trap variable count.
* \return Trap variable count.
*/
int getInfoCount(void) { return this->strSet.size(); }
/*!
* \brief Get SNMP PDU information.
* \return Pdu object.
*/
netsnmp_pdu *getPdu(void) { return this->pPdu; }
private:
/*!
* \brief Flags whether libnetsnmp.so is loaded.
*/
static bool is_netsnmp_loaded;
/*!
* \brief Library handle of libnetsnmp.so .
*/
static void *libnetsnmp_handle;
/*!
* \brief Functions in NET-SNMP client library.
*/
static TNetSNMPFunctions netSnmpFuncs;
/*!
* \brief SNMP session information.
*/
static netsnmp_session session;
/*!
* \brief SNMP PDU information.
*/
netsnmp_pdu *pPdu;
/*!
* \brief Allocated string set for PDU.
*/
std::set<char *> strSet;
/*!
* \brief Get function address from libnetsnmp.
* \return true if succeeded.
*/
static bool getProcAddressFromNetSNMPLib(void);
};
#endif //_TRAP_SENDER_H
| 8,194
|
C++
|
.h
| 281
| 25.099644
| 82
| 0.645931
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,064
|
vmVariables.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/vmVariables.hpp
|
/*!
* \file vmVariables.hpp
* \brief This file includes variables in HotSpot VM.
* Copyright (C) 2014-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef VMVARIABLES_H
#define VMVARIABLES_H
#include <stdint.h>
#include <stddef.h>
#include <sys/types.h>
#include "symbolFinder.hpp"
#include "vmStructScanner.hpp"
/* Macros for symbol */
/*!
* \brief String of symbol which is safepoint state variable.
*/
#define SAFEPOINT_STATE_SYMBOL "_ZN20SafepointSynchronize6_stateE"
/*!
* \brief Numbering which shows safepoint state as enumeration.
*/
#define SAFEPOINT_STATE_NORMAL_EXECUTION 0
#define SAFEPOINT_STATE_SYNCHRONIZING 1
#define SAFEPOINT_STATE_SYNCHRONIZED 2
/* extern variables */
extern "C" void *collectedHeap;
/*!
* \brief This class gathers/provides variables from HotSpot VM.
*/
class TVMVariables {
private:
/* Unrecognized option (-XX) */
/*!
* \brief Value of "-XX:UseCompressedOops" or
* "-XX:UseCompressedClassPointers".
*/
bool isCOOP;
/*!
* \brief Value of "-XX:UseParallelGC".
*/
bool useParallel;
/*!
* \brief Value of "-XX:UseParallelOldGC".
*/
bool useParOld;
/*!
* \brief Value of "-XX:UseConcMarkSweepGC".
*/
bool useCMS;
/*!
* \brief Value of "-XX:UseG1GC".
*/
bool useG1;
/* Internal value in HotSpot VM */
/*!
* \brief CMS collector state pointer.
* \sa concurrentMarkSweepGeneration.hpp<br>
* at hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/<br>
* enum CollectorState
*/
int *CMS_collectorState;
/*!
* \brief Size of "oopDesc" class in JVM.
*/
uint64_t clsSizeOopDesc;
/*!
* \brief Size of "klassOopDesc" class in JVM.
*/
uint64_t clsSizeKlassOop;
/*!
* \brief Size of "narrowOop" class in JVM.
*/
uint64_t clsSizeNarrowOop;
/*!
* \brief Size of "Klass" class in JVM.
*/
uint64_t clsSizeKlass;
/*!
* \brief Size of "instanceKlass" class in JVM.
*/
uint64_t clsSizeInstanceKlass;
/*!
* \brief Size of "arrayOopDesc" class in JVM.
*/
uint64_t clsSizeArrayOopDesc;
/*!
* \brief Offset of "oopDesc" class's "_metadata._klass" field.
* This field is stored class object when JVM don't using COOP.
*/
off_t ofsKlassAtOop;
/*!
* \brief Offset of "oopDesc" class's "_metadata._compressed_klass" field.
* This field is stored class object when JVM is using COOP.
*/
off_t ofsCoopKlassAtOop;
/*!
* \brief Offset of "oopDesc" class's "_mark" field.
* This field is stored bit flags of lock information.
*/
off_t ofsMarkAtOop;
/*!
* \brief Offset of "Klass" class's "_name" field.
* This field is stored symbol object that designed class name.
*/
off_t ofsNameAtKlass;
/*!
* \brief Offset of "Symbol" class's "_length" field.
* This field is stored string size of class name.
*/
off_t ofsLengthAtSymbol;
/*!
* \brief Offset of "Symbol" class's "_body" field.
* This field is stored string of class name.
*/
off_t ofsBodyAtSymbol;
/*!
* \brief Offset of "instanceKlass" class's "_vtable_len" field.
* This field is stored vtable size.
*/
off_t ofsVTableSizeAtInsKlass;
/*!
* \brief Offset of "instanceKlass" class's "_itable_len" field.
* This field is stored itable size.
*/
off_t ofsITableSizeAtInsKlass;
/*!
* \brief Offset of "instanceKlass" class's "_static_field_size" field.
* This field is stored static field size.
*/
off_t ofsStaticFieldSizeAtInsKlass;
/*!
* \brief Offset of "instanceKlass" class's "_nonstatic_oop_map_size" field.
* This field is stored static field size.
*/
off_t ofsNonstaticOopMapSizeAtInsKlass;
/*!
* \brief Offset of "oopDesc" class's "klass_offset_in_bytes" field.
* This field is stored static field size.
*/
off_t ofsKlassOffsetInBytesAtOopDesc;
/*!
* \brief Pointer of COOP base address.
*/
ptrdiff_t narrowOffsetBase;
/*!
* \brief Value of COOP shift bits.
*/
int narrowOffsetShift;
/*!
* \brief Pointer of Klass COOP base address.
*/
ptrdiff_t narrowKlassOffsetBase;
/*!
* \brief Value of Klass COOP shift bits.
*/
int narrowKlassOffsetShift;
/*!
* \brief Lock bit mask.<br>
* Value of "markOopDesc" class's "lock_mask_in_place" constant value.
*/
uint64_t lockMaskInPlaceMarkOop;
/*!
* \brief GC mark value.<br>
* Const value of marked_value in markOopDesc_place".
*/
uint64_t marked_value;
/*!
* \brief Pointer of CMS marking bitmap start word.
*/
void *cmsBitMap_startWord;
/*!
* \brief Value of CMS bitmap shifter.
*/
int cmsBitMap_shifter;
/*!
* \brief Pointer to CMS Marking bitmap start memory address.
*/
size_t *cmsBitMap_startAddr;
/*!
* \brief Size of integer(regular integer register) on now environment.<br>
* BitsPerWord is used by CMS GC mark bitmap.
*/
int32_t HeapWordSize;
/*!
* \brief Number of bit to need expressing integer size of "HeapWordSize".
* HeapWordSize = 2 ^ LogHeapWordSize.<br>
* BitsPerWord is used by CMS GC mark bitmap.
*/
int32_t LogHeapWordSize;
/*!
* \brief It's integer's number to need for expressing 64bit integer
* on now environment.<br>
* BitsPerWord is used by CMS GC mark bitmap.
*/
int HeapWordsPerLong;
/*!
* \brief Number of bit to need expressing a integer register.<br>
* LogBitsPerWord = 2 ^ LogBitsPerWord.<br>
* BitsPerWord is used by CMS GC mark bitmap.
*/
int LogBitsPerWord;
/*!
* \brief Number of bit to expressable max integer by single register
* on now environment.<br>
* LogBitsPerWord = sizeof(long) * 8.<br>
* BitsPerWord is used by CMS GC mark bitmap.
*/
int BitsPerWord;
/*!
* \brief Mask bit data of BitsPerWord.<br>
* Used by CMSGC("isMarkedObject") process.
*/
int BitsPerWordMask;
/*!
* \brief JVM safepoint state pointer.
*/
int *safePointState;
/*!
* \brief G1 start address.
*/
void *g1StartAddr;
/*!
* \brief offset of _osthread field in JavaThread.
*/
off_t ofsJavaThreadOsthread;
/*!
* \brief offset of _threadObj field in JavaThread.
*/
off_t ofsJavaThreadThreadObj;
/*!
* \brief offset of _thread_state field in JavaThread.
*/
off_t ofsJavaThreadThreadState;
/*!
* \brief offset of _current_pending_monitor in Thread.
*/
off_t ofsThreadCurrentPendingMonitor;
/*!
* \brief offset of _thread_id in OSThread.
*/
off_t ofsOSThreadThreadId;
/*!
* \brief offset of _object in ObjectMonitor.
*/
off_t ofsObjectMonitorObject;
/*!
* \brief Pointer of Threads_lock monitor in HotSpot.
*/
void *threads_lock;
/*!
* \brief Pointer of YoungGen in GenCollectedHeap.
*/
void *youngGen;
/*!
* \brief Start address of YoungGen.
*/
void *youngGenStartAddr;
/*!
* \brief sizeof YoungGen.
*/
size_t youngGenSize;
/* Class of HeapStats for scanning variables in HotSpot VM */
TSymbolFinder *symFinder;
TVMStructScanner *vmScanner;
/*!
* \brief Singleton instance of TVMVariables.
*/
static TVMVariables *inst;
/*!
* \brief Get HotSpot values through VMStructs which is related to CMS.
* \return Result of this function.
*/
bool getCMSValuesFromVMStructs(void);
/*!
* \brief Get HotSpot values through symbol table which is related to CMS.
* \return Result of this function.
*/
bool getCMSValuesFromSymbol(void);
/*!
* \brief Get HotSpot values through VMStructs which is related to G1.
* \return Result of this function.
*/
bool getG1ValuesFromVMStructs(void);
protected:
/*!
* \brief Get unrecognized options (-XX)
* \return Result of this function.
*/
bool getUnrecognizedOptions(void);
/*!
* \brief Get HotSpot values through VMStructs.
* \return Result of this function.
*/
bool getValuesFromVMStructs(void);
/*!
* \brief Get HotSpot values through symbol table.
* \return Result of this function.
*/
bool getValuesFromSymbol(void);
public:
/*
* Constructor of TVMVariables.
* \param sym [in] Symbol finder of libjvm.so .
* \param scan [in] VMStruct scanner.
*/
TVMVariables(TSymbolFinder *sym, TVMStructScanner *scan);
/*!
* \brief Instance initializer.
* \param sym [in] Symbol finder of libjvm.so .
* \param scan [in] VMStruct scanner.
* \return Singleton instance of TVMVariables.
*/
static TVMVariables *initialize(TSymbolFinder *sym, TVMStructScanner *scan);
/*!
* \brief Get singleton instance of TVMVariables.
* \return Singleton instance of TVMVariables.
*/
static TVMVariables *getInstance() { return inst; };
/*!
* \brief Get values which are decided after VMInit JVMTI event.
* This function should be called after JVMTI VMInit event.
* \return Process result.
*/
bool getValuesAfterVMInit(void);
/* Getters */
inline bool getIsCOOP() { return isCOOP; };
inline bool getUseParallel() { return useParallel; };
inline bool getUseParOld() { return useParOld; };
inline bool getUseCMS() { return useCMS; };
inline bool getUseG1() { return useG1; };
inline int getCMS_collectorState() { return *CMS_collectorState; };
inline uint64_t getClsSizeOopDesc() { return clsSizeOopDesc; };
inline uint64_t getClsSizeKlassOop() { return clsSizeKlassOop; };
inline uint64_t getClsSizeNarrowOop() { return clsSizeNarrowOop; };
inline uint64_t getClsSizeKlass() { return clsSizeKlass; };
inline uint64_t getClsSizeInstanceKlass() { return clsSizeInstanceKlass; };
inline uint64_t getClsSizeArrayOopDesc() { return clsSizeArrayOopDesc; };
inline off_t getOfsKlassAtOop() { return ofsKlassAtOop; };
inline off_t getOfsCoopKlassAtOop() { return ofsCoopKlassAtOop; };
inline off_t getOfsMarkAtOop() { return ofsMarkAtOop; };
inline off_t getOfsNameAtKlass() { return ofsNameAtKlass; };
inline off_t getOfsLengthAtSymbol() { return ofsLengthAtSymbol; };
inline off_t getOfsBodyAtSymbol() { return ofsBodyAtSymbol; };
inline off_t getOfsVTableSizeAtInsKlass() { return ofsVTableSizeAtInsKlass; };
inline off_t getOfsITableSizeAtInsKlass() { return ofsITableSizeAtInsKlass; };
inline off_t getOfsStaticFieldSizeAtInsKlass() {
return ofsStaticFieldSizeAtInsKlass;
};
inline off_t getOfsNonstaticOopMapSizeAtInsKlass() {
return ofsNonstaticOopMapSizeAtInsKlass;
};
inline off_t getOfsKlassOffsetInBytesAtOopDesc() {
return ofsKlassOffsetInBytesAtOopDesc;
};
inline ptrdiff_t getNarrowOffsetBase() { return narrowOffsetBase; };
inline int getNarrowOffsetShift() { return narrowOffsetShift; };
inline ptrdiff_t getNarrowKlassOffsetBase() { return narrowKlassOffsetBase; };
inline int getNarrowKlassOffsetShift() { return narrowKlassOffsetShift; };
inline uint64_t getLockMaskInPlaceMarkOop() {
return lockMaskInPlaceMarkOop;
};
inline uint64_t getMarkedValue() { return marked_value; };
inline void *getCmsBitMap_startWord() { return cmsBitMap_startWord; };
inline int getCmsBitMap_shifter() { return cmsBitMap_shifter; };
inline size_t *getCmsBitMap_startAddr() { return cmsBitMap_startAddr; };
inline int32_t getHeapWordSize() { return HeapWordSize; };
inline int32_t getLogHeapWordSize() { return LogHeapWordSize; };
inline int getHeapWordsPerLong() { return HeapWordsPerLong; };
inline int getLogBitsPerWord() { return LogBitsPerWord; };
inline int getBitsPerWord() { return BitsPerWord; };
inline int getBitsPerWordMask() { return BitsPerWordMask; };
inline int getSafePointState() { return *safePointState; };
inline void *getG1StartAddr() { return g1StartAddr; };
inline off_t getOfsJavaThreadOsthread() { return ofsJavaThreadOsthread; };
inline off_t getOfsJavaThreadThreadObj() { return ofsJavaThreadThreadObj; };
inline off_t getOfsJavaThreadThreadState() {
return ofsJavaThreadThreadState;
};
inline off_t getOfsThreadCurrentPendingMonitor() {
return ofsThreadCurrentPendingMonitor;
};
inline off_t getOfsOSThreadThreadId() { return ofsOSThreadThreadId; };
inline off_t getOfsObjectMonitorObject() { return ofsObjectMonitorObject; };
inline void *getThreadsLock() { return threads_lock; };
inline void *getYoungGen() const { return youngGen; };
inline void *getYoungGenStartAddr() const { return youngGenStartAddr; };
inline size_t getYoungGenSize() const { return youngGenSize; };
};
/* Utility functions for Safepoint */
/*!
* \brief Check whether VM is at safepoint or not.
* \return true if VM is at safepoint.
*/
inline bool isAtSafepoint(void) {
return (TVMVariables::getInstance()->getSafePointState()
== SAFEPOINT_STATE_SYNCHRONIZED);
};
/*!
* \brief Check whether VM is at normal execution or not.
* \return true if VM is at normal execution.
*/
inline bool isAtNormalExecution(void) {
return (TVMVariables::getInstance()->getSafePointState()
== SAFEPOINT_STATE_NORMAL_EXECUTION);
};
#endif // VMVARIABLES_H
| 13,912
|
C++
|
.h
| 420
| 29.547619
| 82
| 0.70319
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,065
|
configuration.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/configuration.hpp
|
/*!
* \file configuration.hpp
* \brief This file treats HeapStats configuration.
* Copyright (C) 2014-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef CONFIGURATION_HPP
#define CONFIGURATION_HPP
#include <jni.h>
#include <list>
#include "jvmInfo.hpp"
#include "logger.hpp"
/*!
* \brief Ranking Order.<br>
* This order affects heap alert.
*/
typedef enum {
DELTA, /*!< Ranking is sorted by delta from before snapshot. */
USAGE /*!< Ranking is sorted by heap using size. */
} TRankOrder;
/*!
* \brief Configuration data types.
*/
typedef enum {
BOOLEAN,
INTEGER,
LONG,
STRING,
LOGLEVEL,
RANKORDER
} TConfigDataType;
/* Forward declaration. */
class TConfiguration;
/*!
* \brief Super class of configuration holder.
*/
class TConfigElementSuper {
public:
virtual ~TConfigElementSuper(){};
virtual TConfigDataType getConfigDataType() = 0;
virtual const char *getConfigName() = 0;
};
/*!
* \brief Implementation of configuration.
*
* \param T C++ data type.
* \param V Configuration data type.
*/
template <typename T, TConfigDataType V>
class TConfigElement : public TConfigElementSuper {
public:
typedef void (*TSetter)(TConfiguration *inst, T val, T *dest);
typedef void (*TFinalizer)(T val);
private:
/*!
* \brief Instance of TConfiguration which is related to this config.
*/
TConfiguration *config;
/*!
* \brief Configuration name in heapstats.conf .
*/
char *configName;
/*!
* \brief Setter of this configuration.
* If this value is NULL, configuration will be stored directly.
*/
TSetter setter;
/*!
* \brief Finalizer of this configuration.
* If this value is not NULL, it will be called at destructor
* of this class.
* If you can use C++ pointer type configuration, you can set
* free() to this value.
*/
TFinalizer finalizer;
protected:
/*!
* \brief Configuration value.
*/
T value;
public:
TConfigElement(TConfiguration *cnf, const char *name, T initVal,
TSetter sttr = NULL, TFinalizer fnlzr = NULL) {
config = cnf;
configName = strdup(name);
value = (T)0;
setter = sttr;
finalizer = fnlzr;
set(initVal);
}
TConfigElement(const TConfigElement<T, V> &src) {
config = src.config;
configName = strdup(src.configName);
setter = src.setter;
finalizer = src.finalizer;
value = src.value;
}
virtual ~TConfigElement() {
free(configName);
if (finalizer != NULL) {
finalizer(value);
}
}
/*!
* \brief Get configuration data type.
* \return Data type of configuration.
*/
TConfigDataType getConfigDataType() { return V; }
/*!
* \brief Get configuration name.
* \return Configuration name in heapstats.conf .
*/
const char *getConfigName() { return configName; }
/*!
* \brief Getter of value in this configuration.
* \return Current configuration value in this configuration.
*/
inline T get() { return value; }
/*!
* \brief Setter of value in this configuration.
* If you set setter function, configuration value will be set
* through its function.
*/
inline void set(T val) {
if (setter == NULL) {
value = val;
} else {
setter(config, val, &value);
}
}
};
/* Configuration definition */
typedef TConfigElement<bool, BOOLEAN> TBooleanConfig;
typedef TConfigElement<int, INTEGER> TIntConfig;
typedef TConfigElement<jlong, LONG> TLongConfig;
typedef TConfigElement<TLogLevel, LOGLEVEL> TLogLevelConfig;
typedef TConfigElement<TRankOrder, RANKORDER> TRankOrderConfig;
class TStringConfig : public TConfigElement<char *, STRING> {
public:
TStringConfig(TConfiguration *cnf, const char *name, char *initVal,
TSetter sttr = NULL, TFinalizer fnlzr = NULL) :
TConfigElement<char *, STRING>(cnf, name, initVal, sttr, fnlzr) {}
/* Override copy constructor. */
TStringConfig(const TStringConfig &src) :
TConfigElement<char *, STRING>(src) {
value = (src.value == NULL) ? NULL : strdup(src.value);
}
virtual ~TStringConfig() {}
};
/*!
* \brief Configuration holder.
* This class contains current configuration value.
*/
class TConfiguration {
private:
/*!< Flag of agent attach enable. */
TBooleanConfig *attach;
/*!< Output snapshot file name. */
TStringConfig *fileName;
/*!< Output common log file name. */
TStringConfig *heapLogFile;
/*!< Output archive log file name. */
TStringConfig *archiveFile;
/*!< Output console log file name. */
TStringConfig *logFile;
/*!< Is reduced snapshot. */
TBooleanConfig *reduceSnapShot;
/*!< Whether collecting reftree. */
TBooleanConfig *collectRefTree;
/*!< Make snapshot is triggered by Full GC. */
TBooleanConfig *triggerOnFullGC;
/*!< Make snapshot is triggered by dump request. */
TBooleanConfig *triggerOnDump;
/*!< Is deadlock finder enabled? */
TBooleanConfig *checkDeadlock;
/*!< Logging on JVM error(Resoure exhausted). */
TBooleanConfig *triggerOnLogError;
/*!< Logging on received signal. */
TBooleanConfig *triggerOnLogSignal;
/*!< Logging on occurred deadlock. */
TBooleanConfig *triggerOnLogLock;
/*!< Count of show ranking. */
TIntConfig *rankLevel;
/*!< Output log level. */
TLogLevelConfig *logLevel;
/*!< Order of ranking. */
TRankOrderConfig *order;
/*!< Percentage of trigger alert in heap. */
TIntConfig *alertPercentage;
/*!< Alert percentage of javaHeapAlert. */
TIntConfig *heapAlertPercentage;
/*!< Trigger usage for javaMetaspaceAlert. */
TLongConfig *metaspaceThreshold;
/*!< Interval of periodic snapshot. */
TLongConfig *timerInterval;
/*!< Interval of periodic logging. */
TLongConfig *logInterval;
/*!< Logging on JVM error only first time. */
TBooleanConfig *firstCollect;
/*!< Name of signal logging about process. */
TStringConfig *logSignalNormal;
/*!< Name of signal logging about environment. */
TStringConfig *logSignalAll;
/*!< Name of signal reload configuration file. */
TStringConfig *reloadSignal;
/*!< Flag of thread recorder enable. */
TBooleanConfig *threadRecordEnable;
/*!< Buffer size of thread recorder. */
TLongConfig *threadRecordBufferSize;
/*!< Thread record filename. */
TStringConfig *threadRecordFileName;
/*!< Class file for I/O tracing. */
TStringConfig *threadRecordIOTracer;
/*!< Flag of SNMP trap send enable. */
TBooleanConfig *snmpSend;
/*!< SNMP trap send target. */
TStringConfig *snmpTarget;
/*!< SNMP trap community name. */
TStringConfig *snmpComName;
/*!< NET-SNMP client library path. */
TStringConfig *snmpLibPath;
/*!< Path of working directory for log archive. */
TStringConfig *logDir;
/*!< Command was execute to making log archive. */
TStringConfig *archiveCommand;
/*!< Abort JVM on resoure exhausted or deadlock. */
TBooleanConfig *killOnError;
/*!< Array of all configurations. */
std::list<TConfigElementSuper *> configs;
/*!< Configs are already loaded. */
bool isLoaded;
/*!< Trigger usage for javaHeapAlert. */
jlong heapAlertThreshold;
/*!< Size of trigger alert in heap. */
jlong alertThreshold;
/*!< Flag of already logged on JVM error. */
bool firstCollected;
/*!< JVM statistics. */
TJvmInfo *jvmInfo;
protected:
/*!
* \brief Read string value from configuration.
* \param value [in] Value of this configuration.
* \param dest [in] [out] Destination of this configuration.
*/
static void ReadStringValue(TConfiguration *inst, char *value, char **dest);
/*!
* \brief Read string value for signal from configuration.
* \param value [in] Value of this configuration.
* \param dest [in] [out] Destination of this configuration.
*/
void ReadSignalValue(const char *value, char **dest);
public:
TConfiguration(TJvmInfo *info);
TConfiguration(const TConfiguration &src);
virtual ~TConfiguration();
/*!
* \brief Read boolean value from configuration.
* \param value [in] Value of this configuration.
* \return value which is represented by boolean.
*/
bool ReadBooleanValue(const char *value);
/*!
* \brief Read long/int value from configuration.
* \param value [in] Value of this configuration.
* \param max_val [in] Max value of this parameter.
* \return value which is represented by long.
*/
long ReadLongValue(const char *value, const jlong max_val);
/*!
* \brief Read order value from configuration.
* \param value [in] Value of this configuration.
* \return value which is represented by TRankOrder.
*/
TRankOrder ReadRankOrderValue(const char *value);
/*!
* \brief Read log level value from configuration.
* \param value [in] Value of this configuration.
* \return value which is represented by TLogLevel.
*/
TLogLevel ReadLogLevelValue(const char *value);
/*!
* \brief Load configuration from file.
* \param filename [in] Read configuration file path.
*/
void loadConfiguration(const char *filename);
/*!
* \brief Print setting information.
*/
void printSetting(void);
/*!
* \brief Validate this configuration.
* \return Return true if all configuration is valid.
*/
bool validate(void);
/*!
* \brief Merge configuration from others.
* \param src Pointer of source configuration.
*/
void merge(TConfiguration *src);
/*!
* \brief Apply value to configuration which is presented by key.
* \param key Key of configuration.
* \param value New value.
* \exception Throws const char * or int which presents error.
*/
void applyConfig(char *key, char *value);
/* Accessors */
TBooleanConfig *Attach() { return attach; }
TStringConfig *FileName() { return fileName; }
TStringConfig *HeapLogFile() { return heapLogFile; }
TStringConfig *ArchiveFile() { return archiveFile; }
TStringConfig *LogFile() { return logFile; }
TBooleanConfig *ReduceSnapShot() { return reduceSnapShot; }
TBooleanConfig *CollectRefTree() { return collectRefTree; }
TBooleanConfig *TriggerOnFullGC() { return triggerOnFullGC; }
TBooleanConfig *TriggerOnDump() { return triggerOnDump; }
TBooleanConfig *CheckDeadlock() { return checkDeadlock; }
TBooleanConfig *TriggerOnLogError() { return triggerOnLogError; }
TBooleanConfig *TriggerOnLogSignal() { return triggerOnLogSignal; }
TBooleanConfig *TriggerOnLogLock() { return triggerOnLogLock; }
TIntConfig *RankLevel() { return rankLevel; }
TLogLevelConfig *LogLevel() { return logLevel; }
TRankOrderConfig *Order() { return order; }
TIntConfig *AlertPercentage() { return alertPercentage; }
TIntConfig *HeapAlertPercentage() { return heapAlertPercentage; }
TLongConfig *MetaspaceThreshold() { return metaspaceThreshold; }
TLongConfig *TimerInterval() { return timerInterval; }
TLongConfig *LogInterval() { return logInterval; }
TBooleanConfig *FirstCollect() { return firstCollect; }
TStringConfig *LogSignalNormal() { return logSignalNormal; }
TStringConfig *LogSignalAll() { return logSignalAll; }
TStringConfig *ReloadSignal() { return reloadSignal; }
TBooleanConfig *ThreadRecordEnable() { return threadRecordEnable; }
TLongConfig *ThreadRecordBufferSize() { return threadRecordBufferSize; }
TStringConfig *ThreadRecordFileName() { return threadRecordFileName; }
TStringConfig *ThreadRecordIOTracer() { return threadRecordIOTracer; }
TBooleanConfig *SnmpSend() { return snmpSend; }
TStringConfig *SnmpTarget() { return snmpTarget; }
TStringConfig *SnmpComName() { return snmpComName; }
TStringConfig *SnmpLibPath() { return snmpLibPath; }
TStringConfig *LogDir() { return logDir; }
TStringConfig *ArchiveCommand() { return archiveCommand; }
TBooleanConfig *KillOnError() { return killOnError; }
jlong getHeapAlertThreshold() { return heapAlertThreshold; }
void setHeapAlertThreshold(jlong val) { heapAlertThreshold = val; }
jlong getAlertThreshold() { return alertThreshold; }
void setAlertThreshold(jlong val) { alertThreshold = val; }
bool isFirstCollected() { return firstCollected; }
void setFirstCollected(bool val) { firstCollected = val; }
std::list<TConfigElementSuper *> getConfigs() { return configs; }
/*!
* \brief Get current log level as string.
* \return String of current log level.
*/
const char *getLogLevelAsString() {
const char *loglevel_str[] = {"Unknown", "CRIT", "WARN", "INFO", "DEBUG"};
return loglevel_str[logLevel->get()];
}
/*!
* \brief Get current rank order as string.
* \return String of current rank order.
*/
const char *getRankOrderAsString() {
const char *rankorder_str[] = {"delta", "usage"};
return rankorder_str[order->get()];
}
/*!
* \brief Initialize each configurations.
*
* \param src Source operand of configuration.
* If this value is not NULL, each configurations are copied
* from src.
*/
void initializeConfig(const TConfiguration *src);
/* Setters */
static void setLogLevel(TConfiguration *inst, TLogLevel val, TLogLevel *dest);
static void setOnewayBooleanValue(TConfiguration *inst, bool val,
bool *dest) {
if (inst->isLoaded && !(*dest) && val) {
throw "Cannot set to true";
} else {
*dest = val;
}
}
static void setSignalValue(TConfiguration *inst, char *value, char **dest) {
if (inst->isLoaded &&
((value != NULL) && (*dest != NULL) && (strlen(value) > 3) &&
strcmp(value + 3, *dest) != 0)) {
throw "Cannot change signal value";
} else {
inst->ReadSignalValue(value, dest);
}
}
static void setSnmpTarget(TConfiguration *inst, char *val, char **dest) {
if (inst->isLoaded &&
((val != NULL) && (*dest != NULL) && (strcmp(val, *dest) != 0))) {
throw "Cannot set snmp_target";
} else {
inst->ReadStringValue(inst, val, dest);
}
}
static void setSnmpComName(TConfiguration *inst, char *val, char **dest) {
if (inst->isLoaded &&
((val != NULL) && (*dest != NULL) && (strcmp(val, *dest) != 0))) {
throw "Cannot set snmp_comname";
} else {
if (*dest != NULL) {
free(*dest);
}
/* If set empty value to community name. */
*dest = (strcmp(val, "(NULL)") == 0) ? strdup("") : strdup(val);
}
}
static void setSnmpLibPath(TConfiguration *inst, char *val, char **dest) {
if (inst->isLoaded &&
((val != NULL) && (*dest != NULL) && (strcmp(val, *dest) != 0))) {
throw "Cannot set snmp_libpath";
} else {
inst->ReadStringValue(inst, val, dest);
}
}
};
#endif // CONFIGURATION_HPP
| 15,480
|
C++
|
.h
| 438
| 31.522831
| 82
| 0.696313
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,066
|
regexAdapter.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/regexAdapter.hpp
|
/*!
* \file regexAdapter.hpp
* \brief C++ super class for regex.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef REGEXADAPTER_HPP
#define REGEXADAPTER_HPP
class TRegexAdapter {
protected:
const char *pattern_str;
public:
TRegexAdapter(const char *pattern) : pattern_str(pattern){};
virtual ~TRegexAdapter(){};
virtual bool find(const char *str) = 0;
virtual char *group(int index) = 0;
};
#endif // REGEXADAPTER_HPP
| 1,164
|
C++
|
.h
| 32
| 34.25
| 82
| 0.75244
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,067
|
jvmSockCmd.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/jvmSockCmd.hpp
|
/*!
* \file jvmSockCmd.hpp
* \brief This file is used by thread dump.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _JVM_SOCK_CMD_H
#define _JVM_SOCK_CMD_H
#include <limits.h>
#include <string.h>
/*!
* \brief Structure of command arguments information.
*/
typedef char TJVMSockCmdArgs[3][255];
/*!
* \brief This class execute command in JVM socket.
*/
class TJVMSockCmd {
public:
/*!
* \brief TJVMSockCmd constructor.
* \param temporaryPath [in] Temporary path of JVM.
*/
TJVMSockCmd(char const* temporaryPath);
/*!
* \brief TJVMSockCmd destructor.
*/
virtual ~TJVMSockCmd(void);
/*!
* \brief Execute command without params, and save response.
* \param cmd [in] Execute command string.
* \param filename [in] Output file path.
* \return Response code of execute commad line.<br>
* Execute command is succeed, if value is 0.<br>
* Value is error code, if failure execute command.<br>
* Even so the file was written response data, if failure.
*/
int exec(char const* cmd, char const* filename);
/*!
* \brief Get connectable socket to JVM.
* \return Is connectable socket.
*/
inline bool isConnectable(void) { return strlen(socketPath) > 0; };
protected:
/*!
* \brief Execute command, and save response.
* \param cmd [in] Execute command string.
* \param conf [in] Execute command arguments.
* \param filename [in] Output file path.
* \return Response code of execute commad line.<br>
* Execute command is succeed, if value is 0.<br>
* Value is error code, if failure execute command.<br>
* Even so the file was written response data, if failure.
*/
virtual int execute(char const* cmd, const TJVMSockCmdArgs conf,
char const* filename);
/*!
* \brief Create JVM socket file.
* \return Process result.
*/
virtual bool createJvmSock(void);
/*!
* \brief Open socket to JVM.
* \param path [in] Path of socket file.
* \return Socket file descriptor.
*/
virtual int openJvmSock(char* path);
/*!
* \brief Find JVM socket file and get path.
* \param path [out] Path of socket file.
* \param pathLen [in] Max length of param "path".
* \return Search result.
*/
virtual bool findJvmSock(char* path, int pathLen);
/*!
* \brief Create attach file.
* \param path [out] Path of created attach file.
* \param pathLen [in] Max length of param "path".
* \return Process result.
*/
virtual bool createAttachFile(char* path, int pathLen);
private:
/*!
* \brief Socket file path.
*/
char socketPath[PATH_MAX];
/*!
* \brief Temporary directory path.
*/
char tempPath[PATH_MAX];
};
#endif // _JVM_SOCK_CMD_H
| 3,543
|
C++
|
.h
| 106
| 30.113208
| 82
| 0.686148
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,068
|
snapShotContainer.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/snapShotContainer.hpp
|
/*!
* \file snapshotContainer.hpp
* \brief This file is used to add up using size every class.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _SNAPSHOT_CONTAINER_HPP
#define _SNAPSHOT_CONTAINER_HPP
#include <tbb/concurrent_hash_map.h>
#include <tbb/concurrent_queue.h>
#include <algorithm>
#include "jvmInfo.hpp"
#include "oopUtil.hpp"
#include "classContainer.hpp"
#if PROCESSOR_ARCH == X86
#include "arch/x86/lock.inline.hpp"
#elif PROCESSOR_ARCH == ARM
#include "arch/arm/lock.inline.hpp"
#endif
/* Magic number macro. */
/*!
* \brief Magic number of snapshot file format.<br />
* 49 ... HeapStats 1.0 format.<br />
* 61 ... HeapStats 1.1 format.<br />
* Extended magic number is represented as logical or.
* Meanings of each field are as below:
* 0b10000000: This SnapShot is 2.0 format.
* It contains snapshot and metaspace data.
* 0b00000001: This SnapShot contains reference data.
* 0b00000010: This SnapShot contains safepoint time.
* Other fields (bit 2 - 6) are reserved.
* \warning Don't change output snapshot format, if you change this value.
*/
#define EXTENDED_SNAPSHOT 0x80 // 0b10000000
#define EXTENDED_REFTREE_SNAPSHOT 0x81 // 0b10000001
#define EXTENDED_SAFEPOINT_TIME 0x82 // 0b10000010
/*!
* \brief This structure stored class size and number of class-instance.
*/
#pragma pack(push, 1)
typedef struct {
jlong count; /*!< Class instance count. */
jlong total_size; /*!< Class total use size. */
} TObjectCounter;
/*!
* \brief This structure stored child class size information.
*/
struct TChildClassCounter {
TObjectCounter *counter; /*!< Java inner class object. */
TObjectData *objData; /*!< Class information. */
TChildClassCounter *next; /*!< Pointer of next object. */
};
/*!
* \brief This structure stored class and children class size information.
*/
typedef struct {
TObjectCounter *counter; /*!< Java inner class object. */
TChildClassCounter *child; /*!< Child class informations. */
volatile int spinlock; /*!< Spin lock object. */
TOopMapBlock *offsets; /*!< Offset list. */
int offsetCount; /*!< Count of offset list. */
} TClassCounter;
/*!
* \brief This structure stored snapshot information.
*/
typedef struct {
char magicNumber; /*!< Magic number for format. */
char byteOrderMark; /*!< Express byte order. */
jlong snapShotTime; /*!< Datetime of take snapshot. */
jlong size; /*!< Class entries count. */
jint cause; /*!< Cause of snapshot. */
jlong gcCauseLen; /*!< Length of GC cause. */
char gcCause[80]; /*!< String about GC casue. */
jlong FGCCount; /*!< Full-GC count. */
jlong YGCCount; /*!< Young-GC count. */
jlong gcWorktime; /*!< GC worktime. */
jlong newAreaSize; /*!< New area using size. */
jlong oldAreaSize; /*!< Old area using size. */
jlong totalHeapSize; /*!< Total heap size. */
jlong metaspaceUsage; /*!< Usage of PermGen or Metaspace. */
jlong metaspaceCapacity; /*!< Max capacity of PermGen or Metaspace. */
jlong safepointTime; /*!< Safepoint time in milliseconds. */
} TSnapShotFileHeader;
#pragma pack(pop)
/*!
* \brief This class is stored class object usage on heap.
*/
class TSnapShotContainer;
/*!
* \brief Type is for map of storing object counters.
*/
typedef tbb::concurrent_hash_map<TObjectData *, TClassCounter *,
TPointerHasher<TObjectData *> > TSizeMap;
/*!
* \brief Container of active snapshot list.
*/
typedef tbb::concurrent_hash_map<TSnapShotContainer *, int> TActiveSnapShots;
typedef std::pair<TClassCounter *, PKlassOop> TChildrenMapKey;
typedef tbb::concurrent_hash_map
<TChildrenMapKey, TChildClassCounter *> TChildrenMap;
/*!
* \brief Snapshot container instance stock queue.
*/
typedef tbb::concurrent_queue<TSnapShotContainer *> TSnapShotQueue;
/*!
* \brief This class is stored class object usage on heap.
*/
class TSnapShotContainer {
public:
/*!
* \brief Initialize snapshot caontainer class.
* \return Is process succeed.
* \warning Please call only once from main thread.
*/
static bool globalInitialize(void);
/*!
* \brief Finalize snapshot caontainer class.
* \warning Please call only once from main thread.
*/
static void globalFinalize(void);
/*!
* \brief Get snapshot container instance.
* \return Snapshot container instance.
* \warning Don't deallocate instance getting by this function.<br>
* Please call "releaseInstance" method.
*/
static TSnapShotContainer *getInstance(void);
/*!
* \brief Release snapshot container instance..
* \param instance [in] Snapshot container instance.
* \warning Don't access instance after called this function.
*/
static void releaseInstance(TSnapShotContainer *instance);
/*!
* \brief Get class entries count.
* \return Entries count of class information.
*/
inline size_t getContainerSize(void) { return this->_header.size; }
/*!
* \brief Set time of take snapshot.
* \param t [in] Datetime of take snapshot.
*/
inline void setSnapShotTime(jlong t) { this->_header.snapShotTime = t; }
/*!
* \brief Set snapshot cause.
* \param cause [in] Cause of snapshot.
*/
inline void setSnapShotCause(TInvokeCause cause) {
this->_header.cause = cause;
}
/*!
* \brief Set total size of Java Heap.
* \param size [in] Total size of Java Heap.
*/
inline void setTotalSize(jlong size) { this->_header.totalHeapSize = size; }
/*!
* \brief Set JVM performance info to header.
* \param info [in] JVM running performance information.
*/
void setJvmInfo(TJvmInfo *info);
/*!
* \brief Get snapshot header.
* \return Snapshot header.
*/
inline TSnapShotFileHeader *getHeader(void) {
return (TSnapShotFileHeader *)&this->_header;
}
/*!
* \brief Increment instance count and using size atomically.
* \param counter [in] Increment target class.
* \param size [in] Increment object size.
*/
void Inc(TObjectCounter *counter, jlong size);
/*!
* \brief Increment instance count and using size without lock.
* \param counter [in] Increment target class.
* \param size [in] Increment object size.
*/
inline void FastInc(TObjectCounter *counter, jlong size) {
counter->count++;
counter->total_size += size;
}
/*!
* \brief Increment instance count and using size.
* \param counter [in] Increment target class.
* \param operand [in] Right-hand operand (SRC operand).
* This value must be aligned 16bytes.
*/
void addInc(TObjectCounter *counter, TObjectCounter *operand);
/*!
* \brief Find class data.
* \param objData [in] Class key object.
* \return Found class data.
* Value is null, if class is not found.
*/
inline TClassCounter *findClass(TObjectData *objData) {
TSizeMap::const_accessor acc;
return counterMap.find(acc, objData) ? acc->second : NULL;
}
/*!
* \brief Find child class data.
* \param clsCounter [in] Parent class counter object.
* \param klassOop [in] Child class key object.
* \return Found class data.
* Value is null, if class is not found.
*/
inline TChildClassCounter *findChildClass(TClassCounter *clsCounter,
PKlassOop klassOop) {
TChildrenMapKey key = std::make_pair(clsCounter, klassOop);
TChildrenMap::const_accessor acc;
return childrenMap.find(acc, key) ? acc->second : NULL;
}
/*!
* \brief Append new-class to container.
* \param objData [in] New-class key object.
* \return New-class data.
*/
virtual TClassCounter *pushNewClass(TObjectData *objData);
/*!
* \brief Append new-child-class to container.
* \param clsCounter [in] Parent class counter object.
* \param objData [in] New-child-class key object.
* \return New-class data.
*/
virtual TChildClassCounter *pushNewChildClass(TClassCounter *clsCounter,
TObjectData *objData);
/*!
* \brief Output GC statistics information.
*/
void printGCInfo(void);
/*!
* \brief Clear snapshot data.
*/
void clear(bool isForce);
/*!
* \brief Set "isCleared" flag.
*/
inline void setIsCleared(bool flag) { this->isCleared = flag; }
/*!
* \brief Remove unloaded TObjectData in this snapshot container.
* This function should be called at safepoint.
* \param unloadedList Set of unloaded TObjectData.
*/
void removeObjectData(TClassInfoSet &unloadedList);
/*!
* \brief Remove unloaded TObjectData all active snapshot container.
* \param unloadedList Set of unloaded TObjectData.
*/
static void removeObjectDataFromAllSnapShots(TClassInfoSet &unloadedList);
protected:
/*!
* \brief TSnapshotContainer constructor.
*/
TSnapShotContainer(void);
/*!
* \brief TSnapshotContainer destructor.
*/
virtual ~TSnapShotContainer(void);
/*!
* \brief Zero clear to TObjectCounter.
* \param counter TObjectCounter to clear.
*/
void clearObjectCounter(TObjectCounter *counter);
/*!
* \brief Zero clear to TClassCounter.
* \param counter TClassCounter to clear.
*/
void clearClassCounter(TClassCounter *counter);
/*!
* \brief Zero clear to TClassCounter and its children counter.
* \param counter TClassCounter to clear.
*/
void clearChildClassCounters(TClassCounter *counter);
/*!
* \brief Snapshot container instance stock queue.
*/
static TSnapShotQueue *stockQueue;
/*!
* \brief Max limit count of snapshot container instance.
*/
const static unsigned int MAX_STOCK_COUNT = 2;
/*!
* \brief Map for TClassCounter.
*/
TSizeMap counterMap;
/*!
* \brief Map for TChildClassCounter.
*/
TChildrenMap childrenMap;
private:
/*!
* \brief Snapshot header.
*/
volatile TSnapShotFileHeader _header;
/*!
* \brief Is this container is cleared ?
*/
volatile bool isCleared;
/*!
* \brief Set of active TSnapShotContainer set
*/
static TActiveSnapShots activeSnapShots;
};
/* Include optimized inline functions. */
#if PROCESSOR_ARCH == X86
#include "arch/x86/snapShotContainer.inline.hpp"
#elif PROCESSOR_ARCH == ARM
#include "arch/arm/snapShotContainer.inline.hpp"
#endif
#ifdef AVX
#include "arch/x86/avx/snapShotContainer.inline.hpp"
#elif defined SSE4
#include "arch/x86/sse4/snapShotContainer.inline.hpp"
#elif defined SSE2
#include "arch/x86/sse2/snapShotContainer.inline.hpp"
#elif defined NEON
#include "arch/arm/neon/snapShotContainer.inline.hpp"
#else
/*!
* \brief Increment instance count and using size.
* \param counter [in] Increment target class.
* \param operand [in] Right-hand operand (SRC operand).
* This value must be aligned 16bytes.
*/
inline void TSnapShotContainer::addInc(TObjectCounter *counter,
TObjectCounter *operand) {
counter->count += operand->count;
counter->total_size += operand->total_size;
}
/*!
* \brief Zero clear to TObjectCounter.
* \param counter TObjectCounter to clear.
*/
inline void TSnapShotContainer::clearObjectCounter(TObjectCounter *counter) {
counter->count = 0;
counter->total_size = 0;
}
/*!
* \brief Zero clear to TClassCounter and its children counter.
* \param counter TClassCounter to clear.
*/
inline void TSnapShotContainer::clearChildClassCounters(
TClassCounter *counter) {
/* Reset counter of children class. */
TChildClassCounter *child_counter = counter->child;
while (child_counter != NULL) {
child_counter->counter->count = 0;
child_counter->counter->total_size = 0;
child_counter = child_counter->next;
}
/* Reset counter of all class. */
this->clearObjectCounter(counter->counter);
}
#endif
#endif // _SNAPSHOT_CONTAINER_HPP
| 13,052
|
C++
|
.h
| 369
| 31.924119
| 82
| 0.680634
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,069
|
callbackRegister.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/callbackRegister.hpp
|
/*!
* \file callbackRegister.hpp
* \brief Handling JVMTI callback functions.
* Copyright (C) 2015-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef CALLBACK_REGISTER_HPP
#define CALLBACK_REGISTER_HPP
#include <jvmti.h>
#include <jni.h>
#include <pthread.h>
#include <list>
/*!
* \brief Base class of JVMTI event callback.
*/
template <typename T, jvmtiEvent event>
class TJVMTIEventCallback {
protected:
/*!
* \brief JVMTI callback function list.
*/
static std::list<T> callbackList;
/*!
* \brief Read-Write lock for callback container.
*/
static pthread_rwlock_t callbackLock;
public:
/*!
* \brief Register JVMTI callback function.
*
* \param callback [in] Callback function.
*/
static void registerCallback(T callback) {
pthread_rwlock_wrlock(&callbackLock);
{
callbackList.push_back(callback);
}
pthread_rwlock_unlock(&callbackLock);
};
/*!
* \brief Unregister JVMTI callback function.
* \param callback [in] Callback function to unregister.
*/
static void unregisterCallback(T callback) {
pthread_rwlock_wrlock(&callbackLock);
{
#ifdef USE_N2350
// C++11 support
auto list_begin = callbackList.cbegin();
auto list_end = callbackList.cend();
#else
auto list_begin = callbackList.begin();
auto list_end = callbackList.end();
#endif
for (auto itr = list_begin; itr != list_end; itr++) {
if (*itr == callback) {
callbackList.erase(itr);
break;
}
}
}
pthread_rwlock_unlock(&callbackLock);
};
/*!
* \brief Merge JVMTI capabilities for this JVMTI event.
*
* \param capabilities [out] Capabilities to merge.
*/
static void mergeCapabilities(jvmtiCapabilities *capabilities){
// Nothing to do in default.
};
/*!
* \brief Merge JVMTI callback for this JVMTI event.
*
* \param callbacks [out] Callbacks to merge.
*/
static void mergeCallback(jvmtiEventCallbacks *callbacks){
// Nothing to do in deafault.
};
/*!
* \brief Switch JVMTI event notification.
*
* \param jvmti [in] JVMTI environment.
* \param mode [in] Switch of this JVMTI event.
*/
static bool switchEventNotification(jvmtiEnv *jvmti, jvmtiEventMode mode) {
return isError(jvmti, jvmti->SetEventNotificationMode(mode, event, NULL));
}
};
/*!
* \brief JVMTI callback list definition.
*/
template <typename T, jvmtiEvent event>
std::list<T> TJVMTIEventCallback<T, event>::callbackList;
/*!
* \brief Read-Write lock for callback container.
*/
template <typename T, jvmtiEvent event>
pthread_rwlock_t TJVMTIEventCallback<T, event>::callbackLock =
PTHREAD_RWLOCK_INITIALIZER;
#define ITERATE_CALLBACK_CHAIN(type, ...) \
pthread_rwlock_rdlock(&callbackLock); \
{ \
for (std::list<type>::iterator itr = callbackList.begin(); \
itr != callbackList.end(); itr++) { \
(*itr)(__VA_ARGS__); \
} \
} \
pthread_rwlock_unlock(&callbackLock);
#define DEFINE_MERGE_CALLBACK(callbackName) \
static void mergeCallback(jvmtiEventCallbacks *callbacks) { \
pthread_rwlock_rdlock(&callbackLock); \
{ \
if (callbackList.size() == 0) { \
callbacks->callbackName = NULL; \
} else if (callbackList.size() == 1) { \
callbacks->callbackName = *callbackList.begin(); \
} else { \
callbacks->callbackName = &callbackStub; \
} \
} \
pthread_rwlock_unlock(&callbackLock); \
};
/*!
* \brief JVMTI ClassPrepare callback.
*/
class TClassPrepareCallback
: public TJVMTIEventCallback<jvmtiEventClassPrepare,
JVMTI_EVENT_CLASS_PREPARE> {
public:
static void JNICALL
callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jclass klass){
ITERATE_CALLBACK_CHAIN(jvmtiEventClassPrepare, jvmti, env, thread,
klass)};
DEFINE_MERGE_CALLBACK(ClassPrepare)
};
/*!
* \brief JVMTI DumpRequest callback.
*/
class TDataDumpRequestCallback
: public TJVMTIEventCallback<jvmtiEventDataDumpRequest,
JVMTI_EVENT_DATA_DUMP_REQUEST> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti){
ITERATE_CALLBACK_CHAIN(jvmtiEventDataDumpRequest, jvmti)};
DEFINE_MERGE_CALLBACK(DataDumpRequest)
};
/*!
* \brief JVMTI GarbageCollectionStart callback.
*/
class TGarbageCollectionStartCallback
: public TJVMTIEventCallback<jvmtiEventGarbageCollectionStart,
JVMTI_EVENT_GARBAGE_COLLECTION_START> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti){
ITERATE_CALLBACK_CHAIN(jvmtiEventGarbageCollectionStart, jvmti)};
DEFINE_MERGE_CALLBACK(GarbageCollectionStart)
static void mergeCapabilities(jvmtiCapabilities *capabilities) {
capabilities->can_generate_garbage_collection_events = 1;
};
};
/*!
* \brief JVMTI GarbageCollectionFinish callback.
*/
class TGarbageCollectionFinishCallback
: public TJVMTIEventCallback<jvmtiEventGarbageCollectionFinish,
JVMTI_EVENT_GARBAGE_COLLECTION_FINISH> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti){
ITERATE_CALLBACK_CHAIN(jvmtiEventGarbageCollectionFinish, jvmti)};
DEFINE_MERGE_CALLBACK(GarbageCollectionFinish)
static void mergeCapabilities(jvmtiCapabilities *capabilities) {
capabilities->can_generate_garbage_collection_events = 1;
};
};
/*!
* \brief JVMTI ResourceExhausted callback.
*/
class TResourceExhaustedCallback
: public TJVMTIEventCallback<jvmtiEventResourceExhausted,
JVMTI_EVENT_RESOURCE_EXHAUSTED> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jint flags,
const void *reserved,
const char *description) {
ITERATE_CALLBACK_CHAIN(jvmtiEventResourceExhausted, jvmti, env, flags,
reserved, description);
};
DEFINE_MERGE_CALLBACK(ResourceExhausted)
static void mergeCapabilities(jvmtiCapabilities *capabilities) {
capabilities->can_generate_resource_exhaustion_heap_events = 1;
capabilities->can_generate_resource_exhaustion_threads_events = 1;
};
};
/*!
* \brief JVMTI MonitorContendedEnter callback.
*/
class TMonitorContendedEnterCallback
: public TJVMTIEventCallback<jvmtiEventMonitorContendedEnter,
JVMTI_EVENT_MONITOR_CONTENDED_ENTER> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread,
jobject object) {
ITERATE_CALLBACK_CHAIN(jvmtiEventMonitorContendedEnter, jvmti, env, thread,
object);
};
DEFINE_MERGE_CALLBACK(MonitorContendedEnter)
static void mergeCapabilities(jvmtiCapabilities *capabilities) {
capabilities->can_generate_monitor_events = 1;
};
};
/*!
* \brief JVMTI MonitorContendedEntered callback.
*/
class TMonitorContendedEnteredCallback
: public TJVMTIEventCallback<jvmtiEventMonitorContendedEntered,
JVMTI_EVENT_MONITOR_CONTENDED_ENTERED> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread,
jobject object) {
ITERATE_CALLBACK_CHAIN(jvmtiEventMonitorContendedEntered, jvmti, env,
thread, object);
};
DEFINE_MERGE_CALLBACK(MonitorContendedEntered)
static void mergeCapabilities(jvmtiCapabilities *capabilities) {
capabilities->can_generate_monitor_events = 1;
};
};
/*!
* \brief JVMTI VMInit callback.
*/
class TVMInitCallback
: public TJVMTIEventCallback<jvmtiEventVMInit, JVMTI_EVENT_VM_INIT> {
public:
static void JNICALL
callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
ITERATE_CALLBACK_CHAIN(jvmtiEventVMInit, jvmti, env, thread);
};
DEFINE_MERGE_CALLBACK(VMInit)
};
/*!
* \brief JVMTI VMDeath callback.
*/
class TVMDeathCallback
: public TJVMTIEventCallback<jvmtiEventVMDeath, JVMTI_EVENT_VM_DEATH> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti, JNIEnv *env) {
ITERATE_CALLBACK_CHAIN(jvmtiEventVMDeath, jvmti, env);
};
DEFINE_MERGE_CALLBACK(VMDeath)
};
/*!
* \brief JVMTI ThreadStart callback.
*/
class TThreadStartCallback
: public TJVMTIEventCallback<jvmtiEventThreadStart,
JVMTI_EVENT_THREAD_START> {
public:
static void JNICALL
callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
ITERATE_CALLBACK_CHAIN(jvmtiEventThreadStart, jvmti, env, thread);
};
DEFINE_MERGE_CALLBACK(ThreadStart)
};
/*!
* \brief JVMTI ThreadEnd callback.
*/
class TThreadEndCallback
: public TJVMTIEventCallback<jvmtiEventThreadEnd, JVMTI_EVENT_THREAD_END> {
public:
static void JNICALL
callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
ITERATE_CALLBACK_CHAIN(jvmtiEventThreadEnd, jvmti, env, thread);
};
DEFINE_MERGE_CALLBACK(ThreadEnd)
};
/*!
* \brief JVMTI MonitorWait callback.
*/
class TMonitorWaitCallback
: public TJVMTIEventCallback<jvmtiEventMonitorWait,
JVMTI_EVENT_MONITOR_WAIT> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread,
jobject object, jlong timeout) {
ITERATE_CALLBACK_CHAIN(jvmtiEventMonitorWait, jvmti, env, thread, object,
timeout);
};
DEFINE_MERGE_CALLBACK(MonitorWait)
static void mergeCapabilities(jvmtiCapabilities *capabilities) {
capabilities->can_generate_monitor_events = 1;
};
};
/*!
* \brief JVMTI MonitorWaited callback.
*/
class TMonitorWaitedCallback
: public TJVMTIEventCallback<jvmtiEventMonitorWaited,
JVMTI_EVENT_MONITOR_WAITED> {
public:
static void JNICALL callbackStub(jvmtiEnv *jvmti, JNIEnv *env, jthread thread,
jobject object, jboolean timeout) {
ITERATE_CALLBACK_CHAIN(jvmtiEventMonitorWaited, jvmti, env, thread, object,
timeout);
};
DEFINE_MERGE_CALLBACK(MonitorWaited)
static void mergeCapabilities(jvmtiCapabilities *capabilities) {
capabilities->can_generate_monitor_events = 1;
};
};
/*!
* \brief Register JVMTI callbacks to JVM.
*
* \param jvmti [in] JVMTI environment.
*/
inline bool registerJVMTICallbacks(jvmtiEnv *jvmti) {
jvmtiEventCallbacks callbacks = {0};
TClassPrepareCallback::mergeCallback(&callbacks);
TDataDumpRequestCallback::mergeCallback(&callbacks);
TGarbageCollectionStartCallback::mergeCallback(&callbacks);
TGarbageCollectionFinishCallback::mergeCallback(&callbacks);
TResourceExhaustedCallback::mergeCallback(&callbacks);
TMonitorContendedEnterCallback::mergeCallback(&callbacks);
TMonitorContendedEnteredCallback::mergeCallback(&callbacks);
TVMInitCallback::mergeCallback(&callbacks);
TVMDeathCallback::mergeCallback(&callbacks);
TThreadStartCallback::mergeCallback(&callbacks);
TThreadEndCallback::mergeCallback(&callbacks);
TMonitorWaitCallback::mergeCallback(&callbacks);
TMonitorWaitedCallback::mergeCallback(&callbacks);
return isError(
jvmti, jvmti->SetEventCallbacks(&callbacks, sizeof(jvmtiEventCallbacks)));
}
#endif // CALLBACK_REGISTER_HPP
| 12,728
|
C++
|
.h
| 348
| 31.178161
| 82
| 0.672047
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,070
|
gcWatcher.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/gcWatcher.hpp
|
/*!
* \file gcWatcher.hpp
* \brief This file is used to take snapshot when finish garbage collection.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef GCWATCHER_HPP
#define GCWATCHER_HPP
#include <jvmti.h>
#include <jni.h>
#include "util.hpp"
#include "jvmInfo.hpp"
#include "agentThread.hpp"
/*!
* \brief This type is callback to notify finished gc by gcWatcher.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param cause [in] Cause of invoke function.<br>Maybe "GC".
*/
typedef void (*TPostGCFunc)(jvmtiEnv *jvmti, JNIEnv *env, TInvokeCause cause);
/*!
* \brief This class is used to take snapshot when finished GC.
*/
class TGCWatcher : public TAgentThread {
public:
/*!
* \brief TGCWatcher constructor.
* \param postGCFunc [in] Callback is called after GC.
* \param info [in] JVM running performance information.
*/
TGCWatcher(TPostGCFunc postGCFunc, TJvmInfo *info);
/*!
* \brief TGCWatcher destructor.
*/
virtual ~TGCWatcher(void);
/*!
* \brief What's gc kind.
* \return is full-GC? (true/false)
*/
inline bool needToStartGCTrigger(void) {
bool isFullGC;
/* Check full-GC count. */
if (this->pJvmInfo->getFGCCount() > this->_FGC) {
/* Refresh full GC count. */
this->_FGC = this->pJvmInfo->getFGCCount();
/* GC kind is full-GC. */
isFullGC = true;
} else {
/* GC kind is young-GC. */
isFullGC = false;
}
/* Set GC kind flag. */
this->pJvmInfo->setFullGCFlag(isFullGC);
return isFullGC;
};
using TAgentThread::start;
/*!
* \brief Make and begin Jthread.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void start(jvmtiEnv *jvmti, JNIEnv *env);
protected:
/*!
* \brief JThread entry point.
* \param jvmti [in] JVMTI environment object.
* \param jni [in] JNI environment object.
* \param data [in] Pointer of user data.
*/
static void JNICALL entryPoint(jvmtiEnv *jvmti, JNIEnv *jni, void *data);
RELEASE_ONLY(private :)
/*!
* \brief Treated full-GC count.
*/
jlong _FGC;
/*!
* \brief Callback for notify finished gc by gcWatcher.
*/
TPostGCFunc _postGCFunc;
/*!
* \brief JVM running performance information.
*/
TJvmInfo *pJvmInfo;
};
#endif
| 3,105
|
C++
|
.h
| 99
| 28.151515
| 82
| 0.695623
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,071
|
cppRegex.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/cppRegex.hpp
|
/*!
* \file cppRegex.hpp
* \brief Regex implementation to use regex in C++11.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef CPP_REGEX_HPP
#define CPP_REGEX_HPP
#include <regex>
#include "regexAdapter.hpp"
class TCPPRegex : TRegexAdapter {
private:
std::regex expr;
std::cmatch mat;
public:
TCPPRegex(const char *pattern) : TRegexAdapter(pattern), expr(pattern){};
virtual ~TCPPRegex(){};
bool find(const char *str) { return std::regex_match(str, mat, expr); };
char *group(int index) { return strdup(mat.str(index).c_str()); };
};
#endif // CPP_REGEX_HPP
| 1,310
|
C++
|
.h
| 35
| 35.257143
| 82
| 0.741121
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,072
|
logMain.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/logMain.hpp
|
/*!
* \file logMain.hpp
* \brief This file is used common logging process.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _LOG_MAIN_HPP
#define _LOG_MAIN_HPP
#include <jvmti.h>
#include <jni.h>
/* Event for logging function. */
/*!
* \brief Interval watching for log signal.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void intervalSigProcForLog(jvmtiEnv *jvmti, JNIEnv *env);
/*!
* \brief Setting enable of JVMTI and extension events for log function.
* \param jvmti [in] JVMTI environment object.
* \param enable [in] Event notification is enable.
* \return Setting process result.
*/
jint setEventEnableForLog(jvmtiEnv *jvmti, bool enable);
/*!
* \brief Setting enable of agent each threads for log function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param enable [in] Event notification is enable.
*/
void setThreadEnableForLog(jvmtiEnv *jvmti, JNIEnv *env, bool enable);
/*!
* \brief JVM initialization event for log function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMInitForLog(jvmtiEnv *jvmti, JNIEnv *env);
/*!
* \brief JVM finalization event for log function.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
*/
void onVMDeathForLog(jvmtiEnv *jvmti, JNIEnv *env);
/*!
* \brief Agent initialization for log function.
* \return Initialize process result.
*/
jint onAgentInitForLog(void);
/*!
* \brief Agent finalization for log function.
* \param env [in] JNI environment object.
*/
void onAgentFinalForLog(JNIEnv *env);
/* JVMTI events. */
/*!
* \brief JVM resource exhausted event.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param flags [in] Resource information bit flag.
* \param reserved [in] Reserved variable.
* \param description [in] Description about resource exhausted.
*/
void JNICALL OnResourceExhausted(jvmtiEnv *jvmti, JNIEnv *env, jint flags,
const void *reserved, const char *description);
#endif // _LOG_MAIN_HPP
| 2,960
|
C++
|
.h
| 79
| 35.202532
| 82
| 0.732915
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,073
|
fsUtil.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/fsUtil.hpp
|
/*!
* \file fsUtil.hpp
* \brief This file is utilities to access file system.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _FS_UTIL_H
#define _FS_UTIL_H
#include <errno.h>
/*!
* \brief Copy data as avoid overwriting.
* \param sourceFile [in] Path of source file.
* \param destPath [in] Path of directory put duplicated file.
* \param destName [in] Name of duplicated file.<br>
* Don't rename, if value is null.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int copyFile(char const* sourceFile, char const* destPath,
char const* destName = NULL);
/*!
* \brief Create filename in expected path.
* \param basePath [in] Path of directory.
* \param filename [in] filename.
* \return Create string.<br>
* Process is failure, if return is null.<br>
* Need call "free", if return is not null.
*/
char* createFilename(char const* basePath, char const* filename);
/*!
* \brief Resolve canonicalized path path and check regular file or not.
* \param path [in] Path of the target file.
* \param rpath [out] Real path which is pointed at "path".
* Buffer size must be enough to store path (we recommend PATH_MAX).
* \return If "path" is copiable, this function returns true.
*/
bool isCopiablePath(const char* path, char* rpath);
/*!
* \brief Create temporary directory in designated directory.
* \param basePath [out] Path of temporary directory.<br>
* Process is failure, if return is null.<br>
* Need call "free", if return is not null.
* \param wishesName [in] Name of one's wishes directory name.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int createTempDir(char** basePath, char const* wishesName);
/*!
* \brief Remove temporary directory.
* \param basePath [in] Path of temporary directory.
*/
void removeTempDir(char const* basePath);
/*!
* \brief Create unique path.
* \param path [in] Path.
* \param isDirectory [in] Path is directory.
* \return Unique path.<br>Don't forget deallocate.
*/
char* createUniquePath(char* path, bool isDirectory);
/*!
* \brief Get parent directory path.
* \param path [in] Path which file or directory.
* \return Parent directory path.<br>Don't forget deallocate.
*/
char* getParentDirectoryPath(char const* path);
/*!
* \brief Get accessible of directory.
* \param path [in] Directory path.
* \param needRead [in] Accessible flag about file read.
* \param needWrite [in] Accessible flag about file write.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
int isAccessibleDirectory(char const* path, bool needRead, bool needWrite);
/*!
* \brief Check that path is accessible.
* \param path [in] A path to file.
* \return Path is accessible.
*/
bool isValidPath(const char* path);
/*!
* \brief Check disk full error.<br />
* If error is disk full, then print alert message.
* \param aErrorNum [in] Number of error code.
* \return Is designated error number means disk full.
*/
inline bool isRaisedDiskFull(const int aErrorNum) {
return (aErrorNum == ENOSPC);
}
/*!
* \brief Check disk full error.<br />
* If error is disk full, then print alert message.
* \param aErrorNum [in] Number of error code.
* \param workName [in] Name of process when found disk full error.
* \return Is designated error number means disk full.
*/
inline bool checkDiskFull(const int aErrorNum, char const* workName) {
bool result = isRaisedDiskFull(aErrorNum);
if (unlikely(result)) {
/* Output alert message. */
logger->printWarnMsg(
"ALERT(DISKFULL): Designated disk is full"
" for file output. work:\"%s\"",
workName);
}
return result;
}
#endif // _FS_UTIL_H
| 4,736
|
C++
|
.h
| 122
| 36.590164
| 82
| 0.700717
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,074
|
symbolFinder.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/symbolFinder.hpp
|
/*!
* \file symbolFinder.hpp
* \brief This file is used by search symbol in library.
* Copyright (C) 2011-2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _SYMBOL_FINDER_HPP
#define _SYMBOL_FINDER_HPP
#include <bfd.h>
#include <sys/stat.h>
#include <stddef.h>
#include "util.hpp"
#ifndef DEBUGINFO_DIR
/*!
* \brief Debuginfo parent directory.
*/
#define DEBUGINFO_DIR "/usr/lib/debug"
#endif
#ifndef DEBUGINFO_SUFFIX
/*!
* \brief Debuginfo binary name suffix.
*/
#define DEBUGINFO_SUFFIX ".debug"
#endif
/*!
* \brief Data container of shared library name and loaded virtual address.
*/
typedef struct {
char *libname; /*!< Name of target library. */
size_t libname_len; /*!< Length of target library name. */
char *libpath; /*!< Part of library path. */
size_t libpath_len; /*!< Length of library path. */
char *realpath; /*!< Real path of library. */
ptrdiff_t baseaddr; /*!< Pointer of library base address. */
} TLibraryInfo;
/*!
* \brief BFD symbol information structure.
*/
typedef struct {
bfd *bfdInfo; /*!< BFD descriptor. */
char *staticSyms; /*!< List stored static symbol. */
int staticSymCnt; /*!< Count of static symbols. */
unsigned int staticSymSize; /*!< Size of single static symbols. */
char *dynSyms; /*!< List stored dynamic symbol. */
int dynSymCnt; /*!< Count of dynamic symbols. */
unsigned int dynSymSize; /*!< Size of single dynamic symbols. */
bool hasSymtab; /*!< Flag of BFD has .symtab section. */
asymbol *workSym; /*!< Empty symbol for working temporary. */
} TLibBFDInfo;
/*!
* \brief .note.gnu.build-id information structure.
*/
typedef struct {
unsigned int name_size; /*!< size of the name. */
unsigned int hash_size; /*!< size of the hash. */
unsigned int identifier; /*!< NT_GNU_BUILD_ID == 0x3 */
char contents; /*!< name ("GNU") & hash (build id) */
} TBuildIdInfo;
/*!
* \brief C++ class for symbol search.
*/
class TSymbolFinder {
public:
/*!
* \brief TSymbolFinder constructor.
*/
TSymbolFinder(void);
/*!
* \brief TSymbolFinder destructor.
*/
virtual ~TSymbolFinder();
/*!
* \brief Load target libaray.
* \param pathPattern [in] Pattern of target library path.
* \param libname [in] Name of library.
* \return Is success load library.<br>
*/
virtual bool loadLibrary(const char *pathPattern, const char *libname);
/*!
* \brief Find symbol in target library.
* \param symbol [in] Symbol string.
* \return Address of designated symbol.<br>
* value is null if process is failure.
*/
virtual void *findSymbol(char const *symbol);
/*!
* \brief Clear loaded libaray data.
*/
virtual void clear(void);
/*!
* \brief Get target library name.
* \return String of library name.
*/
const inline char *getLibraryName(void) {
return this->targetLibInfo.libname;
};
/*!
* \brief Get target library base address.
* \return Pointer of library base address.
*/
const inline void *getLibraryAddress(void) {
return (void *)this->targetLibInfo.baseaddr;
};
/*!
* \brief Get absolute address.
* \param addr [in] Address of library symbol.
* \return Absolute symbol address in library.
*/
inline void *getAbsoluteAddress(void *addr) {
return (void *)((ptrdiff_t) this->targetLibInfo.baseaddr + (ptrdiff_t)addr);
};
protected:
/*!
* \brief Load target libaray information.
* \param path [in] Target library path.
* \param libInfo [out] BFD information record.<br>
* Value is null if process is failure.
*/
virtual void loadLibraryInfo(char const *path, TLibBFDInfo *libInfo);
/*!
* \brief Find symbol in target library to use BFD.
* \param libInfo [in] BFD information record.
* \param symbol [in] Symbol string.
* \param isDynSym [in] Symbol is dynamic symbol.
* \return Address of designated symbol.<br>
* value is null if process is failure.
*/
virtual void *doFindSymbol(TLibBFDInfo *libInfo, char const *symbol,
bool isDynSym);
RELEASE_ONLY(private :)
/*!
* \brief Flag of BFD libarary is already initialized.
*/
static bool initFlag;
/*!
* \brief Record of target library information.
*/
TLibraryInfo targetLibInfo;
/*!
* \brief BFD record of target library information.
*/
TLibBFDInfo libBfdInfo;
/*!
* \brief BFD record of target library's debug information.
*/
TLibBFDInfo debugBfdInfo;
};
#endif // _SYMBOL_FINDER_HPP
| 5,510
|
C++
|
.h
| 162
| 30.932099
| 82
| 0.657277
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,075
|
threadRecorder.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/threadRecorder.hpp
|
/*!
* \file threadRecorder.hpp
* \brief Recording thread status.
* Copyright (C) 2015-2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef THREAD_RECORDER_HPP
#define THREAD_RECORDER_HPP
#include <jvmti.h>
#include <jni.h>
#include <stddef.h>
#include <tbb/concurrent_hash_map.h>
/*!
* \brief Header of recording data.
*/
typedef struct {
jlong buffer_size;
int thread_name_len;
char *thread_name;
void *record_buffer;
} TRecordHeader;
/*!
* \brief Event record information.
*/
typedef struct {
jlong time;
jlong thread_id;
jlong event; // This value presents TThreadEvent.
jlong additionalData;
} TEventRecord;
/*!
* \brief Event definition.
*/
typedef enum {
/* JVMTI event */
ThreadStart = 1,
ThreadEnd,
MonitorWait,
MonitorWaited,
MonitorContendedEnter,
MonitorContendedEntered,
/* JNI function hook */
ThreadSleepStart,
ThreadSleepEnd,
Park,
Unpark,
/* IoTrace */
FileWriteStart,
FileWriteEnd,
FileReadStart,
FileReadEnd,
SocketWriteStart,
SocketWriteEnd,
SocketReadStart,
SocketReadEnd,
} TThreadEvent;
/*!
* \brief Type of ThreadID-ThreadName map.
*/
typedef tbb::concurrent_hash_map<jlong, char *, TNumericalHasher<jlong> >
TThreadIDMap;
/*!
* \brief Implementation of HeapStats Thread Recorder.
* This instance must be singleton.
*/
class TThreadRecorder {
private:
/*!
* \brief Page-aligned buffer size.
*/
size_t aligned_buffer_size;
/*!
* \brief Pointer of record buffer.
*/
void *record_buffer;
/*!
* \brief Pointer of record buffer.
* Record buffer is ring buffer. So this pointer must be increment
* in each writing event, and return to top of buffer when this
* pointer reaches end of buffer.
*/
TEventRecord *top_of_buffer;
/*!
* \brief End of record buffer.
*/
TEventRecord *end_of_buffer;
/*!
* \brief ThreadID-ThreadName map.
* Key is thread ID, Value is thread name.
*/
TThreadIDMap threadIDMap;
/*!
* \brief SpinLock variable for Ring Buffer operation.
*/
volatile int bufferLockVal;
/*!
* \brief Instance of TThreadRecorder.
*/
static TThreadRecorder *inst;
protected:
/*!
* \brief Constructor of TThreadRecorder.
*
* \param buffer_size [in] Size of ring buffer.
* Ring buffer size will be aligned to page size.
*/
TThreadRecorder(size_t buffer_size);
/*!
* \brief Register new thread to thread id map.
*
* \param jvmti [in] JVMTI environment.
* \param thread [in] jthread object of new thread.
*/
void registerNewThread(jvmtiEnv *jvmti, jthread thread);
/*!
* \brief Register all existed threads to thread id map.
*
* \param jvmti [in] JVMTI environment.
*/
void registerAllThreads(jvmtiEnv *jvmti);
/*!
* \brief Register JVMTI hook point.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
*/
static void registerHookPoint(jvmtiEnv *jvmti, JNIEnv *env);
/*!
* \brief Register JNI hook point.
*
* \param env [in] JNI environment.
*/
static void registerJNIHookPoint(JNIEnv *env);
/*!
* \brief Register I/O tracer.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
*
* \return true if succeeded.
*/
static bool registerIOTracer(jvmtiEnv *jvmti, JNIEnv *env);
/*!
* \brief Unegister I/O tracer.
*
* \param env [in] JNI environment.
*/
static void UnregisterIOTracer(JNIEnv *env);
public:
/*!
* \brief JVMTI callback for ThreadStart event.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param thread [in] jthread object which is created.
*/
friend void JNICALL
OnThreadStart(jvmtiEnv *jvmti, JNIEnv *env, jthread thread);
/*!
* \brief JVMTI callback for DataDumpRequest to dump thread record data.
*
* \param jvmti [in] JVMTI environment.
*/
friend void JNICALL OnDataDumpRequestForDumpThreadRecordData(jvmtiEnv *jvmti);
/*!
* \brief Initialize HeapStats Thread Recorder.
*
* \param jvmti [in] JVMTI environment.
* \param jni [in] JNI environment.
* \param buf_sz [in] Size of ring buffer.
*/
static void initialize(jvmtiEnv *jvmti, JNIEnv *jni, size_t buf_sz);
/*!
* \brief Finalize HeapStats Thread Recorder.
*
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment.
* \param fname [in] File name to dump record data.
*/
static void finalize(jvmtiEnv *jvmti, JNIEnv *env, const char *fname);
/*!
* \brief Set JVMTI capabilities to work HeapStats Thread Recorder.
*
* \param capabilities [out] JVMTI capabilities.
*/
static void setCapabilities(jvmtiCapabilities *capabilities);
/*!
* \brief Destructor of TThreadRecorder.
*/
virtual ~TThreadRecorder();
/*!
* \brief Dump record data to file.
*
* \param fname [in] File name to dump record data.
*/
void dump(const char *fname);
/*!
* \brief Get singleton instance of TThreadRecorder.
*
* \return Instance of TThreadRecorder.
*/
inline static TThreadRecorder *getInstance() { return inst; };
/*!
* \brief Enqueue new event.
*
* \param thread [in] jthread object which occurs new event.
* \param event [in] New thread event.
* \param additionalData [in] Additional data if exist.
*/
inline void putEvent(jthread thread, TThreadEvent event,
jlong additionalData);
};
#endif // THREAD_RECORDER_HPP
| 6,313
|
C++
|
.h
| 227
| 24.193833
| 82
| 0.688367
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,076
|
deadlockDetector.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/deadlockDetector.hpp
|
/*!
* \file deadlockDetector.hpp
* \brief This file is used by find deadlock.
* Copyright (C) 2017 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*/
#ifndef _DEADLOCK_DETECTOR_H
#define _DEADLOCK_DETECTOR_H
#include <jvmti.h>
#include <jni.h>
namespace dldetector {
/*!
* \brief Event handler of JVMTI MonitorContendedEnter for finding deadlock.
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment of the event (current) thread.
* \param thread [in] JNI local reference to the thread attempting to enter
* the monitor.
* \param object [in] JNI local reference to the monitor.
*/
void JNICALL OnMonitorContendedEnter(jvmtiEnv *jvmti, JNIEnv *env,
jthread thread, jobject object);
/*!
* \brief Event handler of JVMTI MonitorContendedEntered for finding deadlock.
* \param jvmti [in] JVMTI environment.
* \param env [in] JNI environment of the event (current) thread.
* \param thread [in] JNI local reference to the thread attempting to enter
* the monitor.
* \param object [in] JNI local reference to the monitor.
*/
void JNICALL OnMonitorContendedEntered(jvmtiEnv *jvmti, JNIEnv *env,
jthread thread, jobject object);
/*!
* \brief Deadlock detector initializer.
* \param jvmti [in] JVMTI environment
* \param isOnLoad [in] OnLoad phase or not (Live phase).
* \return Process result.
* \warning This function MUST be called only once.
*/
bool initialize(jvmtiEnv *jvmti, bool isOnLoad);
/*!
* \brief Deadlock detector finalizer.
* This function unregisters JVMTI callback for deadlock detection.
* \param jvmti [in] JVMTI environment
*/
void finalize(jvmtiEnv *jvmti);
};
#endif // _DEADLOCK_DETECTOR_H
| 2,562
|
C++
|
.h
| 62
| 37.129032
| 80
| 0.698394
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,077
|
pcreRegex.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/pcreRegex.hpp
|
/*!
* \file pcreRegex.hpp
* \brief Regex implementation to use PCRE.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef PCRE_REGEX_HPP
#define PCRE_REGEX_HPP
#include <pcre.h>
#include "regexAdapter.hpp"
class TPCRERegex : TRegexAdapter {
private:
int ovecsize;
int *ovec;
real_pcre *pcreExpr;
const char *find_str;
public:
TPCRERegex(const char *pattern, int ovecsz);
virtual ~TPCRERegex();
bool find(const char *str);
char *group(int index);
};
#endif // PCRE_REGEX_HPP
| 1,225
|
C++
|
.h
| 37
| 30.918919
| 82
| 0.751905
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,078
|
classContainer.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/classContainer.hpp
|
/*!
* \file classContainer.hpp
* \brief This file is used to add up using size every class.
* Copyright (C) 2011-2017 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef CLASS_CONTAINER_HPP
#define CLASS_CONTAINER_HPP
#include <tbb/concurrent_hash_map.h>
#include <tbb/concurrent_queue.h>
#include <algorithm>
#include "sorter.hpp"
#include "trapSender.hpp"
#include "oopUtil.hpp"
#if PROCESSOR_ARCH == X86
#include "arch/x86/lock.inline.hpp"
#elif PROCESSOR_ARCH == ARM
#include "arch/arm/lock.inline.hpp"
#endif
/*!
* \brief Pointer type of klassOop.
*/
typedef void* PKlassOop;
/*!
* \brief Forward declaration in snapShotContainer.hpp
*/
class TSnapShotContainer;
/*!
* \brief This structure stored class information.
*/
typedef struct {
jlong tag; /*!< Class tag. */
jlong classNameLen; /*!< Class name. */
char *className; /*!< Class name length. */
PKlassOop klassOop; /*!< Java inner class object. */
jlong oldTotalSize; /*!< Class old total use size. */
TOopType oopType; /*!< Type of class. */
jlong clsLoaderId; /*!< Class loader instance id. */
jlong clsLoaderTag; /*!< Class loader class tag. */
jlong instanceSize; /*!< Class size if this class is instanceKlass. */
} TObjectData;
/*!
* \brief This structure stored size of a class used in heap.
*/
typedef struct {
jlong tag; /*!< Pointer of TObjectData. */
jlong usage; /*!< Class using total size. */
jlong delta; /*!< Class delta size from before snapshot. */
} THeapDelta;
/*!
* \brief Memory usage alert types.
*/
typedef enum { ALERT_JAVA_HEAP, ALERT_METASPACE } TMemoryUsageAlertType;
/*!
* \brief Type is for unloaded class information.
*/
typedef tbb::concurrent_queue<TObjectData *> TClassInfoSet;
/*!
* \brief Type is for storing class information.
*/
typedef tbb::concurrent_hash_map<PKlassOop, TObjectData *,
TPointerHasher<PKlassOop> > TClassMap;
/*!
* \brief This class is stored class information.<br>
* e.g. class-name, class instance count, size, etc...
*/
class TClassContainer {
public:
/*!
* \brief TClassContainer constructor.
*/
TClassContainer(void);
/*!
* \brief TClassContainer destructor.
*/
virtual ~TClassContainer(void);
/*!
* \brief Append new-class to container.
* \param klassOop [in] New class oop.
* \return New-class data.
*/
virtual TObjectData *pushNewClass(PKlassOop klassOop);
/*!
* \brief Append new-class to container.
* \param klassOop [in] New class oop.
* \param objData [in] Add new class data.
* \return New-class data.<br />
* This value isn't equal param "objData",
* if already registered equivalence class.
*/
virtual TObjectData *pushNewClass(PKlassOop klassOop, TObjectData *objData);
/*!
* \brief Remove class from container.
* \param target [in] Remove class data.
*/
virtual void removeClass(TObjectData *target);
/*!
* \brief Search class from container.
* \param klassOop [in] Target class oop.
* \return Class data of target class.
*/
inline TObjectData *findClass(PKlassOop klassOop) {
TClassMap::const_accessor acc;
return classMap.find(acc, klassOop) ? acc->second : NULL;
}
/*!
* \brief Update class oop.
* \param oldKlassOop [in] Target old class oop.
* \param newKlassOop [in] Target new class oop.
* \return Class data of target class.
*/
inline void updateClass(PKlassOop oldKlassOop, PKlassOop newKlassOop) {
TClassMap::const_accessor acc;
if (classMap.find(acc, oldKlassOop)) {
TObjectData *cur = acc->second;
acc.release();
cur->klassOop = newKlassOop;
TClassMap::accessor new_acc;
classMap.insert(new_acc, std::make_pair(newKlassOop, cur));
new_acc.release();
classMap.erase(oldKlassOop);
updatedClassList.push(oldKlassOop);
}
}
/*!
* \brief Get class entries count.
* \return Entries count of class information.
*/
inline size_t getContainerSize(void) {
return classMap.size();
}
/*!
* \brief Remove all-class from container.
*/
virtual void allClear(void);
/*!
* \brief Output all-class information to file.
* \param snapshot [in] Snapshot instance.
* \param rank [out] Sorted-class information.
* \return Value is zero, if process is succeed.<br />
* Value is error number a.k.a. "errno", if process is failure.
*/
virtual int afterTakeSnapShot(TSnapShotContainer *snapshot,
TSorter<THeapDelta> **rank);
void removeBeforeUpdatedData(void) {
PKlassOop klass;
while (updatedClassList.try_pop(klass)) {
classMap.erase(klass);
}
}
private:
/*!
* \brief SNMP trap sender.
*/
TTrapSender *pSender;
/*!
* \brief Maps of class counting record.
*/
TClassMap classMap;
/*!
* \brief Updated class list.
*/
tbb::concurrent_queue<PKlassOop> updatedClassList;
};
/*!
* \brief Class unload event. Unloaded class will be added to unloaded list.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param thread [in] Java thread object.
* \param klass [in] Unload class object.
* \sa from: hotspot/src/share/vm/prims/jvmti.xml
*/
void JNICALL
OnClassUnload(jvmtiEnv *jvmti, JNIEnv *env, jthread thread, jclass klass);
/*!
* \brief GarbageCollectionFinish JVMTI event to release memory for unloaded
* TObjectData.
* This function will be called at safepoint.
* All GC worker and JVMTI agent threads for HeapStats will not work
* at this point.
*/
void JNICALL OnGarbageCollectionFinishForUnload(jvmtiEnv *jvmti);
#endif // CLASS_CONTAINER_HPP
| 6,677
|
C++
|
.h
| 197
| 30.57868
| 82
| 0.67426
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,079
|
bitMapMarker.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/bitMapMarker.hpp
|
/*!
* \file bitMapMarker.hpp
* \brief This file is used to store and control of bit map.
* Copyright (C) 2011-2016 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _BITMAPMARKER_HPP
#define _BITMAPMARKER_HPP
#include <stddef.h>
#ifdef __LP64__
/*!
* \brief Memory align bit count.
* Pointer is aligned 8byte,
* If allocate pointer as like "void*" in 64bit.
* So, 3bits under allocated pointer is always 0.
*/
#define MEMALIGN_BIT 3
/*!
* \brief Bit size of pointer.
* E.g. "sizeof(void*) << 3".
*/
#define PTR_BIT_WIDTH 64
/*!
* \brief Log. 2 of allocated pointer size.
* E.g. "log 2 sizeof(void*)".
*/
#define LOG2_PTR_WIDTH 6
#else // __ILP32__
/*!
* \brief Memory align bit count.
* Pointer is aligned 4byte,
* If allocate pointer as like "void*" in 32bit.
* So, 2bits under allocated pointer is always 0.
*/
#define MEMALIGN_BIT 2
/*!
* \brief Bit size of pointer.
* E.g. "sizeof(void*) << 3".
*/
#define PTR_BIT_WIDTH 32
/*!
* \brief Log. 2 of allocated pointer size.
* E.g. "log 2 sizeof(void*)".
*/
#define LOG2_PTR_WIDTH 5
#endif
/*!
* \brief This class is stored bit express flag in pointer range.
*/
class TBitMapMarker {
public:
/*!
* \brief TBitMapMarker constructor.
* \param startAddr [in] Start address of Java heap.
* \param size [in] Max Java heap size.
*/
TBitMapMarker(const void *startAddr, const size_t size);
/*!
* \brief TBitMapMarker destructor.
*/
virtual ~TBitMapMarker();
/*!
* \brief Check address which is covered by this bitmap.
* \param addr [in] Oop address.
* \return Designated pointer is existing in bitmap.
*/
inline bool isInZone(const void *addr) {
return (this->beginAddr <= addr) && (this->endAddr >= addr);
}
/*!
* \brief Mark GC-marked address in this bitmap.
* \param addr [in] Oop address.
*/
virtual void setMark(const void *addr) = 0;
/*!
* \brief Get marked flag of designated pointer.
* \param addr [in] Targer pointer.
* \return Designated pointer is marked.
*/
virtual bool isMarked(const void *addr);
/*!
* \brief Check address which is already marked and set mark.
* \param addr [in] Oop address.
* \return Designated pointer is marked.
*/
virtual bool checkAndMark(const void *addr) = 0;
/*!
* \brief Clear bitmap flag.
*/
virtual void clear(void);
protected:
/*!
* \brief Pointer of memory stored bitmap flag.
*/
void *bitmapAddr;
/*!
* \brief Real allocated bitmap range size for mmap.
*/
size_t bitmapSize;
/*!
* \brief Get a byte data and mask expressing target pointer.
* \param addr [in] Oop address.
* \param block [out] A byte data including bit flag.
* The bit flag is expressing target pointer.
* \param mask [out] A bitmask for getting only flag of target pointer.
*/
inline void getBlockAndMask(const void *addr,
ptrdiff_t **block, ptrdiff_t *mask) {
/*
* Calculate bitmap offset.
* offset = (address offset from top of JavaHeap) / (pointer size)
*/
ptrdiff_t bitmapOfs =
((ptrdiff_t)addr - (ptrdiff_t) this->beginAddr) >> MEMALIGN_BIT;
/*
* Calculate bitmap block.
* block = (top of bitmap) + ((bitmap offset) / (pointer size(bit)))
*/
*block = (ptrdiff_t *)this->bitmapAddr + (bitmapOfs >> LOG2_PTR_WIDTH);
/*
* Calculate bitmask.
* mask = 1 << ((bitmap offset) % (pointer size(bit)))
*/
*mask = (ptrdiff_t)1 << (bitmapOfs % PTR_BIT_WIDTH);
}
private:
/*!
* \brief Begin of Java heap.
*/
void *beginAddr;
/*!
* \brief End of Java heap.
*/
void *endAddr;
};
#endif // _BITMAPMARKER_HPP
| 4,510
|
C++
|
.h
| 150
| 26.773333
| 82
| 0.657057
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,080
|
util.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/util.hpp
|
/*!
* \file util.hpp
* \brief This file is utilities.
* Copyright (C) 2011-2019 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef UTIL_HPP
#define UTIL_HPP
#include <jvmti.h>
#include <jni.h>
#ifdef HAVE_ATOMIC
#include <atomic>
#else
#include <cstdatomic>
#endif
#include <assert.h>
#include <stddef.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
/* Branch prediction. */
/*!
* \brief Positive branch prediction.
*/
#define likely(x) __builtin_expect(!!(x), 1)
/*!
* \brief Negative branch prediction.
*/
#define unlikely(x) __builtin_expect(!!(x), 0)
/*!
* \brief C++ class for pthread mutex.
* C'tor acquires mutex, and d'tor releases it.
*/
class TMutexLocker {
private:
pthread_mutex_t *_mutex;
public:
TMutexLocker(pthread_mutex_t *mutex) : _mutex(mutex) {
assert(pthread_mutex_lock(_mutex) == 0);
}
~TMutexLocker() {
assert(pthread_mutex_unlock(_mutex) == 0);
}
};
/*!
* \brief Calculate align macro.
* from hotspot/src/share/vm/utilities/globalDefinitions.hpp
*/
#define ALIGN_SIZE_UP(size, alignment) \
(((size) + ((alignment)-1)) & ~((alignment)-1))
#ifdef __LP64__
/*!
* \brief Format string for jlong.<br />
* At "LP64" java environment, jlong is defined as "long int".
*/
#define JLONG_FORMAT_STR "%ld"
#define JLONG_MAX LONG_MAX
#else
/*!
* \brief Format string for jlong.<br />
* At most java environment, jlong is defined as "long long int".
*/
#define JLONG_FORMAT_STR "%lld"
#define JLONG_MAX LLONG_MAX
#endif
#ifdef DEBUG
/*!
* \brief This macro for statement only debug.
*/
#define DEBUG_ONLY(statement) statement
/*!
* \brief This macro for statement only release.
*/
#define RELEASE_ONLY(statement)
#else
/*!
* \brief This macro for statement only debug.
*/
#define DEBUG_ONLY(statement)
/*!
* \brief This macro for statement only release.
*/
#define RELEASE_ONLY(statement) statement
#endif
/*!
* \brief Debug macro.
*/
#define STATEMENT_BY_MODE(debug_state, release_state) \
DEBUG_ONLY(debug_state) RELEASE_ONLY(release_state)
/* Agent_OnLoad/JNICALL Agent_OnAttach return code. */
/*!
* \brief Process is successed.
*/
#define SUCCESS 0x00
/*!
* \brief Failure set capabilities.
*/
#define CAPABILITIES_SETTING_FAILED 0x01
/*!
* \brief Failure set callbacks.
*/
#define CALLBACKS_SETTING_FAILED 0x02
/*!
* \brief Failure initialize container.
*/
#define CLASSCONTAINER_INITIALIZE_FAILED 0x03
/*!
* \brief Failure initialize agent thread.
*/
#define AGENT_THREAD_INITIALIZE_FAILED 0x04
/*!
* \brief Failure create monitor.
*/
#define MONITOR_CREATION_FAILED 0x05
/*!
* \brief Failure get environment.
*/
#define GET_ENVIRONMENT_FAILED 0x06
/*!
* \brief Failure get low level information.<br>
* E.g. symbol, VMStructs, etc..
*/
#define GET_LOW_LEVEL_INFO_FAILED 0x07
/*!
* \brief Configuration is not valid.
*/
#define INVALID_CONFIGURATION 0x07
/*!
* \brief SNMP setup failed.
*/
#define SNMP_SETUP_FAILED 0x08
/*!
* \brief Deadlock detector setup failed.
*/
#define DLDETECTOR_SETUP_FAILED 0x09
/*!
* \brief This macro is notification catch signal to signal watcher thread.
*/
#define NOTIFY_CATCH_SIGNAL intervalSigTimer->notify();
/* Byte order mark. */
#ifdef WORDS_BIGENDIAN
/*!
* \brief Big endian.<br>
* e.g. SPARC, PowerPC, etc...
*/
#define BOM 'B'
#else
/*!
* \brief Little endian.<br>
* e.g. i386, AMD64, etc..
*/
#define BOM 'L'
#endif
/* Typedef. */
/*!
* \brief Causes of function invoking.
*/
typedef enum {
GC = 1, /*!< Invoke by Garbage Collection. */
DataDumpRequest = 2, /*!< Invoke by user dump request. */
Interval = 3, /*!< Invoke by timer interval. */
Signal = 4, /*!< Invoke by user's signal. */
AnotherSignal = 5, /*!< Invoke by user's another signal. */
ResourceExhausted = 6, /*!< Invoke by JVM resource exhausted. */
ThreadExhausted = 7, /*!< Invoke by thread exhausted. */
OccurredDeadlock = 8 /*!< Invoke by occured deadlock. */
} TInvokeCause;
/*!
* \brief Java thread information structure.
*/
typedef struct {
char *name; /*!< Name of java thread. */
bool isDaemon; /*!< Flag of thread is daemon thread. */
int priority; /*!< Priority of thread in java. */
char *state; /*!< String about thread state. */
} TJavaThreadInfo;
/*!
* \brief Java method information structure in stack frame.
*/
typedef struct {
char *methodName; /*!< Name of class method. */
char *className; /*!< Name of class is declaring method. */
bool isNative; /*!< Flag of method is native. */
char *sourceFile; /*!< Name of file name is declaring class. */
int lineNumber; /*!< Line number of method's executing position in file. */
} TJavaStackMethodInfo;
/*!
* \brief This type is common large size int.
*/
typedef unsigned long long int TLargeUInt;
/*!
* \brief This type is used by store datetime is mili-second unit.
*/
typedef unsigned long long int TMSecTime;
/*!
* \brief Interval of check signal by signal watch timer.(msec)
*/
const unsigned int SIG_WATCHER_INTERVAL = 0;
/* Export functions. */
/*!
* \brief JVMTI error detector.
* \param jvmti [in] JVMTI envrionment object.
* \param error [in] JVMTI error code.
* \return Param "error" is error code?(true/false)
*/
bool isError(jvmtiEnv *jvmti, jvmtiError error);
/*!
* \brief Get system information.
* \param env [in] JNI envrionment.
* \param key [in] System property key.
* \return String of system property.
*/
char *GetSystemProperty(JNIEnv *env, const char *key);
/*!
* \brief Get ClassUnload event index.
* \param jvmti [in] JVMTI envrionment object.
* \return ClassUnload event index.
* \sa hotspot/src/share/vm/prims/jvmtiExport.cpp<br>
* hotspot/src/share/vm/prims/jvmtiEventController.cpp<br>
* hotspot/src/share/vm/prims/jvmti.xml<br>
* in JDK.
*/
jint GetClassUnloadingExtEventIndex(jvmtiEnv *jvmti);
/*!
* \brief Replace old string in new string on string.
* \param str [in] Process target string.
* \param oldStr [in] Targer of replacing.
* \param newStr [in] A string will replace existing string.
* \return String invoked replace.<br>Don't forget deallocate.
*/
char *strReplase(char const *str, char const *oldStr, char const *newStr);
/*!
* \brief Get now date and time.
* \return Mili-second elapsed time from 1970/1/1 0:00:00.
*/
jlong getNowTimeSec(void);
/*!
* \brief A little sleep.
* \param sec [in] Second of sleep range.
* \param nsec [in] Nano second of sleep range.
*/
void littleSleep(const long int sec, const long int nsec);
/*!
* \brief Get thread information.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param thread [in] Thread object in java.
* \param info [out] Record stored thread information.
*/
void getThreadDetailInfo(jvmtiEnv *jvmti, JNIEnv *env, jthread thread,
TJavaThreadInfo *info);
/*!
* \brief Get method information in designed stack frame.
* \param jvmti [in] JVMTI environment object.
* \param env [in] JNI environment object.
* \param frame [in] method stack frame.
* \param info [out] Record stored method information in stack frame.
*/
void getMethodFrameInfo(jvmtiEnv *jvmti, JNIEnv *env, jvmtiFrameInfo frame,
TJavaStackMethodInfo *info);
/*!
* \brief Handling Java Exception if exists.
* \param env [in] JNI environment object.
*/
inline void handlePendingException(JNIEnv *env) {
/* If exists execption in java. */
if (env->ExceptionOccurred() != NULL) {
/* Clear execption in java. */
env->ExceptionDescribe();
env->ExceptionClear();
}
};
/*!
* \brief Add to address.
* \param addr [in] Target address.
* \param inc [in] Incremental integer value.
* \return The address added increment value.
*/
inline void *incAddress(void *addr, off_t inc) {
return (void *)((ptrdiff_t)addr + inc);
};
/*!
* \brief Wrapper function of strerror_r().
* \param buf [in] Buffer of error string.
* \param buflen [in] Length of buf.
* \return Pointer to error string.
*/
inline char *strerror_wrapper(char *buf, size_t buflen) {
char *output_message;
#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
/* XSI-compliant version of strerror_r() */
strerror_r(errno, buf, buflen);
output_message = errno_string;
#else
/* GNU-specific version of strerror_r() */
output_message = strerror_r(errno, buf, buflen);
#endif
return output_message;
};
/* Classes. */
/*!
* \brief Hasher class for tbb::concurrent_hash_map.
* This template class is for number type except pointers.
*/
template <typename T>
class TNumericalHasher {
public:
static size_t hash(const T v) {
return v;
}
static bool equal(const T v1, const T v2) {
return v1 == v2;
}
};
/*!
* \brief Hasher class for tbb::concurrent_hash_map.
* This template class is for pointer type.
*/
template <typename T>
class TPointerHasher : public TNumericalHasher<T> {
public:
static size_t hash(const T v) {
return reinterpret_cast<size_t>(v) / sizeof(T);
}
};
/*!
* \brief Utility class for flag of processing.
*/
class TProcessMark {
private:
std::atomic_int &flag;
public:
TProcessMark(std::atomic_int &flg) : flag(flg) { flag++; }
~TProcessMark() { flag--; }
};
/* CPU Specific utilities. */
#ifdef AVX
#include "arch/x86/avx/util.hpp"
#elif defined(SSE2) || defined(SSE4)
#include "arch/x86/sse2/util.hpp"
#elif defined(NEON)
#include "arch/arm/neon/util.hpp"
#else
inline void memcpy32(void *dest, const void *src) {
memcpy(dest, src, 32);
};
#endif
#endif
| 10,593
|
C++
|
.h
| 362
| 27.082873
| 82
| 0.685675
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,081
|
snapShotContainer.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/snapShotContainer.inline.hpp
|
/*!
* \file snapShotContainer.inline.hpp
* \brief This file is used to add up using size every class.
* This source is optimized for x86 instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef X86_SNAPSHOTCONTAINER_INLINE_HPP
#define X86_SNAPSHOTCONTAINER_INLINE_HPP
/*!
* \brief Increment instance count and using size atomically.
* \param counter [in] Increment target class.
* \param size [in] Increment object size.
*/
inline void TSnapShotContainer::Inc(TObjectCounter *counter, jlong size) {
#ifdef __amd64__
asm volatile(
"lock addq $1, %0;"
"lock addq %2, %1;"
: "+m"(counter->count), "+m"(counter->total_size)
: "r"(size)
: "cc"
);
#else // __i386__
asm volatile(
"lock addl $1, %0;" /* Lower 32bit */
"lock adcl $0, 4+%0;" /* Upper 32bit */
" movl %2, %%eax;"
"lock addl %%eax, %1;" /* Lower 32bit */
" movl 4+%2, %%eax;"
"lock adcl %%eax, 4+%1;" /* Upper 32bit */
: "+o"(counter->count), "+o"(counter->total_size)
: "o"(size)
: "%eax", "cc"
);
#endif
}
#endif // X86_SNAPSHOTCONTAINER_INLINE_HPP
| 1,856
|
C++
|
.h
| 52
| 32.942308
| 82
| 0.672404
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,082
|
x86BitMapMarker.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/x86BitMapMarker.hpp
|
/*!
* \file x86BitMapMarker.hpp
* \brief This file is used to store and control of bit map.
* Copyright (C) 2014-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef X86BITMAPMARKER_HPP
#define X86BITMAPMARKER_HPP
#include "../../bitMapMarker.hpp"
/*!
* \brief This class is stored bit express flag in pointer range.
*/
class TX86BitMapMarker : public TBitMapMarker {
public:
/*!
* \brief TBitMapMarker constructor.
* \param startAddr [in] Start address of Java heap.
* \param size [in] Max Java heap size.
*/
TX86BitMapMarker(const void *startAddr, const size_t size)
: TBitMapMarker(startAddr, size){};
/*!
* \brief TBitMapMarker destructor.
*/
virtual ~TX86BitMapMarker(){};
/*!
* \brief Mark GC-marked address in this bitmap.
* \param addr [in] Oop address.
*/
virtual void setMark(const void *addr);
/*!
* \brief Get marked flag of designated pointer.
* \param addr [in] Targer pointer.
* \return Designated pointer is marked.
*/
virtual bool isMarked(const void *addr);
/*!
* \brief Check address which is already marked and set mark.
* \param addr [in] Oop address.
* \return Designated pointer is marked.
*/
virtual bool checkAndMark(const void *addr);
};
#endif // X86BITMAPMARKER_HPP
| 1,997
|
C++
|
.h
| 58
| 31.586207
| 82
| 0.722941
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,083
|
lock.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/lock.inline.hpp
|
/*!
* \file lock.inline.hpp
* \brief This file defines spinlock functions.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef LOCK_INLINE_HPP
#define LOCK_INLINE_HPP
/*!
* \brief Wait spin lock.
* \param aLock [in] Target integer lock.
*/
inline void spinLockWait(volatile int *aLock) {
asm volatile(
"1:"
"xorl %%eax, %%eax;"
"pause;"
"lock cmpxchgl %1, (%0);"
"jnz 1b;"
: "+r"(aLock)
: "r"(1)
: "cc", "memory", "%eax"
);
};
/*!
* \brief Release spin lock.
* \param aLock [in] Target integer lock.
*/
inline void spinLockRelease(volatile int *aLock) {
asm volatile(
"xorl %%eax, %%eax;"
"lock xchgl %%eax, (%0);"
: "+r"(aLock)
:
: "cc", "memory", "%eax"
);
};
#endif // LOCK_INLINE_HPP
| 1,485
|
C++
|
.h
| 52
| 25.846154
| 82
| 0.680196
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,084
|
sse2BitMapMarker.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/sse2/sse2BitMapMarker.hpp
|
/*!
* \file sse2BitMapMarker.hpp
* \brief Storeing and Controlling G1 marking bitmap.
* This source is optimized for SSE2 instruction set.
* Copyright (C) 2014-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _SSE2BITMAPMARKER_HPP
#define _SSE2BITMAPMARKER_HPP
#include "arch/x86/x86BitMapMarker.hpp"
/*!
* \brief This class is stored bit express flag in pointer range SSE2 version.
*/
class TSSE2BitMapMarker : public TX86BitMapMarker {
public:
/*!
* \brief TSSE2BitMapMarker constructor.
* \param startAddr [in] Start address of Java heap.
* \param size [in] Max Java heap size.
*/
TSSE2BitMapMarker(const void *startAddr, const size_t size)
: TX86BitMapMarker(startAddr, size){};
/*!
* \brief TSSE2BitMapMarker destructor.
*/
virtual ~TSSE2BitMapMarker(){};
/*!
* \brief Clear bitmap flag.
*/
virtual void clear(void);
};
#endif // _SSE2BITMAPMARKER_HPP
| 1,635
|
C++
|
.h
| 46
| 33
| 82
| 0.739735
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,085
|
jvmInfo.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/sse2/jvmInfo.inline.hpp
|
/*!
* \file jvmInfo.inline.hpp
* \brief This file is used to get JVM performance information.
* This source is optimized for SSE2 instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef SSE2_JVMINFO_INLINE_H
#define SSE2_JVMINFO_INLINE_H
/*!
* \brief memcpy for gccause
*/
inline void TJvmInfo::loadGCCause(void) {
/* Strcpy with SSE2 (80 bytes).
* Sandy Bridge can two load operations per cycle.
* So we should execute sequentially 2-load / 1-store ops.
* Intel 64 and IA-32 Architectures Optimization Reference Manual
* 3.6.1.1 Make Use of Load Bandwidth in Intel Microarchitecture
* Code Name Sandy Bridge
*/
asm volatile(
"movdqu (%0), %%xmm0;"
"movdqu 16(%0), %%xmm1;"
"movdqa %%xmm0, (%1);"
"movdqu 32(%0), %%xmm0;"
"movdqu 48(%0), %%xmm2;"
"movdqa %%xmm1, 16(%1);"
"movdqu 64(%0), %%xmm1;"
"movdqa %%xmm0, 32(%1);"
"movdqa %%xmm2, 48(%1);"
"movdqa %%xmm1, 64(%1);"
:
: "d"(this->_gcCause), /* GC Cause address. */
"c"(this->gcCause) /* GC Cause container. */
: "cc", "%xmm0", "%xmm1", "%xmm2"
);
}
/*!
* \brief Set "Unknown GCCause" to gccause.
*/
inline void TJvmInfo::SetUnknownGCCause(void) {
asm volatile(
"movdqa (%1), %%xmm0;"
"movdqa %%xmm0, (%0);"
:
: "a"(this->gcCause), "c"(UNKNOWN_GC_CAUSE)
: "%xmm0"
);
}
#endif // SSE2_JVMINFO_INLINE_H
| 2,141
|
C++
|
.h
| 64
| 30.359375
| 82
| 0.662325
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,086
|
snapShotContainer.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/sse2/snapShotContainer.inline.hpp
|
/*!
* \file snapshotContainer.inline.hpp
* \brief This file is used to add up using size every class.
* This source is optimized for SSE2 instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef SSE2_SNAPSHOT_CONTAINER_INLINE_HPP
#define SSE2_SNAPSHOT_CONTAINER_INLINE_HPP
/*
* This file will be included from arch/sse4/snapShotContainer.inline.hpp .
* It includes addInc() only.
* So I want to disable addInc() when SSE4 is enabled.
*/
#ifndef SSE4
/*!
* \brief Increment instance count and using size.
* \param counter [in] Increment target class.
* \param operand [in] Right-hand operand (SRC operand).
* This value must be aligned 16bytes.
*/
inline void TSnapShotContainer::addInc(TObjectCounter *counter,
TObjectCounter *operand) {
asm volatile(
"movdqa (%1), %%xmm0;"
"paddq (%0), %%xmm0;"
"movdqa %%xmm0, (%0);"
:
: "r"(counter), "r"(operand)
: "%xmm0"
);
}
#endif
/*!
* \brief Zero clear to TObjectCounter.
* \param counter TObjectCounter to clear.
*/
inline void TSnapShotContainer::clearObjectCounter(TObjectCounter *counter) {
asm volatile(
"pxor %%xmm0, %%xmm0;"
"movdqa %%xmm0, (%0);"
:
: "r"(counter)
: "%xmm0"
);
}
/*!
* \brief Zero clear to TClassCounter and its children counter.
* \param counter TClassCounter to clear.
*/
inline void TSnapShotContainer::clearChildClassCounters(
TClassCounter *counter) {
#ifdef __amd64__
asm volatile(
"pxor %%xmm0, %%xmm0;"
"movq 8(%0), %%rax;" /* clsCounter->child */
".align 16;"
"1:"
" testq %%rax, %%rax;"
" jz 2f;"
" movq (%%rax), %%rbx;" /* child->counter */
" movdqa %%xmm0, (%%rbx);"
" movq 16(%%rax), %%rax;" /* child->next */
" jmp 1b;"
"2:"
" movq (%0), %%rbx;" /* clsCounter->counter */
" movdqa %%xmm0, (%%rbx);"
:
: "r"(counter)
: "%xmm0", "%rax", "%rbx", "cc"
);
#else // i386
asm volatile(
"pxor %%xmm0, %%xmm0;"
"movl 4(%0), %%eax;" /* clsCounter->child */
".align 16;"
"1:"
" testl %%eax, %%eax;"
" jz 2f;"
" movl (%%eax), %%ecx;" /* child->counter */
" movdqa %%xmm0, (%%ecx);"
" movl 8(%%eax), %%eax;" /* child->next */
" jmp 1b;"
"2:"
" movl (%0), %%ecx;" /* clsCounter->counter */
" movdqa %%xmm0, (%%ecx);"
:
: "r"(counter)
: "%xmm0", "%eax", "%ecx", "cc"
);
#endif
}
#endif // SSE2_SNAPSHOT_CONTAINER_INLINE_HPP
| 3,286
|
C++
|
.h
| 107
| 27.158879
| 82
| 0.612232
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,087
|
util.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/sse2/util.hpp
|
/*!
* \file util.hpp
* \brief Optimized utility functions for SSE2 instruction set.
* Copyright (C) 2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef SSE2_UTIL_H
#define SSE2_UTIL_H
inline void memcpy32(void *dest, const void *src) {
asm volatile(
"movdqa (%1), %%xmm0;"
"movdqa 16(%1), %%xmm1;"
"movdqa %%xmm0, (%0);"
"movdqa %%xmm1, 16(%0);"
:
: "r"(dest), "r"(src)
: "%xmm0", "%xmm1"
);
}
#endif // SSE2_UTIL_H
| 1,192
|
C++
|
.h
| 34
| 32.470588
| 82
| 0.705628
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.