src/os/solaris/vm/attachListener_solaris.cpp

Mon, 19 Apr 2010 18:58:31 -0400

author
coleenp
date
Mon, 19 Apr 2010 18:58:31 -0400
changeset 1852
96d554193f72
parent 1788
a2ea687fdc7c
child 1907
c18cbe5936b8
permissions
-rw-r--r--

6944822: Fix for 6938627 exposes problem with hard-coded buffer sizes
Summary: Make tmpdir buffer sizes MAX_PATH+1
Reviewed-by: dholmes, coleenp
Contributed-by: andreas.kohn@fredhopper.com

     1 /*
     2  * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    20  * CA 95054 USA or visit www.sun.com if you need additional information or
    21  * have any questions.
    22  *
    23  */
    25 # include "incls/_precompiled.incl"
    26 # include "incls/_attachListener_solaris.cpp.incl"
    28 #include <door.h>
    29 #include <string.h>
    30 #include <signal.h>
    31 #include <sys/types.h>
    32 #include <sys/socket.h>
    33 #include <sys/stat.h>
    35 // stropts.h uses STR in stream ioctl defines
    36 #undef STR
    37 #include <stropts.h>
    38 #undef STR
    39 #define STR(a) #a
    41 // The attach mechanism on Solaris is implemented using the Doors IPC
    42 // mechanism. The first tool to attempt to attach causes the attach
    43 // listener thread to startup. This thread creats a door that is
    44 // associated with a function that enqueues an operation to the attach
    45 // listener. The door is attached to a file in the file system so that
    46 // client (tools) can locate it. To enqueue an operation to the VM the
    47 // client calls through the door which invokes the enqueue function in
    48 // this process. The credentials of the client are checked and if the
    49 // effective uid matches this process then the operation is enqueued.
    50 // When an operation completes the attach listener is required to send the
    51 // operation result and any result data to the client. In this implementation
    52 // the result is returned via a UNIX domain socket. A pair of connected
    53 // sockets (socketpair) is created in the enqueue function and the file
    54 // descriptor for one of the sockets is returned to the client as the
    55 // return from the door call. The other end is retained in this process.
    56 // When the operation completes the result is sent to the client and
    57 // the socket is closed.
    59 // forward reference
    60 class SolarisAttachOperation;
    62 class SolarisAttachListener: AllStatic {
    63  private:
    65   // the path to which we attach the door file descriptor
    66   static char _door_path[PATH_MAX+1];
    67   static volatile bool _has_door_path;
    69   // door descriptor returned by door_create
    70   static int _door_descriptor;
    72   static void set_door_path(char* path) {
    73     if (path == NULL) {
    74       _has_door_path = false;
    75     } else {
    76       strncpy(_door_path, path, PATH_MAX);
    77       _door_path[PATH_MAX] = '\0';      // ensure it's nul terminated
    78       _has_door_path = true;
    79     }
    80   }
    82   static void set_door_descriptor(int dd)               { _door_descriptor = dd; }
    84   // mutex to protect operation list
    85   static mutex_t _mutex;
    87   // semaphore to wakeup listener thread
    88   static sema_t _wakeup;
    90   static mutex_t* mutex()                               { return &_mutex; }
    91   static sema_t* wakeup()                               { return &_wakeup; }
    93   // enqueued operation list
    94   static SolarisAttachOperation* _head;
    95   static SolarisAttachOperation* _tail;
    97   static SolarisAttachOperation* head()                 { return _head; }
    98   static void set_head(SolarisAttachOperation* head)    { _head = head; }
   100   static SolarisAttachOperation* tail()                 { return _tail; }
   101   static void set_tail(SolarisAttachOperation* tail)    { _tail = tail; }
   103   // create the door
   104   static int create_door();
   106  public:
   107   enum {
   108     ATTACH_PROTOCOL_VER = 1                             // protocol version
   109   };
   110   enum {
   111     ATTACH_ERROR_BADREQUEST     = 100,                  // error code returned by
   112     ATTACH_ERROR_BADVERSION     = 101,                  // the door call
   113     ATTACH_ERROR_RESOURCE       = 102,
   114     ATTACH_ERROR_INTERNAL       = 103,
   115     ATTACH_ERROR_DENIED         = 104
   116   };
   118   // initialize the listener
   119   static int init();
   121   static bool has_door_path()                           { return _has_door_path; }
   122   static char* door_path()                              { return _door_path; }
   123   static int door_descriptor()                          { return _door_descriptor; }
   125   // enqueue an operation
   126   static void enqueue(SolarisAttachOperation* op);
   128   // dequeue an operation
   129   static SolarisAttachOperation* dequeue();
   130 };
   133 // SolarisAttachOperation is an AttachOperation that additionally encapsulates
   134 // a socket connection to the requesting client/tool. SolarisAttachOperation
   135 // can additionally be held in a linked list.
   137 class SolarisAttachOperation: public AttachOperation {
   138  private:
   139   friend class SolarisAttachListener;
   141   // connection to client
   142   int _socket;
   144   // linked list support
   145   SolarisAttachOperation* _next;
   147   SolarisAttachOperation* next()                         { return _next; }
   148   void set_next(SolarisAttachOperation* next)            { _next = next; }
   150  public:
   151   void complete(jint res, bufferedStream* st);
   153   int socket() const                                     { return _socket; }
   154   void set_socket(int s)                                 { _socket = s; }
   156   SolarisAttachOperation(char* name) : AttachOperation(name) {
   157     set_socket(-1);
   158     set_next(NULL);
   159   }
   160 };
   162 // statics
   163 char SolarisAttachListener::_door_path[PATH_MAX+1];
   164 volatile bool SolarisAttachListener::_has_door_path;
   165 int SolarisAttachListener::_door_descriptor = -1;
   166 mutex_t SolarisAttachListener::_mutex;
   167 sema_t SolarisAttachListener::_wakeup;
   168 SolarisAttachOperation* SolarisAttachListener::_head = NULL;
   169 SolarisAttachOperation* SolarisAttachListener::_tail = NULL;
   171 // Supporting class to help split a buffer into individual components
   172 class ArgumentIterator : public StackObj {
   173  private:
   174   char* _pos;
   175   char* _end;
   176  public:
   177   ArgumentIterator(char* arg_buffer, size_t arg_size) {
   178     _pos = arg_buffer;
   179     _end = _pos + arg_size - 1;
   180   }
   181   char* next() {
   182     if (*_pos == '\0') {
   183       return NULL;
   184     }
   185     char* res = _pos;
   186     char* next_pos = strchr(_pos, '\0');
   187     if (next_pos < _end)  {
   188       next_pos++;
   189     }
   190     _pos = next_pos;
   191     return res;
   192   }
   193 };
   195 // Calls from the door function to check that the client credentials
   196 // match this process. Returns 0 if credentials okay, otherwise -1.
   197 static int check_credentials() {
   198   door_cred_t cred_info;
   200   // get client credentials
   201   if (door_cred(&cred_info) == -1) {
   202     return -1; // unable to get them
   203   }
   205   // get our euid/eguid (probably could cache these)
   206   uid_t euid = geteuid();
   207   gid_t egid = getegid();
   209   // check that the effective uid/gid matches - discuss this with Jeff.
   210   if (cred_info.dc_euid == euid && cred_info.dc_egid == egid) {
   211     return 0;  // okay
   212   } else {
   213     return -1; // denied
   214   }
   215 }
   218 // Parses the argument buffer to create an AttachOperation that we should
   219 // enqueue to the attach listener.
   220 // The buffer is expected to be formatted as follows:
   221 // <ver>0<cmd>0<arg>0<arg>0<arg>0
   222 // where <ver> is the version number (must be "1"), <cmd> is the command
   223 // name ("load, "datadump", ...) and <arg> is an argument.
   224 //
   225 static SolarisAttachOperation* create_operation(char* argp, size_t arg_size, int* err) {
   226   // assume bad request until parsed
   227   *err = SolarisAttachListener::ATTACH_ERROR_BADREQUEST;
   229   if (arg_size < 2 || argp[arg_size-1] != '\0') {
   230     return NULL;   // no ver or not null terminated
   231   }
   233   // Use supporting class to iterate over the buffer
   234   ArgumentIterator args(argp, arg_size);
   236   // First check the protocol version
   237   char* ver = args.next();
   238   if (ver == NULL) {
   239     return NULL;
   240   }
   241   if (atoi(ver) != SolarisAttachListener::ATTACH_PROTOCOL_VER) {
   242     *err = SolarisAttachListener::ATTACH_ERROR_BADVERSION;
   243     return NULL;
   244   }
   246   // Get command name and create the operation
   247   char* name = args.next();
   248   if (name == NULL || strlen(name) > AttachOperation::name_length_max) {
   249     return NULL;
   250   }
   251   SolarisAttachOperation* op = new SolarisAttachOperation(name);
   253   // Iterate over the arguments
   254   for (int i=0; i<AttachOperation::arg_count_max; i++) {
   255     char* arg = args.next();
   256     if (arg == NULL) {
   257       op->set_arg(i, NULL);
   258     } else {
   259       if (strlen(arg) > AttachOperation::arg_length_max) {
   260         delete op;
   261         return NULL;
   262       }
   263       op->set_arg(i, arg);
   264     }
   265   }
   267   // return operation
   268   *err = 0;
   269   return op;
   270 }
   272 // create special operation to indicate all clients have detached
   273 static SolarisAttachOperation* create_detachall_operation() {
   274   return new SolarisAttachOperation(AttachOperation::detachall_operation_name());
   275 }
   277 // This is door function which the client executes via a door_call.
   278 extern "C" {
   279   static void enqueue_proc(void* cookie, char* argp, size_t arg_size,
   280                            door_desc_t* dt, uint_t n_desc)
   281   {
   282     int return_fd = -1;
   283     SolarisAttachOperation* op = NULL;
   285     // no listener
   286     jint res = 0;
   287     if (!AttachListener::is_initialized()) {
   288       // how did we get here?
   289       debug_only(warning("door_call when not enabled"));
   290       res = (jint)SolarisAttachListener::ATTACH_ERROR_INTERNAL;
   291     }
   293     // check client credentials
   294     if (res == 0) {
   295       if (check_credentials() != 0) {
   296         res = (jint)SolarisAttachListener::ATTACH_ERROR_DENIED;
   297       }
   298     }
   300     // if we are stopped at ShowMessageBoxOnError then maybe we can
   301     // load a diagnostic library
   302     if (res == 0 && is_error_reported()) {
   303       if (ShowMessageBoxOnError) {
   304         // TBD - support loading of diagnostic library here
   305       }
   307       // can't enqueue operation after fatal error
   308       res = (jint)SolarisAttachListener::ATTACH_ERROR_RESOURCE;
   309     }
   311     // create the operation
   312     if (res == 0) {
   313       int err;
   314       op = create_operation(argp, arg_size, &err);
   315       res = (op == NULL) ? (jint)err : 0;
   316     }
   318     // create a pair of connected sockets. Store the file descriptor
   319     // for one end in the operation and enqueue the operation. The
   320     // file descriptor for the other end wil be returned to the client.
   321     if (res == 0) {
   322       int s[2];
   323       if (socketpair(PF_UNIX, SOCK_STREAM, 0, s) < 0) {
   324         delete op;
   325         res = (jint)SolarisAttachListener::ATTACH_ERROR_RESOURCE;
   326       } else {
   327         op->set_socket(s[0]);
   328         return_fd = s[1];
   329         SolarisAttachListener::enqueue(op);
   330       }
   331     }
   333     // Return 0 (success) + file descriptor, or non-0 (error)
   334     if (res == 0) {
   335       door_desc_t desc;
   336       desc.d_attributes = DOOR_DESCRIPTOR;
   337       desc.d_data.d_desc.d_descriptor = return_fd;
   338       door_return((char*)&res, sizeof(res), &desc, 1);
   339     } else {
   340       door_return((char*)&res, sizeof(res), NULL, 0);
   341     }
   342   }
   343 }
   345 // atexit hook to detach the door and remove the file
   346 extern "C" {
   347   static void listener_cleanup() {
   348     static int cleanup_done;
   349     if (!cleanup_done) {
   350       cleanup_done = 1;
   351       int dd = SolarisAttachListener::door_descriptor();
   352       if (dd >= 0) {
   353         ::close(dd);
   354       }
   355       if (SolarisAttachListener::has_door_path()) {
   356         char* path = SolarisAttachListener::door_path();
   357         ::fdetach(path);
   358         ::unlink(path);
   359       }
   360     }
   361   }
   362 }
   364 // Create the door
   365 int SolarisAttachListener::create_door() {
   366   char door_path[PATH_MAX+1];
   367   int fd, res;
   369   // register exit function
   370   ::atexit(listener_cleanup);
   372   // create the door descriptor
   373   int dd = ::door_create(enqueue_proc, NULL, 0);
   374   if (dd < 0) {
   375     return -1;
   376   }
   378   snprintf(door_path, sizeof(door_path), "%s/.java_pid%d",
   379            os::get_temp_directory(), os::current_process_id());
   380   RESTARTABLE(::creat(door_path, S_IRUSR | S_IWUSR), fd);
   382   if (fd == -1) {
   383     debug_only(warning("attempt to create %s failed", door_path));
   384     return -1;
   385   }
   386   assert(fd >= 0, "bad file descriptor");
   387   set_door_path(door_path);
   388   RESTARTABLE(::close(fd), res);
   390   // attach the door descriptor to the file
   391   if ((res = ::fattach(dd, door_path)) == -1) {
   392     // if busy then detach and try again
   393     if (errno == EBUSY) {
   394       ::fdetach(door_path);
   395       res = ::fattach(dd, door_path);
   396     }
   397     if (res == -1) {
   398       ::door_revoke(dd);
   399       dd = -1;
   400     }
   401   }
   402   if (dd >= 0) {
   403     set_door_descriptor(dd);
   404   } else {
   405     // unable to create door or attach it to the file
   406     ::unlink(door_path);
   407     set_door_path(NULL);
   408     return -1;
   409   }
   411   return 0;
   412 }
   414 // Initialization - create the door, locks, and other initialization
   415 int SolarisAttachListener::init() {
   416   if (create_door()) {
   417     return -1;
   418   }
   420   int status = os::Solaris::mutex_init(&_mutex);
   421   assert_status(status==0, status, "mutex_init");
   423   status = ::sema_init(&_wakeup, 0, NULL, NULL);
   424   assert_status(status==0, status, "sema_init");
   426   set_head(NULL);
   427   set_tail(NULL);
   429   return 0;
   430 }
   432 // Dequeue an operation
   433 SolarisAttachOperation* SolarisAttachListener::dequeue() {
   434   for (;;) {
   435     int res;
   437     // wait for somebody to enqueue something
   438     while ((res = ::sema_wait(wakeup())) == EINTR)
   439       ;
   440     if (res) {
   441       warning("sema_wait failed: %s", strerror(res));
   442       return NULL;
   443     }
   445     // lock the list
   446     res = os::Solaris::mutex_lock(mutex());
   447     assert(res == 0, "mutex_lock failed");
   449     // remove the head of the list
   450     SolarisAttachOperation* op = head();
   451     if (op != NULL) {
   452       set_head(op->next());
   453       if (head() == NULL) {
   454         set_tail(NULL);
   455       }
   456     }
   458     // unlock
   459     os::Solaris::mutex_unlock(mutex());
   461     // if we got an operation when return it.
   462     if (op != NULL) {
   463       return op;
   464     }
   465   }
   466 }
   468 // Enqueue an operation
   469 void SolarisAttachListener::enqueue(SolarisAttachOperation* op) {
   470   // lock list
   471   int res = os::Solaris::mutex_lock(mutex());
   472   assert(res == 0, "mutex_lock failed");
   474   // enqueue at tail
   475   op->set_next(NULL);
   476   if (head() == NULL) {
   477     set_head(op);
   478   } else {
   479     tail()->set_next(op);
   480   }
   481   set_tail(op);
   483   // wakeup the attach listener
   484   RESTARTABLE(::sema_post(wakeup()), res);
   485   assert(res == 0, "sema_post failed");
   487   // unlock
   488   os::Solaris::mutex_unlock(mutex());
   489 }
   492 // support function - writes the (entire) buffer to a socket
   493 static int write_fully(int s, char* buf, int len) {
   494   do {
   495     int n = ::write(s, buf, len);
   496     if (n == -1) {
   497       if (errno != EINTR) return -1;
   498     } else {
   499       buf += n;
   500       len -= n;
   501     }
   502   }
   503   while (len > 0);
   504   return 0;
   505 }
   507 // Complete an operation by sending the operation result and any result
   508 // output to the client. At this time the socket is in blocking mode so
   509 // potentially we can block if there is a lot of data and the client is
   510 // non-responsive. For most operations this is a non-issue because the
   511 // default send buffer is sufficient to buffer everything. In the future
   512 // if there are operations that involves a very big reply then it the
   513 // socket could be made non-blocking and a timeout could be used.
   515 void SolarisAttachOperation::complete(jint res, bufferedStream* st) {
   516   if (this->socket() >= 0) {
   517     JavaThread* thread = JavaThread::current();
   518     ThreadBlockInVM tbivm(thread);
   520     thread->set_suspend_equivalent();
   521     // cleared by handle_special_suspend_equivalent_condition() or
   522     // java_suspend_self() via check_and_wait_while_suspended()
   524     // write operation result
   525     char msg[32];
   526     sprintf(msg, "%d\n", res);
   527     int rc = write_fully(this->socket(), msg, strlen(msg));
   529     // write any result data
   530     if (rc == 0) {
   531       write_fully(this->socket(), (char*) st->base(), st->size());
   532       ::shutdown(this->socket(), 2);
   533     }
   535     // close socket and we're done
   536     RESTARTABLE(::close(this->socket()), rc);
   538     // were we externally suspended while we were waiting?
   539     thread->check_and_wait_while_suspended();
   540   }
   541   delete this;
   542 }
   545 // AttachListener functions
   547 AttachOperation* AttachListener::dequeue() {
   548   JavaThread* thread = JavaThread::current();
   549   ThreadBlockInVM tbivm(thread);
   551   thread->set_suspend_equivalent();
   552   // cleared by handle_special_suspend_equivalent_condition() or
   553   // java_suspend_self() via check_and_wait_while_suspended()
   555   AttachOperation* op = SolarisAttachListener::dequeue();
   557   // were we externally suspended while we were waiting?
   558   thread->check_and_wait_while_suspended();
   560   return op;
   561 }
   563 int AttachListener::pd_init() {
   564   JavaThread* thread = JavaThread::current();
   565   ThreadBlockInVM tbivm(thread);
   567   thread->set_suspend_equivalent();
   568   // cleared by handle_special_suspend_equivalent_condition() or
   569   // java_suspend_self()
   571   int ret_code = SolarisAttachListener::init();
   573   // were we externally suspended while we were waiting?
   574   thread->check_and_wait_while_suspended();
   576   return ret_code;
   577 }
   579 // Attach Listener is started lazily except in the case when
   580 // +ReduseSignalUsage is used
   581 bool AttachListener::init_at_startup() {
   582   if (ReduceSignalUsage) {
   583     return true;
   584   } else {
   585     return false;
   586   }
   587 }
   589 // If the file .attach_pid<pid> exists in the working directory
   590 // or /tmp then this is the trigger to start the attach mechanism
   591 bool AttachListener::is_init_trigger() {
   592   if (init_at_startup() || is_initialized()) {
   593     return false;               // initialized at startup or already initialized
   594   }
   595   char fn[PATH_MAX+1];
   596   sprintf(fn, ".attach_pid%d", os::current_process_id());
   597   int ret;
   598   struct stat64 st;
   599   RESTARTABLE(::stat64(fn, &st), ret);
   600   if (ret == -1) {
   601     snprintf(fn, sizeof(fn), "%s/.attach_pid%d",
   602              os::get_temp_directory(), os::current_process_id());
   603     RESTARTABLE(::stat64(fn, &st), ret);
   604   }
   605   if (ret == 0) {
   606     // simple check to avoid starting the attach mechanism when
   607     // a bogus user creates the file
   608     if (st.st_uid == geteuid()) {
   609       init();
   610       return true;
   611     }
   612   }
   613   return false;
   614 }
   616 // if VM aborts then detach/cleanup
   617 void AttachListener::abort() {
   618   listener_cleanup();
   619 }
   621 void AttachListener::pd_data_dump() {
   622   os::signal_notify(SIGQUIT);
   623 }
   625 static jint enable_dprobes(AttachOperation* op, outputStream* out) {
   626   const char* probe = op->arg(0);
   627   if (probe == NULL || probe[0] == '\0') {
   628     out->print_cr("No probe specified");
   629     return JNI_ERR;
   630   } else {
   631     int probe_typess = atoi(probe);
   632     if (errno) {
   633       out->print_cr("invalid probe type");
   634       return JNI_ERR;
   635     } else {
   636       DTrace::enable_dprobes(probe_typess);
   637       return JNI_OK;
   638     }
   639   }
   640 }
   642 // platform specific operations table
   643 static AttachOperationFunctionInfo funcs[] = {
   644   { "enabledprobes", enable_dprobes },
   645   { NULL, NULL }
   646 };
   648 AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* name) {
   649   int i;
   650   for (i = 0; funcs[i].name != NULL; i++) {
   651     if (strcmp(funcs[i].name, name) == 0) {
   652       return &funcs[i];
   653     }
   654   }
   655   return NULL;
   656 }
   658 // Solaris specific global flag set. Currently, we support only
   659 // changing ExtendedDTraceProbes flag.
   660 jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
   661   const char* name = op->arg(0);
   662   assert(name != NULL, "flag name should not be null");
   663   bool flag = true;
   664   const char* arg1;
   665   if ((arg1 = op->arg(1)) != NULL) {
   666     flag = (atoi(arg1) != 0);
   667     if (errno) {
   668       out->print_cr("flag value has to be an integer");
   669       return JNI_ERR;
   670     }
   671   }
   673   if (strcmp(name, "ExtendedDTraceProbes") == 0) {
   674     DTrace::set_extended_dprobes(flag);
   675     return JNI_OK;
   676   }
   678   if (strcmp(name, "DTraceMonitorProbes") == 0) {
   679     DTrace::set_monitor_dprobes(flag);
   680     return JNI_OK;
   681   }
   683   out->print_cr("flag '%s' cannot be changed", name);
   684   return JNI_ERR;
   685 }
   687 void AttachListener::pd_detachall() {
   688   DTrace::detach_all_clients();
   689 }

mercurial