attachListener_solaris.cpp revision 10627:1537c752a7f5
1/*
2 * Copyright (c) 2005, 2016, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "runtime/interfaceSupport.hpp"
27#include "runtime/os.inline.hpp"
28#include "services/attachListener.hpp"
29#include "services/dtraceAttacher.hpp"
30
31#include <door.h>
32#include <limits.h>
33#include <string.h>
34#include <signal.h>
35#include <sys/types.h>
36#include <sys/socket.h>
37#include <sys/stat.h>
38
39// stropts.h uses STR in stream ioctl defines
40#undef STR
41#include <stropts.h>
42#undef STR
43#define STR(a) #a
44
45// The attach mechanism on Solaris is implemented using the Doors IPC
46// mechanism. The first tool to attempt to attach causes the attach
47// listener thread to startup. This thread creats a door that is
48// associated with a function that enqueues an operation to the attach
49// listener. The door is attached to a file in the file system so that
50// client (tools) can locate it. To enqueue an operation to the VM the
51// client calls through the door which invokes the enqueue function in
52// this process. The credentials of the client are checked and if the
53// effective uid matches this process then the operation is enqueued.
54// When an operation completes the attach listener is required to send the
55// operation result and any result data to the client. In this implementation
56// the result is returned via a UNIX domain socket. A pair of connected
57// sockets (socketpair) is created in the enqueue function and the file
58// descriptor for one of the sockets is returned to the client as the
59// return from the door call. The other end is retained in this process.
60// When the operation completes the result is sent to the client and
61// the socket is closed.
62
63// forward reference
64class SolarisAttachOperation;
65
66class SolarisAttachListener: AllStatic {
67 private:
68
69  // the path to which we attach the door file descriptor
70  static char _door_path[PATH_MAX+1];
71  static volatile bool _has_door_path;
72
73  // door descriptor returned by door_create
74  static int _door_descriptor;
75
76  static void set_door_path(char* path) {
77    if (path == NULL) {
78      _has_door_path = false;
79    } else {
80      strncpy(_door_path, path, PATH_MAX);
81      _door_path[PATH_MAX] = '\0';      // ensure it's nul terminated
82      _has_door_path = true;
83    }
84  }
85
86  static void set_door_descriptor(int dd)               { _door_descriptor = dd; }
87
88  // mutex to protect operation list
89  static mutex_t _mutex;
90
91  // semaphore to wakeup listener thread
92  static sema_t _wakeup;
93
94  static mutex_t* mutex()                               { return &_mutex; }
95  static sema_t* wakeup()                               { return &_wakeup; }
96
97  // enqueued operation list
98  static SolarisAttachOperation* _head;
99  static SolarisAttachOperation* _tail;
100
101  static SolarisAttachOperation* head()                 { return _head; }
102  static void set_head(SolarisAttachOperation* head)    { _head = head; }
103
104  static SolarisAttachOperation* tail()                 { return _tail; }
105  static void set_tail(SolarisAttachOperation* tail)    { _tail = tail; }
106
107  // create the door
108  static int create_door();
109
110 public:
111  enum {
112    ATTACH_PROTOCOL_VER = 1                             // protocol version
113  };
114  enum {
115    ATTACH_ERROR_BADREQUEST     = 100,                  // error code returned by
116    ATTACH_ERROR_BADVERSION     = 101,                  // the door call
117    ATTACH_ERROR_RESOURCE       = 102,
118    ATTACH_ERROR_INTERNAL       = 103,
119    ATTACH_ERROR_DENIED         = 104
120  };
121
122  // initialize the listener
123  static int init();
124
125  static bool has_door_path()                           { return _has_door_path; }
126  static char* door_path()                              { return _door_path; }
127  static int door_descriptor()                          { return _door_descriptor; }
128
129  // enqueue an operation
130  static void enqueue(SolarisAttachOperation* op);
131
132  // dequeue an operation
133  static SolarisAttachOperation* dequeue();
134};
135
136
137// SolarisAttachOperation is an AttachOperation that additionally encapsulates
138// a socket connection to the requesting client/tool. SolarisAttachOperation
139// can additionally be held in a linked list.
140
141class SolarisAttachOperation: public AttachOperation {
142 private:
143  friend class SolarisAttachListener;
144
145  // connection to client
146  int _socket;
147
148  // linked list support
149  SolarisAttachOperation* _next;
150
151  SolarisAttachOperation* next()                         { return _next; }
152  void set_next(SolarisAttachOperation* next)            { _next = next; }
153
154 public:
155  void complete(jint res, bufferedStream* st);
156
157  int socket() const                                     { return _socket; }
158  void set_socket(int s)                                 { _socket = s; }
159
160  SolarisAttachOperation(char* name) : AttachOperation(name) {
161    set_socket(-1);
162    set_next(NULL);
163  }
164};
165
166// statics
167char SolarisAttachListener::_door_path[PATH_MAX+1];
168volatile bool SolarisAttachListener::_has_door_path;
169int SolarisAttachListener::_door_descriptor = -1;
170mutex_t SolarisAttachListener::_mutex;
171sema_t SolarisAttachListener::_wakeup;
172SolarisAttachOperation* SolarisAttachListener::_head = NULL;
173SolarisAttachOperation* SolarisAttachListener::_tail = NULL;
174
175// Supporting class to help split a buffer into individual components
176class ArgumentIterator : public StackObj {
177 private:
178  char* _pos;
179  char* _end;
180 public:
181  ArgumentIterator(char* arg_buffer, size_t arg_size) {
182    _pos = arg_buffer;
183    _end = _pos + arg_size - 1;
184  }
185  char* next() {
186    if (*_pos == '\0') {
187      return NULL;
188    }
189    char* res = _pos;
190    char* next_pos = strchr(_pos, '\0');
191    if (next_pos < _end)  {
192      next_pos++;
193    }
194    _pos = next_pos;
195    return res;
196  }
197};
198
199// Calls from the door function to check that the client credentials
200// match this process. Returns 0 if credentials okay, otherwise -1.
201static int check_credentials() {
202  ucred_t *cred_info = NULL;
203  int ret = -1; // deny by default
204
205  // get client credentials
206  if (door_ucred(&cred_info) == -1) {
207    return -1; // unable to get them, deny
208  }
209
210  // get our euid/eguid (probably could cache these)
211  uid_t euid = geteuid();
212  gid_t egid = getegid();
213
214  // get euid/egid from ucred_free
215  uid_t ucred_euid = ucred_geteuid(cred_info);
216  gid_t ucred_egid = ucred_getegid(cred_info);
217
218  // check that the effective uid/gid matches
219  if (ucred_euid == euid && ucred_egid == egid) {
220    ret =  0;  // allow
221  }
222
223  ucred_free(cred_info);
224  return ret;
225}
226
227
228// Parses the argument buffer to create an AttachOperation that we should
229// enqueue to the attach listener.
230// The buffer is expected to be formatted as follows:
231// <ver>0<cmd>0<arg>0<arg>0<arg>0
232// where <ver> is the version number (must be "1"), <cmd> is the command
233// name ("load, "datadump", ...) and <arg> is an argument.
234//
235static SolarisAttachOperation* create_operation(char* argp, size_t arg_size, int* err) {
236  // assume bad request until parsed
237  *err = SolarisAttachListener::ATTACH_ERROR_BADREQUEST;
238
239  if (arg_size < 2 || argp[arg_size-1] != '\0') {
240    return NULL;   // no ver or not null terminated
241  }
242
243  // Use supporting class to iterate over the buffer
244  ArgumentIterator args(argp, arg_size);
245
246  // First check the protocol version
247  char* ver = args.next();
248  if (ver == NULL) {
249    return NULL;
250  }
251  if (atoi(ver) != SolarisAttachListener::ATTACH_PROTOCOL_VER) {
252    *err = SolarisAttachListener::ATTACH_ERROR_BADVERSION;
253    return NULL;
254  }
255
256  // Get command name and create the operation
257  char* name = args.next();
258  if (name == NULL || strlen(name) > AttachOperation::name_length_max) {
259    return NULL;
260  }
261  SolarisAttachOperation* op = new SolarisAttachOperation(name);
262
263  // Iterate over the arguments
264  for (int i=0; i<AttachOperation::arg_count_max; i++) {
265    char* arg = args.next();
266    if (arg == NULL) {
267      op->set_arg(i, NULL);
268    } else {
269      if (strlen(arg) > AttachOperation::arg_length_max) {
270        delete op;
271        return NULL;
272      }
273      op->set_arg(i, arg);
274    }
275  }
276
277  // return operation
278  *err = 0;
279  return op;
280}
281
282// create special operation to indicate all clients have detached
283static SolarisAttachOperation* create_detachall_operation() {
284  return new SolarisAttachOperation(AttachOperation::detachall_operation_name());
285}
286
287// This is door function which the client executes via a door_call.
288extern "C" {
289  static void enqueue_proc(void* cookie, char* argp, size_t arg_size,
290                           door_desc_t* dt, uint_t n_desc)
291  {
292    int return_fd = -1;
293    SolarisAttachOperation* op = NULL;
294
295    // no listener
296    jint res = 0;
297    if (!AttachListener::is_initialized()) {
298      // how did we get here?
299      debug_only(warning("door_call when not enabled"));
300      res = (jint)SolarisAttachListener::ATTACH_ERROR_INTERNAL;
301    }
302
303    // check client credentials
304    if (res == 0) {
305      if (check_credentials() != 0) {
306        res = (jint)SolarisAttachListener::ATTACH_ERROR_DENIED;
307      }
308    }
309
310    // if we are stopped at ShowMessageBoxOnError then maybe we can
311    // load a diagnostic library
312    if (res == 0 && is_error_reported()) {
313      if (ShowMessageBoxOnError) {
314        // TBD - support loading of diagnostic library here
315      }
316
317      // can't enqueue operation after fatal error
318      res = (jint)SolarisAttachListener::ATTACH_ERROR_RESOURCE;
319    }
320
321    // create the operation
322    if (res == 0) {
323      int err;
324      op = create_operation(argp, arg_size, &err);
325      res = (op == NULL) ? (jint)err : 0;
326    }
327
328    // create a pair of connected sockets. Store the file descriptor
329    // for one end in the operation and enqueue the operation. The
330    // file descriptor for the other end wil be returned to the client.
331    if (res == 0) {
332      int s[2];
333      if (socketpair(PF_UNIX, SOCK_STREAM, 0, s) < 0) {
334        delete op;
335        res = (jint)SolarisAttachListener::ATTACH_ERROR_RESOURCE;
336      } else {
337        op->set_socket(s[0]);
338        return_fd = s[1];
339        SolarisAttachListener::enqueue(op);
340      }
341    }
342
343    // Return 0 (success) + file descriptor, or non-0 (error)
344    if (res == 0) {
345      door_desc_t desc;
346      // DOOR_RELEASE flag makes sure fd is closed after passing it to
347      // the client.  See door_return(3DOOR) man page.
348      desc.d_attributes = DOOR_DESCRIPTOR | DOOR_RELEASE;
349      desc.d_data.d_desc.d_descriptor = return_fd;
350      door_return((char*)&res, sizeof(res), &desc, 1);
351    } else {
352      door_return((char*)&res, sizeof(res), NULL, 0);
353    }
354  }
355}
356
357// atexit hook to detach the door and remove the file
358extern "C" {
359  static void listener_cleanup() {
360    static int cleanup_done;
361    if (!cleanup_done) {
362      cleanup_done = 1;
363      int dd = SolarisAttachListener::door_descriptor();
364      if (dd >= 0) {
365        ::close(dd);
366      }
367      if (SolarisAttachListener::has_door_path()) {
368        char* path = SolarisAttachListener::door_path();
369        ::fdetach(path);
370        ::unlink(path);
371      }
372    }
373  }
374}
375
376// Create the door
377int SolarisAttachListener::create_door() {
378  char door_path[PATH_MAX+1];
379  char initial_path[PATH_MAX+1];
380  int fd, res;
381
382  // register exit function
383  ::atexit(listener_cleanup);
384
385  // create the door descriptor
386  int dd = ::door_create(enqueue_proc, NULL, 0);
387  if (dd < 0) {
388    return -1;
389  }
390
391  // create initial file to attach door descriptor
392  snprintf(door_path, sizeof(door_path), "%s/.java_pid%d",
393           os::get_temp_directory(), os::current_process_id());
394  snprintf(initial_path, sizeof(initial_path), "%s.tmp", door_path);
395  RESTARTABLE(::creat(initial_path, S_IRUSR | S_IWUSR), fd);
396  if (fd == -1) {
397    debug_only(warning("attempt to create %s failed", initial_path));
398    ::door_revoke(dd);
399    return -1;
400  }
401  assert(fd >= 0, "bad file descriptor");
402  ::close(fd);
403
404  // attach the door descriptor to the file
405  if ((res = ::fattach(dd, initial_path)) == -1) {
406    // if busy then detach and try again
407    if (errno == EBUSY) {
408      ::fdetach(initial_path);
409      res = ::fattach(dd, initial_path);
410    }
411    if (res == -1) {
412      ::door_revoke(dd);
413      dd = -1;
414    }
415  }
416
417  // rename file so that clients can attach
418  if (dd >= 0) {
419    if (::rename(initial_path, door_path) == -1) {
420        ::close(dd);
421        ::fdetach(initial_path);
422        dd = -1;
423    }
424  }
425  if (dd >= 0) {
426    set_door_descriptor(dd);
427    set_door_path(door_path);
428  } else {
429    // unable to create door, attach it to file, or rename file into place
430    ::unlink(initial_path);
431    return -1;
432  }
433
434  return 0;
435}
436
437// Initialization - create the door, locks, and other initialization
438int SolarisAttachListener::init() {
439  if (create_door()) {
440    return -1;
441  }
442
443  int status = os::Solaris::mutex_init(&_mutex);
444  assert_status(status==0, status, "mutex_init");
445
446  status = ::sema_init(&_wakeup, 0, NULL, NULL);
447  assert_status(status==0, status, "sema_init");
448
449  set_head(NULL);
450  set_tail(NULL);
451
452  return 0;
453}
454
455// Dequeue an operation
456SolarisAttachOperation* SolarisAttachListener::dequeue() {
457  for (;;) {
458    int res;
459
460    // wait for somebody to enqueue something
461    while ((res = ::sema_wait(wakeup())) == EINTR)
462      ;
463    if (res) {
464      warning("sema_wait failed: %s", os::strerror(res));
465      return NULL;
466    }
467
468    // lock the list
469    res = os::Solaris::mutex_lock(mutex());
470    assert(res == 0, "mutex_lock failed");
471
472    // remove the head of the list
473    SolarisAttachOperation* op = head();
474    if (op != NULL) {
475      set_head(op->next());
476      if (head() == NULL) {
477        set_tail(NULL);
478      }
479    }
480
481    // unlock
482    os::Solaris::mutex_unlock(mutex());
483
484    // if we got an operation when return it.
485    if (op != NULL) {
486      return op;
487    }
488  }
489}
490
491// Enqueue an operation
492void SolarisAttachListener::enqueue(SolarisAttachOperation* op) {
493  // lock list
494  int res = os::Solaris::mutex_lock(mutex());
495  assert(res == 0, "mutex_lock failed");
496
497  // enqueue at tail
498  op->set_next(NULL);
499  if (head() == NULL) {
500    set_head(op);
501  } else {
502    tail()->set_next(op);
503  }
504  set_tail(op);
505
506  // wakeup the attach listener
507  RESTARTABLE(::sema_post(wakeup()), res);
508  assert(res == 0, "sema_post failed");
509
510  // unlock
511  os::Solaris::mutex_unlock(mutex());
512}
513
514
515// support function - writes the (entire) buffer to a socket
516static int write_fully(int s, char* buf, int len) {
517  do {
518    int n = ::write(s, buf, len);
519    if (n == -1) {
520      if (errno != EINTR) return -1;
521    } else {
522      buf += n;
523      len -= n;
524    }
525  }
526  while (len > 0);
527  return 0;
528}
529
530// Complete an operation by sending the operation result and any result
531// output to the client. At this time the socket is in blocking mode so
532// potentially we can block if there is a lot of data and the client is
533// non-responsive. For most operations this is a non-issue because the
534// default send buffer is sufficient to buffer everything. In the future
535// if there are operations that involves a very big reply then it the
536// socket could be made non-blocking and a timeout could be used.
537
538void SolarisAttachOperation::complete(jint res, bufferedStream* st) {
539  if (this->socket() >= 0) {
540    JavaThread* thread = JavaThread::current();
541    ThreadBlockInVM tbivm(thread);
542
543    thread->set_suspend_equivalent();
544    // cleared by handle_special_suspend_equivalent_condition() or
545    // java_suspend_self() via check_and_wait_while_suspended()
546
547    // write operation result
548    char msg[32];
549    sprintf(msg, "%d\n", res);
550    int rc = write_fully(this->socket(), msg, strlen(msg));
551
552    // write any result data
553    if (rc == 0) {
554      write_fully(this->socket(), (char*) st->base(), st->size());
555      ::shutdown(this->socket(), 2);
556    }
557
558    // close socket and we're done
559    ::close(this->socket());
560
561    // were we externally suspended while we were waiting?
562    thread->check_and_wait_while_suspended();
563  }
564  delete this;
565}
566
567
568// AttachListener functions
569
570AttachOperation* AttachListener::dequeue() {
571  JavaThread* thread = JavaThread::current();
572  ThreadBlockInVM tbivm(thread);
573
574  thread->set_suspend_equivalent();
575  // cleared by handle_special_suspend_equivalent_condition() or
576  // java_suspend_self() via check_and_wait_while_suspended()
577
578  AttachOperation* op = SolarisAttachListener::dequeue();
579
580  // were we externally suspended while we were waiting?
581  thread->check_and_wait_while_suspended();
582
583  return op;
584}
585
586
587// Performs initialization at vm startup
588// For Solaris we remove any stale .java_pid file which could cause
589// an attaching process to think we are ready to receive a door_call
590// before we are properly initialized
591
592void AttachListener::vm_start() {
593  char fn[PATH_MAX+1];
594  struct stat64 st;
595  int ret;
596
597  int n = snprintf(fn, sizeof(fn), "%s/.java_pid%d",
598           os::get_temp_directory(), os::current_process_id());
599  assert(n < sizeof(fn), "java_pid file name buffer overflow");
600
601  RESTARTABLE(::stat64(fn, &st), ret);
602  if (ret == 0) {
603    ret = ::unlink(fn);
604    if (ret == -1) {
605      debug_only(warning("failed to remove stale attach pid file at %s", fn));
606    }
607  }
608}
609
610int AttachListener::pd_init() {
611  JavaThread* thread = JavaThread::current();
612  ThreadBlockInVM tbivm(thread);
613
614  thread->set_suspend_equivalent();
615  // cleared by handle_special_suspend_equivalent_condition() or
616  // java_suspend_self()
617
618  int ret_code = SolarisAttachListener::init();
619
620  // were we externally suspended while we were waiting?
621  thread->check_and_wait_while_suspended();
622
623  return ret_code;
624}
625
626// Attach Listener is started lazily except in the case when
627// +ReduseSignalUsage is used
628bool AttachListener::init_at_startup() {
629  if (ReduceSignalUsage) {
630    return true;
631  } else {
632    return false;
633  }
634}
635
636// If the file .attach_pid<pid> exists in the working directory
637// or /tmp then this is the trigger to start the attach mechanism
638bool AttachListener::is_init_trigger() {
639  if (init_at_startup() || is_initialized()) {
640    return false;               // initialized at startup or already initialized
641  }
642  char fn[PATH_MAX+1];
643  sprintf(fn, ".attach_pid%d", os::current_process_id());
644  int ret;
645  struct stat64 st;
646  RESTARTABLE(::stat64(fn, &st), ret);
647  if (ret == -1) {
648    snprintf(fn, sizeof(fn), "%s/.attach_pid%d",
649             os::get_temp_directory(), os::current_process_id());
650    RESTARTABLE(::stat64(fn, &st), ret);
651  }
652  if (ret == 0) {
653    // simple check to avoid starting the attach mechanism when
654    // a bogus user creates the file
655    if (st.st_uid == geteuid()) {
656      init();
657      return true;
658    }
659  }
660  return false;
661}
662
663// if VM aborts then detach/cleanup
664void AttachListener::abort() {
665  listener_cleanup();
666}
667
668void AttachListener::pd_data_dump() {
669  os::signal_notify(SIGQUIT);
670}
671
672static jint enable_dprobes(AttachOperation* op, outputStream* out) {
673  const char* probe = op->arg(0);
674  if (probe == NULL || probe[0] == '\0') {
675    out->print_cr("No probe specified");
676    return JNI_ERR;
677  } else {
678    char *end;
679    long val = strtol(probe, &end, 10);
680    if (end == probe || val < 0 || val > INT_MAX) {
681      out->print_cr("invalid probe type");
682      return JNI_ERR;
683    } else {
684      int probe_typess = (int) val;
685      DTrace::enable_dprobes(probe_typess);
686      return JNI_OK;
687    }
688  }
689}
690
691// platform specific operations table
692static AttachOperationFunctionInfo funcs[] = {
693  { "enabledprobes", enable_dprobes },
694  { NULL, NULL }
695};
696
697AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* name) {
698  int i;
699  for (i = 0; funcs[i].name != NULL; i++) {
700    if (strcmp(funcs[i].name, name) == 0) {
701      return &funcs[i];
702    }
703  }
704  return NULL;
705}
706
707// Solaris specific global flag set. Currently, we support only
708// changing ExtendedDTraceProbes flag.
709jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
710  const char* name = op->arg(0);
711  assert(name != NULL, "flag name should not be null");
712  bool flag = true;
713  const char* arg1;
714  if ((arg1 = op->arg(1)) != NULL) {
715    char *end;
716    flag = (strtol(arg1, &end, 10) != 0);
717    if (arg1 == end) {
718      out->print_cr("flag value has to be an integer");
719      return JNI_ERR;
720    }
721  }
722
723  if (strcmp(name, "ExtendedDTraceProbes") == 0) {
724    DTrace::set_extended_dprobes(flag);
725    return JNI_OK;
726  }
727
728  if (strcmp(name, "DTraceMonitorProbes") == 0) {
729    DTrace::set_monitor_dprobes(flag);
730    return JNI_OK;
731  }
732
733  out->print_cr("flag '%s' cannot be changed", name);
734  return JNI_ERR;
735}
736
737void AttachListener::pd_detachall() {
738  DTrace::detach_all_clients();
739}
740