--- old/src/hotspot/os/linux/attachListener_linux.cpp 2019-06-26 23:28:21.314877089 +0900 +++ new/src/hotspot/os/linux/attachListener_linux.cpp 2019-06-26 23:28:21.161877032 +0900 @@ -69,8 +69,22 @@ // the file descriptor for the listening socket static int _listener; + // reads a request from the given connected socket + static LinuxAttachOperation* read_request(int s); + + static bool _atexit_registered; + + public: + enum { + ATTACH_PROTOCOL_VER = 1 // protocol version + }; + enum { + ATTACH_ERROR_BADVERSION = 101 // error codes + }; + static void set_path(char* path) { if (path == NULL) { + _path[0] = '\0'; _has_path = false; } else { strncpy(_path, path, UNIX_PATH_MAX); @@ -81,17 +95,6 @@ static void set_listener(int s) { _listener = s; } - // reads a request from the given connected socket - static LinuxAttachOperation* read_request(int s); - - public: - enum { - ATTACH_PROTOCOL_VER = 1 // protocol version - }; - enum { - ATTACH_ERROR_BADVERSION = 101 // error codes - }; - // initialize the listener, returns 0 if okay static int init(); @@ -125,6 +128,7 @@ char LinuxAttachListener::_path[UNIX_PATH_MAX]; bool LinuxAttachListener::_has_path; int LinuxAttachListener::_listener = -1; +bool LinuxAttachListener::_atexit_registered = false; // Supporting class to help split a buffer into individual components class ArgumentIterator : public StackObj { @@ -159,16 +163,15 @@ // bound too. extern "C" { static void listener_cleanup() { - static int cleanup_done; - if (!cleanup_done) { - cleanup_done = 1; - int s = LinuxAttachListener::listener(); - if (s != -1) { - ::close(s); - } - if (LinuxAttachListener::has_path()) { - ::unlink(LinuxAttachListener::path()); - } + int s = LinuxAttachListener::listener(); + if (s != -1) { + LinuxAttachListener::set_listener(-1); + ::shutdown(s, SHUT_RDWR); + ::close(s); + } + if (LinuxAttachListener::has_path()) { + ::unlink(LinuxAttachListener::path()); + LinuxAttachListener::set_path(NULL); } } } @@ -181,7 +184,10 @@ int listener; // listener socket (file descriptor) // register function to cleanup - ::atexit(listener_cleanup); + if (!_atexit_registered) { + _atexit_registered = true; + ::atexit(listener_cleanup); + } int n = snprintf(path, UNIX_PATH_MAX, "%s/.java_pid%d", os::get_temp_directory(), os::current_process_id()); @@ -485,6 +491,27 @@ return ret_code; } +bool AttachListener::check_socket_file() { + int ret; + struct stat64 st; + ret = stat64(LinuxAttachListener::path(), &st); + if (ret == -1) { // need to restart attach listener. + log_debug(attach)("Socket file %s does not exist - Restart Attach Listener", + LinuxAttachListener::path()); + + listener_cleanup(); + + // wait to terminate current attach listener instance... + while(AttachListener::transit_state(AL_INITIALIZING, + AL_NOT_INITIALIZED) != AL_NOT_INITIALIZED) { + sched_yield(); + } + is_init_trigger(); + return true; + } + return false; +} + // Attach Listener is started lazily except in the case when // +ReduseSignalUsage is used bool AttachListener::init_at_startup() { --- old/src/hotspot/share/runtime/os.cpp 2019-06-26 23:28:21.728877242 +0900 +++ new/src/hotspot/share/runtime/os.cpp 2019-06-26 23:28:21.620877202 +0900 @@ -362,8 +362,23 @@ case SIGBREAK: { // Check if the signal is a trigger to start the Attach Listener - in that // case don't print stack traces. - if (!DisableAttachMechanism && AttachListener::is_init_trigger()) { - continue; + if (!DisableAttachMechanism) { + // Attempt to transit state to AL_INITIALIZING. + AttachListenerState cur_state = AttachListener::transit_state(AL_INITIALIZING, AL_NOT_INITIALIZED); + if (cur_state == AL_INITIALIZING) { + // Attach Listener has been started to initialize. Ignore this signal. + continue; + } else if (cur_state == AL_NOT_INITIALIZED) { + // Start to initialize. + if (!AttachListener::is_init_trigger()) { + // Attach Listener could not be started. + // So we need to transit the state to AL_NOT_INITIALIZED. + AttachListener::set_state(AL_NOT_INITIALIZED); + } + continue; + } else if (AttachListener::check_socket_file()) { + continue; + } } // Print stack traces // Any SIGBREAK operations added here should make sure to flush --- old/src/hotspot/share/services/attachListener.cpp 2019-06-26 23:28:22.167877404 +0900 +++ new/src/hotspot/share/services/attachListener.cpp 2019-06-26 23:28:22.064877366 +0900 @@ -45,7 +45,7 @@ #include "utilities/debug.hpp" #include "utilities/formatBuffer.hpp" -volatile bool AttachListener::_initialized; +volatile AttachListenerState AttachListener::_state = AL_NOT_INITIALIZED; // Implementation of "properties" command. // @@ -372,6 +372,7 @@ "Should already be setup"); if (AttachListener::pd_init() != 0) { + AttachListener::set_state(AL_NOT_INITIALIZED); return; } AttachListener::set_initialized(); @@ -379,6 +380,7 @@ for (;;) { AttachOperation* op = AttachListener::dequeue(); if (op == NULL) { + AttachListener::set_state(AL_NOT_INITIALIZED); return; // dequeue failed or shutdown } @@ -422,6 +424,8 @@ // operation complete - send result and output to client op->complete(res, &st); } + + AttachListener::set_state(AL_NOT_INITIALIZED); } bool AttachListener::has_init_error(TRAPS) { @@ -445,6 +449,7 @@ const char thread_name[] = "Attach Listener"; Handle string = java_lang_String::create_from_str(thread_name, THREAD); if (has_init_error(THREAD)) { + set_state(AL_NOT_INITIALIZED); return; } @@ -456,6 +461,7 @@ string, THREAD); if (has_init_error(THREAD)) { + set_state(AL_NOT_INITIALIZED); return; } @@ -469,6 +475,7 @@ thread_oop, THREAD); if (has_init_error(THREAD)) { + set_state(AL_NOT_INITIALIZED); return; } --- old/src/hotspot/share/services/attachListener.hpp 2019-06-26 23:28:22.565877550 +0900 +++ new/src/hotspot/share/services/attachListener.hpp 2019-06-26 23:28:22.464877513 +0900 @@ -26,6 +26,8 @@ #define SHARE_SERVICES_ATTACHLISTENER_HPP #include "memory/allocation.hpp" +#include "metaprogramming/isRegisteredEnum.hpp" +#include "runtime/atomic.hpp" #include "utilities/debug.hpp" #include "utilities/globalDefinitions.hpp" #include "utilities/macros.hpp" @@ -49,6 +51,14 @@ AttachOperationFunction func; }; +enum AttachListenerState { + AL_NOT_INITIALIZED, + AL_INITIALIZING, + AL_INITIALIZED +}; + +template<> struct IsRegisteredEnum : public TrueType {}; + class AttachListener: AllStatic { public: static void vm_start() NOT_SERVICES_RETURN; @@ -58,6 +68,9 @@ // invoke to perform clean-up tasks when all clients detach static void detachall() NOT_SERVICES_RETURN; + // check unix domain socket file on filesystem + static bool check_socket_file() NOT_SERVICES_RETURN_(false); + // indicates if the Attach Listener needs to be created at startup static bool init_at_startup() NOT_SERVICES_RETURN_(false); @@ -67,12 +80,31 @@ #if !INCLUDE_SERVICES static bool is_attach_supported() { return false; } #else + private: - static volatile bool _initialized; + static volatile AttachListenerState _state; public: - static bool is_initialized() { return _initialized; } - static void set_initialized() { _initialized = true; } + static void set_state(AttachListenerState new_state) { + Atomic::store(new_state, &_state); + } + + static AttachListenerState get_state() { + return Atomic::load(&_state); + } + + static AttachListenerState transit_state(AttachListenerState new_state, + AttachListenerState cmp_state) { + return Atomic::cmpxchg(new_state, &_state, cmp_state); + } + + static bool is_initialized() { + return Atomic::load(&_state) == AL_INITIALIZED; + } + + static void set_initialized() { + Atomic::store(AL_INITIALIZED, &_state); + } // indicates if this VM supports attach-on-demand static bool is_attach_supported() { return !DisableAttachMechanism; } --- /dev/null 2019-06-26 21:09:14.549961700 +0900 +++ new/test/hotspot/jtreg/serviceability/attach/ConcAttachTest.java 2019-06-26 23:28:22.860877659 +0900 @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8225690 + * @library /test/lib + * @modules jdk.attach/com.sun.tools.attach + * @run main ConcAttachTest + */ + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +import com.sun.tools.attach.VirtualMachine; +import com.sun.tools.attach.AttachNotSupportedException; + +import jdk.test.lib.apps.LingeredApp; +import jdk.test.lib.Asserts; +import jdk.test.lib.JDKToolLauncher; +import jdk.test.lib.process.OutputAnalyzer; + +public class ConcAttachTest implements Runnable { + + private static final int NUM_CONC_REQUESTS = 100; + + private static final int THREAD_POOL_TIMEOUT_IN_SEC = 30; + + private static CountDownLatch latch; + + private static String strPID; + + // Attach to LingeredApp concurrently. + public void run() { + VirtualMachine vm = null; + + try { + latch.countDown(); + latch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + try { + vm = VirtualMachine.attach(strPID); + } catch (AttachNotSupportedException | IOException e) { + throw new RuntimeException(e); + } finally { + try { + vm.detach(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + private static void checkAttachListenerThread() throws InterruptedException, IOException { + JDKToolLauncher jcmd = JDKToolLauncher.createUsingTestJDK("jcmd"); + jcmd.addToolArg(strPID); + jcmd.addToolArg("Thread.print"); + + ProcessBuilder pb = new ProcessBuilder(jcmd.getCommand()); + Process jcmdProc = pb.start(); + + OutputAnalyzer out = new OutputAnalyzer(jcmdProc); + + jcmdProc.waitFor(); + + System.out.println(out.getStdout()); + System.err.println(out.getStderr()); + + long numOfAttachListener = out.asLines() + .stream() + .filter(l -> l.contains("Attach Listener")) + .count(); + + Asserts.assertEquals(1L, numOfAttachListener, "AttachListener should exist only 1 thread."); + } + + public static void main(String... args) throws Exception { + LingeredApp app = null; + latch = new CountDownLatch(NUM_CONC_REQUESTS); + ExecutorService pool = Executors.newFixedThreadPool(NUM_CONC_REQUESTS); + + try { + app = LingeredApp.startApp(); + strPID = Long.toString(app.getPid()); + + for (int i = 0; i < NUM_CONC_REQUESTS; i++) { + pool.submit(new ConcAttachTest()); + } + + pool.shutdown(); + pool.awaitTermination(THREAD_POOL_TIMEOUT_IN_SEC, TimeUnit.SECONDS); + + checkAttachListenerThread(); + } finally { + LingeredApp.stopApp(app); + } + } + +} --- /dev/null 2019-06-26 21:09:14.549961700 +0900 +++ new/test/hotspot/jtreg/serviceability/attach/RemovingUnixDomainSocketTest.java 2019-06-26 23:28:23.267877809 +0900 @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8225193 + * @library /test/lib + * @run main RemovingUnixDomainSocketTest + */ + +import java.io.IOException; +import java.nio.file.Path; + +import jdk.test.lib.apps.LingeredApp; +import jdk.test.lib.JDKToolLauncher; +import jdk.test.lib.process.OutputAnalyzer; + +public class RemovingUnixDomainSocketTest { + + private static void runJCmd(long pid) throws InterruptedException, IOException { + JDKToolLauncher jcmd = JDKToolLauncher.createUsingTestJDK("jcmd"); + jcmd.addToolArg(Long.toString(pid)); + jcmd.addToolArg("VM.version"); + + ProcessBuilder pb = new ProcessBuilder(jcmd.getCommand()); + Process jcmdProc = pb.start(); + + OutputAnalyzer out = new OutputAnalyzer(jcmdProc); + + jcmdProc.waitFor(); + + System.out.println(out.getStdout()); + System.err.println(out.getStderr()); + + out.stderrShouldBeEmpty(); + } + + public static void main(String... args) throws Exception { + LingeredApp app = null; + try { + app = LingeredApp.startApp(); + + // Access to Attach Listener + runJCmd(app.getPid()); + + // Remove unix domain socket file + var sockFile = Path.of(System.getProperty("java.io.tmpdir"), + ".java_pid" + app.getPid()) + .toFile(); + System.out.println("Remove " + sockFile.toString()); + sockFile.delete(); + + // Access to Attach Listener again + runJCmd(app.getPid()); + } finally { + LingeredApp.stopApp(app); + } + } + +}