2 * Copyright 2021 Andrei Pangin
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
24 extern int is_openj9_process(int pid);
25 extern int jattach_openj9(int pid, int nspid, int argc, char** argv);
26 extern int jattach_hotspot(int pid, int nspid, int argc, char** argv);
29 __attribute__((visibility("default")))
30 int jattach(int pid, int argc, char** argv) {
31 uid_t my_uid = geteuid();
32 gid_t my_gid = getegid();
33 uid_t target_uid = my_uid;
34 gid_t target_gid = my_gid;
36 if (get_process_info(pid, &target_uid, &target_gid, &nspid) < 0) {
37 fprintf(stderr, "Process %d not found\n", pid);
41 // Container support: switch to the target namespaces.
42 // Network and IPC namespaces are essential for OpenJ9 connection.
45 int mnt_changed = enter_ns(pid, "mnt");
47 // In HotSpot, dynamic attach is allowed only for the clients with the same euid/egid.
48 // If we are running under root, switch to the required euid/egid automatically.
49 if ((my_gid != target_gid && setegid(target_gid) != 0) ||
50 (my_uid != target_uid && seteuid(target_uid) != 0)) {
51 perror("Failed to change credentials to match the target process");
55 get_tmp_path(mnt_changed > 0 ? nspid : pid);
57 // Make write() return EPIPE instead of abnormal process termination
58 signal(SIGPIPE, SIG_IGN);
60 if (is_openj9_process(nspid)) {
61 return jattach_openj9(pid, nspid, argc, argv);
63 return jattach_hotspot(pid, nspid, argc, argv);
67 #ifdef JATTACH_VERSION
69 int main(int argc, char** argv) {
71 printf("jattach " JATTACH_VERSION " built on " __DATE__ "\n"
72 "Copyright 2021 Andrei Pangin\n"
74 "Usage: jattach <pid> <cmd> [args ...]\n"
77 " load threaddump dumpheap setflag properties\n"
78 " jcmd inspectheap datadump printflag agentProperties\n"
83 int pid = atoi(argv[1]);
85 fprintf(stderr, "%s is not a valid process ID\n", argv[1]);
89 return jattach(pid, argc - 2, argv + 2);
92 #endif // JATTACH_VERSION