1 /* 2 * Copyright (c) 2005, 2013, 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.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 64 class SolarisAttachOperation; 65 66 class 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 141 class 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 167 char SolarisAttachListener::_door_path[PATH_MAX+1]; 168 volatile bool SolarisAttachListener::_has_door_path; 169 int SolarisAttachListener::_door_descriptor = -1; 170 mutex_t SolarisAttachListener::_mutex; 171 sema_t SolarisAttachListener::_wakeup; 172 SolarisAttachOperation* SolarisAttachListener::_head = NULL; 173 SolarisAttachOperation* SolarisAttachListener::_tail = NULL; 174 175 // Supporting class to help split a buffer into individual components 176 class 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. 201 static int check_credentials() { 202 door_cred_t cred_info; 203 204 // get client credentials 205 if (door_cred(&cred_info) == -1) { 206 return -1; // unable to get them 207 } 208 209 // get our euid/eguid (probably could cache these) 210 uid_t euid = geteuid(); 211 gid_t egid = getegid(); 212 213 // check that the effective uid/gid matches - discuss this with Jeff. 214 if (cred_info.dc_euid == euid && cred_info.dc_egid == egid) { 215 return 0; // okay 216 } else { 217 return -1; // denied 218 } 219 } 220 221 222 // Parses the argument buffer to create an AttachOperation that we should 223 // enqueue to the attach listener. 224 // The buffer is expected to be formatted as follows: 225 // <ver>0<cmd>0<arg>0<arg>0<arg>0 226 // where <ver> is the version number (must be "1"), <cmd> is the command 227 // name ("load, "datadump", ...) and <arg> is an argument. 228 // 229 static SolarisAttachOperation* create_operation(char* argp, size_t arg_size, int* err) { 230 // assume bad request until parsed 231 *err = SolarisAttachListener::ATTACH_ERROR_BADREQUEST; 232 233 if (arg_size < 2 || argp[arg_size-1] != '\0') { 234 return NULL; // no ver or not null terminated 235 } 236 237 // Use supporting class to iterate over the buffer 238 ArgumentIterator args(argp, arg_size); 239 240 // First check the protocol version 241 char* ver = args.next(); 242 if (ver == NULL) { 243 return NULL; 244 } 245 if (atoi(ver) != SolarisAttachListener::ATTACH_PROTOCOL_VER) { 246 *err = SolarisAttachListener::ATTACH_ERROR_BADVERSION; 247 return NULL; 248 } 249 250 // Get command name and create the operation 251 char* name = args.next(); 252 if (name == NULL || strlen(name) > AttachOperation::name_length_max) { 253 return NULL; 254 } 255 SolarisAttachOperation* op = new SolarisAttachOperation(name); 256 257 // Iterate over the arguments 258 for (int i=0; i<AttachOperation::arg_count_max; i++) { 259 char* arg = args.next(); 260 if (arg == NULL) { 261 op->set_arg(i, NULL); 262 } else { 263 if (strlen(arg) > AttachOperation::arg_length_max) { 264 delete op; 265 return NULL; 266 } 267 op->set_arg(i, arg); 268 } 269 } 270 271 // return operation 272 *err = 0; 273 return op; 274 } 275 276 // create special operation to indicate all clients have detached 277 static SolarisAttachOperation* create_detachall_operation() { 278 return new SolarisAttachOperation(AttachOperation::detachall_operation_name()); 279 } 280 281 // This is door function which the client executes via a door_call. 282 extern "C" { 283 static void enqueue_proc(void* cookie, char* argp, size_t arg_size, 284 door_desc_t* dt, uint_t n_desc) 285 { 286 int return_fd = -1; 287 SolarisAttachOperation* op = NULL; 288 289 // no listener 290 jint res = 0; 291 if (!AttachListener::is_initialized()) { 292 // how did we get here? 293 debug_only(warning("door_call when not enabled")); 294 res = (jint)SolarisAttachListener::ATTACH_ERROR_INTERNAL; 295 } 296 297 // check client credentials 298 if (res == 0) { 299 if (check_credentials() != 0) { 300 res = (jint)SolarisAttachListener::ATTACH_ERROR_DENIED; 301 } 302 } 303 304 // if we are stopped at ShowMessageBoxOnError then maybe we can 305 // load a diagnostic library 306 if (res == 0 && is_error_reported()) { 307 if (ShowMessageBoxOnError) { 308 // TBD - support loading of diagnostic library here 309 } 310 311 // can't enqueue operation after fatal error 312 res = (jint)SolarisAttachListener::ATTACH_ERROR_RESOURCE; 313 } 314 315 // create the operation 316 if (res == 0) { 317 int err; 318 op = create_operation(argp, arg_size, &err); 319 res = (op == NULL) ? (jint)err : 0; 320 } 321 322 // create a pair of connected sockets. Store the file descriptor 323 // for one end in the operation and enqueue the operation. The 324 // file descriptor for the other end wil be returned to the client. 325 if (res == 0) { 326 int s[2]; 327 if (socketpair(PF_UNIX, SOCK_STREAM, 0, s) < 0) { 328 delete op; 329 res = (jint)SolarisAttachListener::ATTACH_ERROR_RESOURCE; 330 } else { 331 op->set_socket(s[0]); 332 return_fd = s[1]; 333 SolarisAttachListener::enqueue(op); 334 } 335 } 336 337 // Return 0 (success) + file descriptor, or non-0 (error) 338 if (res == 0) { 339 door_desc_t desc; 340 // DOOR_RELEASE flag makes sure fd is closed after passing it to 341 // the client. See door_return(3DOOR) man page. 342 desc.d_attributes = DOOR_DESCRIPTOR | DOOR_RELEASE; 343 desc.d_data.d_desc.d_descriptor = return_fd; 344 door_return((char*)&res, sizeof(res), &desc, 1); 345 } else { 346 door_return((char*)&res, sizeof(res), NULL, 0); 347 } 348 } 349 } 350 351 // atexit hook to detach the door and remove the file 352 extern "C" { 353 static void listener_cleanup() { 354 static int cleanup_done; 355 if (!cleanup_done) { 356 cleanup_done = 1; 357 int dd = SolarisAttachListener::door_descriptor(); 358 if (dd >= 0) { 359 ::close(dd); 360 } 361 if (SolarisAttachListener::has_door_path()) { 362 char* path = SolarisAttachListener::door_path(); 363 ::fdetach(path); 364 ::unlink(path); 365 } 366 } 367 } 368 } 369 370 // Create the door 371 int SolarisAttachListener::create_door() { 372 char door_path[PATH_MAX+1]; 373 char initial_path[PATH_MAX+1]; 374 int fd, res; 375 376 // register exit function 377 ::atexit(listener_cleanup); 378 379 // create the door descriptor 380 int dd = ::door_create(enqueue_proc, NULL, 0); 381 if (dd < 0) { 382 return -1; 383 } 384 385 // create initial file to attach door descriptor 386 snprintf(door_path, sizeof(door_path), "%s/.java_pid%d", 387 os::get_temp_directory(), os::current_process_id()); 388 snprintf(initial_path, sizeof(initial_path), "%s.tmp", door_path); 389 RESTARTABLE(::creat(initial_path, S_IRUSR | S_IWUSR), fd); 390 if (fd == -1) { 391 debug_only(warning("attempt to create %s failed", initial_path)); 392 ::door_revoke(dd); 393 return -1; 394 } 395 assert(fd >= 0, "bad file descriptor"); 396 ::close(fd); 397 398 // attach the door descriptor to the file 399 if ((res = ::fattach(dd, initial_path)) == -1) { 400 // if busy then detach and try again 401 if (errno == EBUSY) { 402 ::fdetach(initial_path); 403 res = ::fattach(dd, initial_path); 404 } 405 if (res == -1) { 406 ::door_revoke(dd); 407 dd = -1; 408 } 409 } 410 411 // rename file so that clients can attach 412 if (dd >= 0) { 413 if (::rename(initial_path, door_path) == -1) { 414 ::close(dd); 415 ::fdetach(initial_path); 416 dd = -1; 417 } 418 } 419 if (dd >= 0) { 420 set_door_descriptor(dd); 421 set_door_path(door_path); 422 } else { 423 // unable to create door, attach it to file, or rename file into place 424 ::unlink(initial_path); 425 return -1; 426 } 427 428 return 0; 429 } 430 431 // Initialization - create the door, locks, and other initialization 432 int SolarisAttachListener::init() { 433 if (create_door()) { 434 return -1; 435 } 436 437 int status = os::Solaris::mutex_init(&_mutex); 438 assert_status(status==0, status, "mutex_init"); 439 440 status = ::sema_init(&_wakeup, 0, NULL, NULL); 441 assert_status(status==0, status, "sema_init"); 442 443 set_head(NULL); 444 set_tail(NULL); 445 446 return 0; 447 } 448 449 // Dequeue an operation 450 SolarisAttachOperation* SolarisAttachListener::dequeue() { 451 for (;;) { 452 int res; 453 454 // wait for somebody to enqueue something 455 while ((res = ::sema_wait(wakeup())) == EINTR) 456 ; 457 if (res) { 458 warning("sema_wait failed: %s", strerror(res)); 459 return NULL; 460 } 461 462 // lock the list 463 res = os::Solaris::mutex_lock(mutex()); 464 assert(res == 0, "mutex_lock failed"); 465 466 // remove the head of the list 467 SolarisAttachOperation* op = head(); 468 if (op != NULL) { 469 set_head(op->next()); 470 if (head() == NULL) { 471 set_tail(NULL); 472 } 473 } 474 475 // unlock 476 os::Solaris::mutex_unlock(mutex()); 477 478 // if we got an operation when return it. 479 if (op != NULL) { 480 return op; 481 } 482 } 483 } 484 485 // Enqueue an operation 486 void SolarisAttachListener::enqueue(SolarisAttachOperation* op) { 487 // lock list 488 int res = os::Solaris::mutex_lock(mutex()); 489 assert(res == 0, "mutex_lock failed"); 490 491 // enqueue at tail 492 op->set_next(NULL); 493 if (head() == NULL) { 494 set_head(op); 495 } else { 496 tail()->set_next(op); 497 } 498 set_tail(op); 499 500 // wakeup the attach listener 501 RESTARTABLE(::sema_post(wakeup()), res); 502 assert(res == 0, "sema_post failed"); 503 504 // unlock 505 os::Solaris::mutex_unlock(mutex()); 506 } 507 508 509 // support function - writes the (entire) buffer to a socket 510 static int write_fully(int s, char* buf, int len) { 511 do { 512 int n = ::write(s, buf, len); 513 if (n == -1) { 514 if (errno != EINTR) return -1; 515 } else { 516 buf += n; 517 len -= n; 518 } 519 } 520 while (len > 0); 521 return 0; 522 } 523 524 // Complete an operation by sending the operation result and any result 525 // output to the client. At this time the socket is in blocking mode so 526 // potentially we can block if there is a lot of data and the client is 527 // non-responsive. For most operations this is a non-issue because the 528 // default send buffer is sufficient to buffer everything. In the future 529 // if there are operations that involves a very big reply then it the 530 // socket could be made non-blocking and a timeout could be used. 531 532 void SolarisAttachOperation::complete(jint res, bufferedStream* st) { 533 if (this->socket() >= 0) { 534 JavaThread* thread = JavaThread::current(); 535 ThreadBlockInVM tbivm(thread); 536 537 thread->set_suspend_equivalent(); 538 // cleared by handle_special_suspend_equivalent_condition() or 539 // java_suspend_self() via check_and_wait_while_suspended() 540 541 // write operation result 542 char msg[32]; 543 sprintf(msg, "%d\n", res); 544 int rc = write_fully(this->socket(), msg, strlen(msg)); 545 546 // write any result data 547 if (rc == 0) { 548 write_fully(this->socket(), (char*) st->base(), st->size()); 549 ::shutdown(this->socket(), 2); 550 } 551 552 // close socket and we're done 553 ::close(this->socket()); 554 555 // were we externally suspended while we were waiting? 556 thread->check_and_wait_while_suspended(); 557 } 558 delete this; 559 } 560 561 562 // AttachListener functions 563 564 AttachOperation* AttachListener::dequeue() { 565 JavaThread* thread = JavaThread::current(); 566 ThreadBlockInVM tbivm(thread); 567 568 thread->set_suspend_equivalent(); 569 // cleared by handle_special_suspend_equivalent_condition() or 570 // java_suspend_self() via check_and_wait_while_suspended() 571 572 AttachOperation* op = SolarisAttachListener::dequeue(); 573 574 // were we externally suspended while we were waiting? 575 thread->check_and_wait_while_suspended(); 576 577 return op; 578 } 579 580 581 // Performs initialization at vm startup 582 // For Solaris we remove any stale .java_pid file which could cause 583 // an attaching process to think we are ready to receive a door_call 584 // before we are properly initialized 585 586 void AttachListener::vm_start() { 587 char fn[PATH_MAX+1]; 588 struct stat64 st; 589 int ret; 590 591 int n = snprintf(fn, sizeof(fn), "%s/.java_pid%d", 592 os::get_temp_directory(), os::current_process_id()); 593 assert(n < sizeof(fn), "java_pid file name buffer overflow"); 594 595 RESTARTABLE(::stat64(fn, &st), ret); 596 if (ret == 0) { 597 ret = ::unlink(fn); 598 if (ret == -1) { 599 debug_only(warning("failed to remove stale attach pid file at %s", fn)); 600 } 601 } 602 } 603 604 int AttachListener::pd_init() { 605 JavaThread* thread = JavaThread::current(); 606 ThreadBlockInVM tbivm(thread); 607 608 thread->set_suspend_equivalent(); 609 // cleared by handle_special_suspend_equivalent_condition() or 610 // java_suspend_self() 611 612 int ret_code = SolarisAttachListener::init(); 613 614 // were we externally suspended while we were waiting? 615 thread->check_and_wait_while_suspended(); 616 617 return ret_code; 618 } 619 620 // Attach Listener is started lazily except in the case when 621 // +ReduseSignalUsage is used 622 bool AttachListener::init_at_startup() { 623 if (ReduceSignalUsage) { 624 return true; 625 } else { 626 return false; 627 } 628 } 629 630 // If the file .attach_pid<pid> exists in the working directory 631 // or /tmp then this is the trigger to start the attach mechanism 632 bool AttachListener::is_init_trigger() { 633 if (init_at_startup() || is_initialized()) { 634 return false; // initialized at startup or already initialized 635 } 636 char fn[PATH_MAX+1]; 637 sprintf(fn, ".attach_pid%d", os::current_process_id()); 638 int ret; 639 struct stat64 st; 640 RESTARTABLE(::stat64(fn, &st), ret); 641 if (ret == -1) { 642 snprintf(fn, sizeof(fn), "%s/.attach_pid%d", 643 os::get_temp_directory(), os::current_process_id()); 644 RESTARTABLE(::stat64(fn, &st), ret); 645 } 646 if (ret == 0) { 647 // simple check to avoid starting the attach mechanism when 648 // a bogus user creates the file 649 if (st.st_uid == geteuid()) { 650 init(); 651 return true; 652 } 653 } 654 return false; 655 } 656 657 // if VM aborts then detach/cleanup 658 void AttachListener::abort() { 659 listener_cleanup(); 660 } 661 662 void AttachListener::pd_data_dump() { 663 os::signal_notify(SIGQUIT); 664 } 665 666 static jint enable_dprobes(AttachOperation* op, outputStream* out) { 667 const char* probe = op->arg(0); 668 if (probe == NULL || probe[0] == '\0') { 669 out->print_cr("No probe specified"); 670 return JNI_ERR; 671 } else { 672 char *end; 673 long val = strtol(probe, &end, 10); 674 if (end == probe || val < 0 || val > INT_MAX) { 675 out->print_cr("invalid probe type"); 676 return JNI_ERR; 677 } else { 678 int probe_typess = (int) val; 679 DTrace::enable_dprobes(probe_typess); 680 return JNI_OK; 681 } 682 } 683 } 684 685 // platform specific operations table 686 static AttachOperationFunctionInfo funcs[] = { 687 { "enabledprobes", enable_dprobes }, 688 { NULL, NULL } 689 }; 690 691 AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* name) { 692 int i; 693 for (i = 0; funcs[i].name != NULL; i++) { 694 if (strcmp(funcs[i].name, name) == 0) { 695 return &funcs[i]; 696 } 697 } 698 return NULL; 699 } 700 701 // Solaris specific global flag set. Currently, we support only 702 // changing ExtendedDTraceProbes flag. 703 jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) { 704 const char* name = op->arg(0); 705 assert(name != NULL, "flag name should not be null"); 706 bool flag = true; 707 const char* arg1; 708 if ((arg1 = op->arg(1)) != NULL) { 709 char *end; 710 flag = (strtol(arg1, &end, 10) != 0); 711 if (arg1 == end) { 712 out->print_cr("flag value has to be an integer"); 713 return JNI_ERR; 714 } 715 } 716 717 if (strcmp(name, "ExtendedDTraceProbes") == 0) { 718 DTrace::set_extended_dprobes(flag); 719 return JNI_OK; 720 } 721 722 if (strcmp(name, "DTraceMonitorProbes") == 0) { 723 DTrace::set_monitor_dprobes(flag); 724 return JNI_OK; 725 } 726 727 out->print_cr("flag '%s' cannot be changed", name); 728 return JNI_ERR; 729 } 730 731 void AttachListener::pd_detachall() { 732 DTrace::detach_all_clients(); 733 }