src/os/solaris/vm/attachListener_solaris.cpp

Thu, 19 Mar 2009 09:13:24 -0700

author
kvn
date
Thu, 19 Mar 2009 09:13:24 -0700
changeset 1082
bd441136a5ce
parent 435
a61af66fc99e
child 1759
e392695de029
permissions
-rw-r--r--

Merge

     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   sprintf(door_path, "%s/.java_pid%d", os::get_temp_directory(), os::current_process_id());
   379   RESTARTABLE(::creat(door_path, S_IRUSR | S_IWUSR), fd);
   381   if (fd == -1) {
   382     debug_only(warning("attempt to create %s failed", door_path));
   383     return -1;
   384   }
   385   assert(fd >= 0, "bad file descriptor");
   386   set_door_path(door_path);
   387   RESTARTABLE(::close(fd), res);
   389   // attach the door descriptor to the file
   390   if ((res = ::fattach(dd, door_path)) == -1) {
   391     // if busy then detach and try again
   392     if (errno == EBUSY) {
   393       ::fdetach(door_path);
   394       res = ::fattach(dd, door_path);
   395     }
   396     if (res == -1) {
   397       ::door_revoke(dd);
   398       dd = -1;
   399     }
   400   }
   401   if (dd >= 0) {
   402     set_door_descriptor(dd);
   403   } else {
   404     // unable to create door or attach it to the file
   405     ::unlink(door_path);
   406     set_door_path(NULL);
   407     return -1;
   408   }
   410   return 0;
   411 }
   413 // Initialization - create the door, locks, and other initialization
   414 int SolarisAttachListener::init() {
   415   if (create_door()) {
   416     return -1;
   417   }
   419   int status = os::Solaris::mutex_init(&_mutex);
   420   assert_status(status==0, status, "mutex_init");
   422   status = ::sema_init(&_wakeup, 0, NULL, NULL);
   423   assert_status(status==0, status, "sema_init");
   425   set_head(NULL);
   426   set_tail(NULL);
   428   return 0;
   429 }
   431 // Dequeue an operation
   432 SolarisAttachOperation* SolarisAttachListener::dequeue() {
   433   for (;;) {
   434     int res;
   436     // wait for somebody to enqueue something
   437     while ((res = ::sema_wait(wakeup())) == EINTR)
   438       ;
   439     if (res) {
   440       warning("sema_wait failed: %s", strerror(res));
   441       return NULL;
   442     }
   444     // lock the list
   445     res = os::Solaris::mutex_lock(mutex());
   446     assert(res == 0, "mutex_lock failed");
   448     // remove the head of the list
   449     SolarisAttachOperation* op = head();
   450     if (op != NULL) {
   451       set_head(op->next());
   452       if (head() == NULL) {
   453         set_tail(NULL);
   454       }
   455     }
   457     // unlock
   458     os::Solaris::mutex_unlock(mutex());
   460     // if we got an operation when return it.
   461     if (op != NULL) {
   462       return op;
   463     }
   464   }
   465 }
   467 // Enqueue an operation
   468 void SolarisAttachListener::enqueue(SolarisAttachOperation* op) {
   469   // lock list
   470   int res = os::Solaris::mutex_lock(mutex());
   471   assert(res == 0, "mutex_lock failed");
   473   // enqueue at tail
   474   op->set_next(NULL);
   475   if (head() == NULL) {
   476     set_head(op);
   477   } else {
   478     tail()->set_next(op);
   479   }
   480   set_tail(op);
   482   // wakeup the attach listener
   483   RESTARTABLE(::sema_post(wakeup()), res);
   484   assert(res == 0, "sema_post failed");
   486   // unlock
   487   os::Solaris::mutex_unlock(mutex());
   488 }
   491 // support function - writes the (entire) buffer to a socket
   492 static int write_fully(int s, char* buf, int len) {
   493   do {
   494     int n = ::write(s, buf, len);
   495     if (n == -1) {
   496       if (errno != EINTR) return -1;
   497     } else {
   498       buf += n;
   499       len -= n;
   500     }
   501   }
   502   while (len > 0);
   503   return 0;
   504 }
   506 // Complete an operation by sending the operation result and any result
   507 // output to the client. At this time the socket is in blocking mode so
   508 // potentially we can block if there is a lot of data and the client is
   509 // non-responsive. For most operations this is a non-issue because the
   510 // default send buffer is sufficient to buffer everything. In the future
   511 // if there are operations that involves a very big reply then it the
   512 // socket could be made non-blocking and a timeout could be used.
   514 void SolarisAttachOperation::complete(jint res, bufferedStream* st) {
   515   if (this->socket() >= 0) {
   516     JavaThread* thread = JavaThread::current();
   517     ThreadBlockInVM tbivm(thread);
   519     thread->set_suspend_equivalent();
   520     // cleared by handle_special_suspend_equivalent_condition() or
   521     // java_suspend_self() via check_and_wait_while_suspended()
   523     // write operation result
   524     char msg[32];
   525     sprintf(msg, "%d\n", res);
   526     int rc = write_fully(this->socket(), msg, strlen(msg));
   528     // write any result data
   529     if (rc == 0) {
   530       write_fully(this->socket(), (char*) st->base(), st->size());
   531       ::shutdown(this->socket(), 2);
   532     }
   534     // close socket and we're done
   535     RESTARTABLE(::close(this->socket()), rc);
   537     // were we externally suspended while we were waiting?
   538     thread->check_and_wait_while_suspended();
   539   }
   540   delete this;
   541 }
   544 // AttachListener functions
   546 AttachOperation* AttachListener::dequeue() {
   547   JavaThread* thread = JavaThread::current();
   548   ThreadBlockInVM tbivm(thread);
   550   thread->set_suspend_equivalent();
   551   // cleared by handle_special_suspend_equivalent_condition() or
   552   // java_suspend_self() via check_and_wait_while_suspended()
   554   AttachOperation* op = SolarisAttachListener::dequeue();
   556   // were we externally suspended while we were waiting?
   557   thread->check_and_wait_while_suspended();
   559   return op;
   560 }
   562 int AttachListener::pd_init() {
   563   JavaThread* thread = JavaThread::current();
   564   ThreadBlockInVM tbivm(thread);
   566   thread->set_suspend_equivalent();
   567   // cleared by handle_special_suspend_equivalent_condition() or
   568   // java_suspend_self()
   570   int ret_code = SolarisAttachListener::init();
   572   // were we externally suspended while we were waiting?
   573   thread->check_and_wait_while_suspended();
   575   return ret_code;
   576 }
   578 // Attach Listener is started lazily except in the case when
   579 // +ReduseSignalUsage is used
   580 bool AttachListener::init_at_startup() {
   581   if (ReduceSignalUsage) {
   582     return true;
   583   } else {
   584     return false;
   585   }
   586 }
   588 // If the file .attach_pid<pid> exists in the working directory
   589 // or /tmp then this is the trigger to start the attach mechanism
   590 bool AttachListener::is_init_trigger() {
   591   if (init_at_startup() || is_initialized()) {
   592     return false;               // initialized at startup or already initialized
   593   }
   594   char fn[32];
   595   sprintf(fn, ".attach_pid%d", os::current_process_id());
   596   int ret;
   597   struct stat64 st;
   598   RESTARTABLE(::stat64(fn, &st), ret);
   599   if (ret == -1) {
   600     sprintf(fn, "/tmp/.attach_pid%d", os::current_process_id());
   601     RESTARTABLE(::stat64(fn, &st), ret);
   602   }
   603   if (ret == 0) {
   604     // simple check to avoid starting the attach mechanism when
   605     // a bogus user creates the file
   606     if (st.st_uid == geteuid()) {
   607       init();
   608       return true;
   609     }
   610   }
   611   return false;
   612 }
   614 // if VM aborts then detach/cleanup
   615 void AttachListener::abort() {
   616   listener_cleanup();
   617 }
   619 void AttachListener::pd_data_dump() {
   620   os::signal_notify(SIGQUIT);
   621 }
   623 static jint enable_dprobes(AttachOperation* op, outputStream* out) {
   624   const char* probe = op->arg(0);
   625   if (probe == NULL || probe[0] == '\0') {
   626     out->print_cr("No probe specified");
   627     return JNI_ERR;
   628   } else {
   629     int probe_typess = atoi(probe);
   630     if (errno) {
   631       out->print_cr("invalid probe type");
   632       return JNI_ERR;
   633     } else {
   634       DTrace::enable_dprobes(probe_typess);
   635       return JNI_OK;
   636     }
   637   }
   638 }
   640 // platform specific operations table
   641 static AttachOperationFunctionInfo funcs[] = {
   642   { "enabledprobes", enable_dprobes },
   643   { NULL, NULL }
   644 };
   646 AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* name) {
   647   int i;
   648   for (i = 0; funcs[i].name != NULL; i++) {
   649     if (strcmp(funcs[i].name, name) == 0) {
   650       return &funcs[i];
   651     }
   652   }
   653   return NULL;
   654 }
   656 // Solaris specific global flag set. Currently, we support only
   657 // changing ExtendedDTraceProbes flag.
   658 jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
   659   const char* name = op->arg(0);
   660   assert(name != NULL, "flag name should not be null");
   661   bool flag = true;
   662   const char* arg1;
   663   if ((arg1 = op->arg(1)) != NULL) {
   664     flag = (atoi(arg1) != 0);
   665     if (errno) {
   666       out->print_cr("flag value has to be an integer");
   667       return JNI_ERR;
   668     }
   669   }
   671   if (strcmp(name, "ExtendedDTraceProbes") != 0) {
   672     out->print_cr("flag '%s' cannot be changed", name);
   673     return JNI_ERR;
   674   }
   676   DTrace::set_extended_dprobes(flag);
   677   return JNI_OK;
   678 }
   680 void AttachListener::pd_detachall() {
   681   DTrace::detach_all_clients();
   682 }

mercurial