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    log_debug(attach)("attempt to create door file %s failed (%d)", initial_path, errno);
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      log_debug(attach)("unable to create door - fattach failed (%d)", errno);
413      ::door_revoke(dd);
414      dd = -1;
415    }
416  }
417
418  // rename file so that clients can attach
419  if (dd >= 0) {
420    if (::rename(initial_path, door_path) == -1) {
421        ::close(dd);
422        ::fdetach(initial_path);
423        log_debug(attach)("unable to create door - rename %s to %s failed (%d)", errno);
424        dd = -1;
425    }
426  }
427  if (dd >= 0) {
428    set_door_descriptor(dd);
429    set_door_path(door_path);
430    log_trace(attach)("door file %s created succesfully", door_path);
431  } else {
432    // unable to create door, attach it to file, or rename file into place
433    ::unlink(initial_path);
434    return -1;
435  }
436
437  return 0;
438}
439
440// Initialization - create the door, locks, and other initialization
441int SolarisAttachListener::init() {
442  if (create_door()) {
443    return -1;
444  }
445
446  int status = os::Solaris::mutex_init(&_mutex);
447  assert_status(status==0, status, "mutex_init");
448
449  status = ::sema_init(&_wakeup, 0, NULL, NULL);
450  assert_status(status==0, status, "sema_init");
451
452  set_head(NULL);
453  set_tail(NULL);
454
455  return 0;
456}
457
458// Dequeue an operation
459SolarisAttachOperation* SolarisAttachListener::dequeue() {
460  for (;;) {
461    int res;
462
463    // wait for somebody to enqueue something
464    while ((res = ::sema_wait(wakeup())) == EINTR)
465      ;
466    if (res) {
467      warning("sema_wait failed: %s", os::strerror(res));
468      return NULL;
469    }
470
471    // lock the list
472    res = os::Solaris::mutex_lock(mutex());
473    assert(res == 0, "mutex_lock failed");
474
475    // remove the head of the list
476    SolarisAttachOperation* op = head();
477    if (op != NULL) {
478      set_head(op->next());
479      if (head() == NULL) {
480        set_tail(NULL);
481      }
482    }
483
484    // unlock
485    os::Solaris::mutex_unlock(mutex());
486
487    // if we got an operation when return it.
488    if (op != NULL) {
489      return op;
490    }
491  }
492}
493
494// Enqueue an operation
495void SolarisAttachListener::enqueue(SolarisAttachOperation* op) {
496  // lock list
497  int res = os::Solaris::mutex_lock(mutex());
498  assert(res == 0, "mutex_lock failed");
499
500  // enqueue at tail
501  op->set_next(NULL);
502  if (head() == NULL) {
503    set_head(op);
504  } else {
505    tail()->set_next(op);
506  }
507  set_tail(op);
508
509  // wakeup the attach listener
510  RESTARTABLE(::sema_post(wakeup()), res);
511  assert(res == 0, "sema_post failed");
512
513  // unlock
514  os::Solaris::mutex_unlock(mutex());
515}
516
517
518// support function - writes the (entire) buffer to a socket
519static int write_fully(int s, char* buf, int len) {
520  do {
521    int n = ::write(s, buf, len);
522    if (n == -1) {
523      if (errno != EINTR) return -1;
524    } else {
525      buf += n;
526      len -= n;
527    }
528  }
529  while (len > 0);
530  return 0;
531}
532
533// Complete an operation by sending the operation result and any result
534// output to the client. At this time the socket is in blocking mode so
535// potentially we can block if there is a lot of data and the client is
536// non-responsive. For most operations this is a non-issue because the
537// default send buffer is sufficient to buffer everything. In the future
538// if there are operations that involves a very big reply then it the
539// socket could be made non-blocking and a timeout could be used.
540
541void SolarisAttachOperation::complete(jint res, bufferedStream* st) {
542  if (this->socket() >= 0) {
543    JavaThread* thread = JavaThread::current();
544    ThreadBlockInVM tbivm(thread);
545
546    thread->set_suspend_equivalent();
547    // cleared by handle_special_suspend_equivalent_condition() or
548    // java_suspend_self() via check_and_wait_while_suspended()
549
550    // write operation result
551    char msg[32];
552    sprintf(msg, "%d\n", res);
553    int rc = write_fully(this->socket(), msg, strlen(msg));
554
555    // write any result data
556    if (rc == 0) {
557      write_fully(this->socket(), (char*) st->base(), st->size());
558      ::shutdown(this->socket(), 2);
559    }
560
561    // close socket and we're done
562    ::close(this->socket());
563
564    // were we externally suspended while we were waiting?
565    thread->check_and_wait_while_suspended();
566  }
567  delete this;
568}
569
570
571// AttachListener functions
572
573AttachOperation* AttachListener::dequeue() {
574  JavaThread* thread = JavaThread::current();
575  ThreadBlockInVM tbivm(thread);
576
577  thread->set_suspend_equivalent();
578  // cleared by handle_special_suspend_equivalent_condition() or
579  // java_suspend_self() via check_and_wait_while_suspended()
580
581  AttachOperation* op = SolarisAttachListener::dequeue();
582
583  // were we externally suspended while we were waiting?
584  thread->check_and_wait_while_suspended();
585
586  return op;
587}
588
589
590// Performs initialization at vm startup
591// For Solaris we remove any stale .java_pid file which could cause
592// an attaching process to think we are ready to receive a door_call
593// before we are properly initialized
594
595void AttachListener::vm_start() {
596  char fn[PATH_MAX+1];
597  struct stat64 st;
598  int ret;
599
600  int n = snprintf(fn, sizeof(fn), "%s/.java_pid%d",
601           os::get_temp_directory(), os::current_process_id());
602  assert(n < sizeof(fn), "java_pid file name buffer overflow");
603
604  RESTARTABLE(::stat64(fn, &st), ret);
605  if (ret == 0) {
606    ret = ::unlink(fn);
607    if (ret == -1) {
608      log_debug(attach)("Failed to remove stale attach pid file at %s", fn);
609    }
610  }
611}
612
613int AttachListener::pd_init() {
614  JavaThread* thread = JavaThread::current();
615  ThreadBlockInVM tbivm(thread);
616
617  thread->set_suspend_equivalent();
618  // cleared by handle_special_suspend_equivalent_condition() or
619  // java_suspend_self()
620
621  int ret_code = SolarisAttachListener::init();
622
623  // were we externally suspended while we were waiting?
624  thread->check_and_wait_while_suspended();
625
626  return ret_code;
627}
628
629// Attach Listener is started lazily except in the case when
630// +ReduseSignalUsage is used
631bool AttachListener::init_at_startup() {
632  if (ReduceSignalUsage) {
633    return true;
634  } else {
635    return false;
636  }
637}
638
639// If the file .attach_pid<pid> exists in the working directory
640// or /tmp then this is the trigger to start the attach mechanism
641bool AttachListener::is_init_trigger() {
642  if (init_at_startup() || is_initialized()) {
643    return false;               // initialized at startup or already initialized
644  }
645  char fn[PATH_MAX+1];
646  sprintf(fn, ".attach_pid%d", os::current_process_id());
647  int ret;
648  struct stat64 st;
649  RESTARTABLE(::stat64(fn, &st), ret);
650  if (ret == -1) {
651    log_trace(attach)("Failed to find attach file: %s, trying alternate", fn);
652    snprintf(fn, sizeof(fn), "%s/.attach_pid%d",
653             os::get_temp_directory(), os::current_process_id());
654    RESTARTABLE(::stat64(fn, &st), ret);
655    if (ret == -1) {
656      log_debug(attach)("Failed to find attach file: %s", fn);
657    }
658  }
659  if (ret == 0) {
660    // simple check to avoid starting the attach mechanism when
661    // a bogus user creates the file
662    if (st.st_uid == geteuid()) {
663      init();
664      return true;
665    }
666  }
667  return false;
668}
669
670// if VM aborts then detach/cleanup
671void AttachListener::abort() {
672  listener_cleanup();
673}
674
675void AttachListener::pd_data_dump() {
676  os::signal_notify(SIGQUIT);
677}
678
679static jint enable_dprobes(AttachOperation* op, outputStream* out) {
680  const char* probe = op->arg(0);
681  if (probe == NULL || probe[0] == '\0') {
682    out->print_cr("No probe specified");
683    return JNI_ERR;
684  } else {
685    char *end;
686    long val = strtol(probe, &end, 10);
687    if (end == probe || val < 0 || val > INT_MAX) {
688      out->print_cr("invalid probe type");
689      return JNI_ERR;
690    } else {
691      int probe_typess = (int) val;
692      DTrace::enable_dprobes(probe_typess);
693      return JNI_OK;
694    }
695  }
696}
697
698// platform specific operations table
699static AttachOperationFunctionInfo funcs[] = {
700  { "enabledprobes", enable_dprobes },
701  { NULL, NULL }
702};
703
704AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* name) {
705  int i;
706  for (i = 0; funcs[i].name != NULL; i++) {
707    if (strcmp(funcs[i].name, name) == 0) {
708      return &funcs[i];
709    }
710  }
711  return NULL;
712}
713
714// Solaris specific global flag set. Currently, we support only
715// changing ExtendedDTraceProbes flag.
716jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
717  const char* name = op->arg(0);
718  assert(name != NULL, "flag name should not be null");
719  bool flag = true;
720  const char* arg1;
721  if ((arg1 = op->arg(1)) != NULL) {
722    char *end;
723    flag = (strtol(arg1, &end, 10) != 0);
724    if (arg1 == end) {
725      out->print_cr("flag value has to be an integer");
726      return JNI_ERR;
727    }
728  }
729
730  if (strcmp(name, "ExtendedDTraceProbes") == 0) {
731    DTrace::set_extended_dprobes(flag);
732    return JNI_OK;
733  }
734
735  if (strcmp(name, "DTraceMonitorProbes") == 0) {
736    DTrace::set_monitor_dprobes(flag);
737    return JNI_OK;
738  }
739
740  out->print_cr("flag '%s' cannot be changed", name);
741  return JNI_ERR;
742}
743
744void AttachListener::pd_detachall() {
745  DTrace::detach_all_clients();
746}
747