11/*
2- * Copyright (c) 2005, 2023 , Oracle and/or its affiliates. All rights reserved.
2+ * Copyright (c) 2005, 2024 , Oracle and/or its affiliates. All rights reserved.
33 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44 *
55 * This code is free software; you can redistribute it and/or modify it
@@ -275,11 +275,8 @@ public synchronized void close() throws IOException {
275275 }
276276
277277 // Return the socket file for the given process.
278- private File findSocketFile (int pid , int ns_pid ) {
279- // A process may not exist in the same mount namespace as the caller.
280- // Instead, attach relative to the target root filesystem as exposed by
281- // procfs regardless of namespaces.
282- String root = "/proc/" + pid + "/root/" + tmpdir ;
278+ private File findSocketFile (int pid , int ns_pid ) throws IOException {
279+ String root = findTargetProcessTmpDirectory (pid , ns_pid );
283280 return new File (root , ".java_pid" + ns_pid );
284281 }
285282
@@ -295,21 +292,34 @@ private File createAttachFile(int pid, int ns_pid) throws IOException {
295292 // Do not canonicalize the file path, or we will fail to attach to a VM in a container.
296293 f .createNewFile ();
297294 } catch (IOException x ) {
298- String root ;
299- if (pid != ns_pid ) {
300- // A process may not exist in the same mount namespace as the caller.
301- // Instead, attach relative to the target root filesystem as exposed by
302- // procfs regardless of namespaces.
303- root = "/proc/" + pid + "/root/" + tmpdir ;
304- } else {
305- root = tmpdir ;
306- }
295+ String root = findTargetProcessTmpDirectory (pid , ns_pid );
307296 f = new File (root , fn );
308297 f .createNewFile ();
309298 }
310299 return f ;
311300 }
312301
302+ private String findTargetProcessTmpDirectory (int pid , int ns_pid ) throws IOException {
303+ String root ;
304+ if (pid != ns_pid ) {
305+ // A process may not exist in the same mount namespace as the caller, e.g.
306+ // if we are trying to attach to a JVM process inside a container.
307+ // Instead, attach relative to the target root filesystem as exposed by
308+ // procfs regardless of namespaces.
309+ String procRootDirectory = "/proc/" + pid + "/root" ;
310+ if (!Files .isReadable (Path .of (procRootDirectory ))) {
311+ throw new IOException (
312+ String .format ("Unable to access root directory %s " +
313+ "of target process %d" , procRootDirectory , pid ));
314+ }
315+
316+ root = procRootDirectory + "/" + tmpdir ;
317+ } else {
318+ root = tmpdir ;
319+ }
320+ return root ;
321+ }
322+
313323 /*
314324 * Write/sends the given to the target VM. String is transmitted in
315325 * UTF-8 encoding.
0 commit comments