$OpenBSD: patch-hotspot_src_os_bsd_vm_attachListener_bsd_cpp,v 1.1 2013/02/01 15:34:35 kurt Exp $
--- hotspot/src/os/bsd/vm/attachListener_bsd.cpp.orig	Tue Jan 29 12:03:16 2013
+++ hotspot/src/os/bsd/vm/attachListener_bsd.cpp	Tue Jan 29 12:08:58 2013
@@ -170,41 +170,58 @@ extern "C" {
 // Initialization - create a listener socket and bind it to a file
 
 int BsdAttachListener::init() {
-  char path[UNIX_PATH_MAX];        // socket file
-  int listener;                 // listener socket (file descriptor)
+  char path[UNIX_PATH_MAX];          // socket file
+  char initial_path[UNIX_PATH_MAX];  // socket file during setup
+  int listener;                      // listener socket (file descriptor)
 
   // register function to cleanup
   ::atexit(listener_cleanup);
 
+  int n = snprintf(path, UNIX_PATH_MAX, "%s/.java_pid%d",
+                   os::get_temp_directory(), os::current_process_id());
+  if (n < (int)UNIX_PATH_MAX) {
+    n = snprintf(initial_path, UNIX_PATH_MAX, "%s.tmp", path);
+  }
+  if (n >= (int)UNIX_PATH_MAX) {
+    return -1;
+  }
+
   // create the listener socket
   listener = ::socket(PF_UNIX, SOCK_STREAM, 0);
   if (listener == -1) {
     return -1;
   }
 
-  int res = -1;
+  // bind socket
   struct sockaddr_un addr;
   addr.sun_family = AF_UNIX;
-
-  snprintf(path, UNIX_PATH_MAX, "%s/.java_pid%d",
-           os::get_temp_directory(), os::current_process_id());
-  strcpy(addr.sun_path, path);
-  ::unlink(path);
-  res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr));
+  strcpy(addr.sun_path, initial_path);
+  ::unlink(initial_path);
+  int res = ::bind(listener, (struct sockaddr*)&addr, sizeof(addr));
   if (res == -1) {
     RESTARTABLE(::close(listener), res);
     return -1;
   }
-  set_path(path);
 
-  // put in listen mode and set permission and ownership
-  if ((::listen(listener, 5) == -1) || (::chmod(path, S_IREAD|S_IWRITE) == -1) ||
-      (::chown(path, geteuid(), getegid()) == -1)) {
+  // put in listen mode, set permissions, and rename into place
+  res = ::listen(listener, 5);
+  if (res == 0) {
+    RESTARTABLE(::chmod(initial_path, S_IREAD|S_IWRITE), res);
+    if (res == 0) {
+      // make sure the file is owned by the effective user and effective group
+      // (this is the default on linux, but not on mac os)
+      RESTARTABLE(::chown(initial_path, geteuid(), getegid()), res);
+      if (res == 0) {
+        res = ::rename(initial_path, path);
+      }
+    }
+  }
+  if (res == -1) {
     RESTARTABLE(::close(listener), res);
-    ::unlink(path);
-    set_path(NULL);
+    ::unlink(initial_path);
     return -1;
   }
+  set_path(path);
   set_listener(listener);
 
   return 0;
