1 /*
   2  * Copyright (c) 2005, 2019, 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 "logging/log.hpp"
  27 #include "runtime/interfaceSupport.inline.hpp"
  28 #include "runtime/os.hpp"
  29 #include "services/attachListener.hpp"
  30 #include "services/dtraceAttacher.hpp"
  31 
  32 #include <windows.h>
  33 #include <signal.h>             // SIGBREAK
  34 #include <stdio.h>
  35 
  36 // The AttachListener thread services a queue of operations. It blocks in the dequeue
  37 // function until an operation is enqueued. A client enqueues an operation by creating
  38 // a thread in this process using the Win32 CreateRemoteThread function. That thread
  39 // executes a small stub generated by the client. The stub invokes the
  40 // JVM_EnqueueOperation function which checks the operation parameters and enqueues
  41 // the operation to the queue serviced by the attach listener. The thread created by
  42 // the client is a native thread and is restricted to a single page of stack. To keep
  43 // it simple operations are pre-allocated at initialization time. An enqueue thus
  44 // takes a preallocated operation, populates the operation parameters, adds it to
  45 // queue and wakes up the attach listener.
  46 //
  47 // When an operation has completed the attach listener is required to send the
  48 // operation result and any result data to the client. In this implementation the
  49 // client is a pipe server. In the enqueue operation it provides the name of pipe
  50 // to this process. When the operation is completed this process opens the pipe and
  51 // sends the result and output back to the client. Note that writing to the pipe
  52 // (and flushing the output) is a blocking operation. This means that a non-responsive
  53 // client could potentially hang the attach listener thread indefinitely. In that
  54 // case no new operations would be executed but the VM would continue as normal.
  55 // As only suitably privileged processes can open this process we concluded that
  56 // this wasn't worth worrying about.
  57 
  58 
  59 // forward reference
  60 class Win32AttachOperation;
  61 
  62 
  63 class Win32AttachListener: AllStatic {
  64  private:
  65   enum {
  66     max_enqueued_operations = 4
  67   };
  68 
  69   // protects the preallocated list and the operation list
  70   static HANDLE _mutex;
  71 
  72   // head of preallocated operations list
  73   static Win32AttachOperation* _avail;
  74 
  75   // head and tail of enqueue operations list
  76   static Win32AttachOperation* _head;
  77   static Win32AttachOperation* _tail;
  78 
  79 
  80   static Win32AttachOperation* head()                       { return _head; }
  81   static void set_head(Win32AttachOperation* head)          { _head = head; }
  82 
  83   static Win32AttachOperation* tail()                       { return _tail; }
  84   static void set_tail(Win32AttachOperation* tail)          { _tail = tail; }
  85 
  86 
  87   // A semaphore is used for communication about enqueued operations.
  88   // The maximum count for the semaphore object will be set to "max_enqueued_operations".
  89   // The state of a semaphore is signaled when its count is greater than
  90   // zero (there are operations enqueued), and nonsignaled when it is zero.
  91   static HANDLE _enqueued_ops_semaphore;
  92   static HANDLE enqueued_ops_semaphore() { return _enqueued_ops_semaphore; }
  93 
  94  public:
  95   enum {
  96     ATTACH_ERROR_DISABLED               = 100,              // error codes
  97     ATTACH_ERROR_RESOURCE               = 101,
  98     ATTACH_ERROR_ILLEGALARG             = 102,
  99     ATTACH_ERROR_INTERNAL               = 103
 100   };
 101 
 102   static int init();
 103   static HANDLE mutex()                                     { return _mutex; }
 104 
 105   static Win32AttachOperation* available()                  { return _avail; }
 106   static void set_available(Win32AttachOperation* avail)    { _avail = avail; }
 107 
 108   // enqueue an operation to the end of the list
 109   static int enqueue(char* cmd, char* arg1, char* arg2, char* arg3, char* pipename);
 110 
 111   // dequeue an operation from from head of the list
 112   static Win32AttachOperation* dequeue();
 113 };
 114 
 115 // statics
 116 HANDLE Win32AttachListener::_mutex;
 117 HANDLE Win32AttachListener::_enqueued_ops_semaphore;
 118 Win32AttachOperation* Win32AttachListener::_avail;
 119 Win32AttachOperation* Win32AttachListener::_head;
 120 Win32AttachOperation* Win32AttachListener::_tail;
 121 
 122 
 123 // Win32AttachOperation is an AttachOperation that additionally encapsulates the name
 124 // of a pipe which is used to send the operation reply/output to the client.
 125 // Win32AttachOperation can also be linked in a list.
 126 
 127 class Win32AttachOperation: public AttachOperation {
 128  private:
 129   friend class Win32AttachListener;
 130 
 131   enum {
 132     pipe_name_max = 256             // maximum pipe name
 133   };
 134 
 135   char _pipe[pipe_name_max + 1];
 136 
 137   const char* pipe() const                              { return _pipe; }
 138   void set_pipe(const char* pipe) {
 139     assert(strlen(pipe) <= pipe_name_max, "exceeds maximum length of pipe name");
 140     os::snprintf(_pipe, sizeof(_pipe), "%s", pipe);
 141   }
 142 
 143   HANDLE open_pipe();
 144   static BOOL write_pipe(HANDLE hPipe, char* buf, int len);
 145 
 146   Win32AttachOperation* _next;
 147 
 148   Win32AttachOperation* next() const                    { return _next; }
 149   void set_next(Win32AttachOperation* next)             { _next = next; }
 150 
 151   // noarg constructor as operation is preallocated
 152   Win32AttachOperation() : AttachOperation("<noname>") {
 153     set_pipe("<nopipe>");
 154     set_next(NULL);
 155   }
 156 
 157  public:
 158   void Win32AttachOperation::complete(jint result, bufferedStream* result_stream);
 159 };
 160 
 161 
 162 // Preallocate the maximum number of operations that can be enqueued.
 163 int Win32AttachListener::init() {
 164   _mutex = (void*)::CreateMutex(NULL, FALSE, NULL);
 165   guarantee(_mutex != (HANDLE)NULL, "mutex creation failed");
 166 
 167   _enqueued_ops_semaphore = ::CreateSemaphore(NULL, 0, max_enqueued_operations, NULL);
 168   guarantee(_enqueued_ops_semaphore != (HANDLE)NULL, "semaphore creation failed");
 169 
 170   set_head(NULL);
 171   set_tail(NULL);
 172   set_available(NULL);
 173 
 174   for (int i=0; i<max_enqueued_operations; i++) {
 175     Win32AttachOperation* op = new Win32AttachOperation();
 176     op->set_next(available());
 177     set_available(op);
 178   }
 179 
 180   return 0;
 181 }
 182 
 183 // Enqueue an operation. This is called from a native thread that is not attached to VM.
 184 // Also we need to be careful not to execute anything that results in more than a 4k stack.
 185 //
 186 int Win32AttachListener::enqueue(char* cmd, char* arg0, char* arg1, char* arg2, char* pipename) {
 187   // wait up to 10 seconds for listener to be up and running
 188   int sleep_count = 0;
 189   while (!AttachListener::is_initialized()) {
 190     Sleep(1000); // 1 second
 191     sleep_count++;
 192     if (sleep_count > 10) { // try for 10 seconds
 193       return ATTACH_ERROR_DISABLED;
 194     }
 195   }
 196 
 197   // check that all paramteres to the operation
 198   if (strlen(cmd) > AttachOperation::name_length_max) return ATTACH_ERROR_ILLEGALARG;
 199   if (strlen(arg0) > AttachOperation::arg_length_max) return ATTACH_ERROR_ILLEGALARG;
 200   if (strlen(arg1) > AttachOperation::arg_length_max) return ATTACH_ERROR_ILLEGALARG;
 201   if (strlen(arg2) > AttachOperation::arg_length_max) return ATTACH_ERROR_ILLEGALARG;
 202   if (strlen(pipename) > Win32AttachOperation::pipe_name_max) return ATTACH_ERROR_ILLEGALARG;
 203 
 204   // check for a well-formed pipename
 205   if (strstr(pipename, "\\\\.\\pipe\\") != pipename) return ATTACH_ERROR_ILLEGALARG;
 206 
 207   // grab the lock for the list
 208   DWORD res = ::WaitForSingleObject(mutex(), INFINITE);
 209   if (res != WAIT_OBJECT_0) {
 210     return ATTACH_ERROR_INTERNAL;
 211   }
 212 
 213   // try to get an operation from the available list
 214   Win32AttachOperation* op = available();
 215   if (op != NULL) {
 216     set_available(op->next());
 217 
 218     // add to end (tail) of list
 219     op->set_next(NULL);
 220     if (tail() == NULL) {
 221       set_head(op);
 222     } else {
 223       tail()->set_next(op);
 224     }
 225     set_tail(op);
 226 
 227     op->set_name(cmd);
 228     op->set_arg(0, arg0);
 229     op->set_arg(1, arg1);
 230     op->set_arg(2, arg2);
 231     op->set_pipe(pipename);
 232 
 233     // Increment number of enqueued operations.
 234     // Side effect: Semaphore will be signaled and will release
 235     // any blocking waiters (i.e. the AttachListener thread).
 236     BOOL not_exceeding_semaphore_maximum_count =
 237       ::ReleaseSemaphore(enqueued_ops_semaphore(), 1, NULL);
 238     guarantee(not_exceeding_semaphore_maximum_count, "invariant");
 239   }
 240   ::ReleaseMutex(mutex());
 241 
 242   return (op != NULL) ? 0 : ATTACH_ERROR_RESOURCE;
 243 }
 244 
 245 
 246 // dequeue the operation from the head of the operation list.
 247 Win32AttachOperation* Win32AttachListener::dequeue() {
 248   for (;;) {
 249     DWORD res = ::WaitForSingleObject(enqueued_ops_semaphore(), INFINITE);
 250     // returning from WaitForSingleObject will have decreased
 251     // the current count of the semaphore by 1.
 252     guarantee(res == WAIT_OBJECT_0, "wait failed");
 253 
 254     res = ::WaitForSingleObject(mutex(), INFINITE);
 255     guarantee(res == WAIT_OBJECT_0, "wait failed");
 256 
 257     Win32AttachOperation* op = head();
 258     if (op != NULL) {
 259       set_head(op->next());
 260       if (head() == NULL) {     // list is empty
 261         set_tail(NULL);
 262       }
 263     }
 264     ::ReleaseMutex(mutex());
 265 
 266     if (op != NULL) {
 267       return op;
 268     }
 269   }
 270 }
 271 
 272 
 273 // open the pipe to the client
 274 HANDLE Win32AttachOperation::open_pipe() {
 275   HANDLE hPipe;
 276 
 277   hPipe = ::CreateFile( pipe(),  // pipe name
 278                         GENERIC_WRITE,   // write only
 279                         0,              // no sharing
 280                         NULL,           // default security attributes
 281                         OPEN_EXISTING,  // opens existing pipe
 282                         0,              // default attributes
 283                         NULL);          // no template file
 284 
 285   if (hPipe != INVALID_HANDLE_VALUE) {
 286     // shouldn't happen as there is a pipe created per operation
 287     if (::GetLastError() == ERROR_PIPE_BUSY) {
 288       ::CloseHandle(hPipe);
 289       return INVALID_HANDLE_VALUE;
 290     }
 291   }
 292   return hPipe;
 293 }
 294 
 295 // write to the pipe
 296 BOOL Win32AttachOperation::write_pipe(HANDLE hPipe, char* buf, int len) {
 297   do {
 298     DWORD nwrote;
 299 
 300     BOOL fSuccess = WriteFile(  hPipe,                  // pipe handle
 301                                 (LPCVOID)buf,           // message
 302                                 (DWORD)len,             // message length
 303                                 &nwrote,                // bytes written
 304                                 NULL);                  // not overlapped
 305     if (!fSuccess) {
 306       return fSuccess;
 307     }
 308     buf += nwrote;
 309     len -= nwrote;
 310   }
 311   while (len > 0);
 312   return TRUE;
 313 }
 314 
 315 // Complete the operation:
 316 //   - open the pipe to the client
 317 //   - write the operation result (a jint)
 318 //   - write the operation output (the result stream)
 319 //
 320 void Win32AttachOperation::complete(jint result, bufferedStream* result_stream) {
 321   JavaThread* thread = JavaThread::current();
 322   ThreadBlockInVM tbivm(thread);
 323 
 324   thread->set_suspend_equivalent();
 325   // cleared by handle_special_suspend_equivalent_condition() or
 326   // java_suspend_self() via check_and_wait_while_suspended()
 327 
 328   HANDLE hPipe = open_pipe();
 329   if (hPipe != INVALID_HANDLE_VALUE) {
 330     BOOL fSuccess;
 331 
 332     char msg[32];
 333     _snprintf(msg, sizeof(msg), "%d\n", result);
 334     msg[sizeof(msg) - 1] = '\0';
 335 
 336     fSuccess = write_pipe(hPipe, msg, (int)strlen(msg));
 337     if (fSuccess) {
 338       fSuccess = write_pipe(hPipe, (char*)result_stream->base(), (int)(result_stream->size()));
 339     }
 340 
 341     // Need to flush buffers
 342     FlushFileBuffers(hPipe);
 343     CloseHandle(hPipe);
 344 
 345     if (fSuccess) {
 346       log_debug(attach)("wrote result of attach operation %s to pipe %s", name(), pipe());
 347     } else {
 348       log_error(attach)("failure writing result of operation %s to pipe %s", name(), pipe());
 349     }
 350   } else {
 351     log_error(attach)("could not open pipe %s to send result of operation %s", pipe(), name());
 352   }
 353 
 354   DWORD res = ::WaitForSingleObject(Win32AttachListener::mutex(), INFINITE);
 355   if (res == WAIT_OBJECT_0) {
 356 
 357     // put the operation back on the available list
 358     set_next(Win32AttachListener::available());
 359     Win32AttachListener::set_available(this);
 360 
 361     ::ReleaseMutex(Win32AttachListener::mutex());
 362   }
 363 
 364   // were we externally suspended while we were waiting?
 365   thread->check_and_wait_while_suspended();
 366 }
 367 
 368 
 369 // AttachOperation functions
 370 
 371 AttachOperation* AttachListener::dequeue() {
 372   JavaThread* thread = JavaThread::current();
 373   ThreadBlockInVM tbivm(thread);
 374 
 375   thread->set_suspend_equivalent();
 376   // cleared by handle_special_suspend_equivalent_condition() or
 377   // java_suspend_self() via check_and_wait_while_suspended()
 378 
 379   AttachOperation* op = Win32AttachListener::dequeue();
 380 
 381   // were we externally suspended while we were waiting?
 382   thread->check_and_wait_while_suspended();
 383 
 384   return op;
 385 }
 386 
 387 void AttachListener::vm_start() {
 388   // nothing to do
 389 }
 390 
 391 int AttachListener::pd_init() {
 392   return Win32AttachListener::init();
 393 }
 394 
 395 // This function is used for Un*x OSes only.
 396 // We need not to implement it for Windows.
 397 bool AttachListener::check_socket_file() {
 398   return false;
 399 }
 400 
 401 bool AttachListener::init_at_startup() {
 402   return true;
 403 }
 404 
 405 // no trigger mechanism on Windows to start Attach Listener lazily
 406 bool AttachListener::is_init_trigger() {
 407   return false;
 408 }
 409 
 410 void AttachListener::abort() {
 411   // nothing to do
 412 }
 413 
 414 void AttachListener::pd_data_dump() {
 415   os::signal_notify(SIGBREAK);
 416 }
 417 
 418 AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* n) {
 419   return NULL;
 420 }
 421 
 422 jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
 423   out->print_cr("flag '%s' cannot be changed", op->arg(0));
 424   return JNI_ERR;
 425 }
 426 
 427 void AttachListener::pd_detachall() {
 428   // do nothing for now
 429 }
 430 
 431 // Native thread started by remote client executes this.
 432 extern "C" {
 433   JNIEXPORT jint JNICALL
 434     JVM_EnqueueOperation(char* cmd, char* arg0, char* arg1, char* arg2, char* pipename) {
 435       return (jint)Win32AttachListener::enqueue(cmd, arg0, arg1, arg2, pipename);
 436     }
 437 
 438 } // extern