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 = ::CreateFile( pipe(),  // pipe name
 276                         GENERIC_WRITE,   // write only
 277                         0,              // no sharing
 278                         NULL,           // default security attributes
 279                         OPEN_EXISTING,  // opens existing pipe
 280                         0,              // default attributes
 281                         NULL);          // no template file
 282   return hPipe;
 283 }
 284 
 285 // write to the pipe
 286 BOOL Win32AttachOperation::write_pipe(HANDLE hPipe, char* buf, int len) {
 287   do {
 288     DWORD nwrote;
 289 
 290     BOOL fSuccess = WriteFile(  hPipe,                  // pipe handle
 291                                 (LPCVOID)buf,           // message
 292                                 (DWORD)len,             // message length
 293                                 &nwrote,                // bytes written
 294                                 NULL);                  // not overlapped
 295     if (!fSuccess) {
 296       return fSuccess;
 297     }
 298     buf += nwrote;
 299     len -= nwrote;
 300   } while (len > 0);
 301   return TRUE;
 302 }
 303 
 304 // Complete the operation:
 305 //   - open the pipe to the client
 306 //   - write the operation result (a jint)
 307 //   - write the operation output (the result stream)
 308 //
 309 void Win32AttachOperation::complete(jint result, bufferedStream* result_stream) {
 310   JavaThread* thread = JavaThread::current();
 311   ThreadBlockInVM tbivm(thread);
 312 
 313   thread->set_suspend_equivalent();
 314   // cleared by handle_special_suspend_equivalent_condition() or
 315   // java_suspend_self() via check_and_wait_while_suspended()
 316 
 317   HANDLE hPipe = open_pipe();
 318   int lastError = (int)::GetLastError();
 319   if (hPipe != INVALID_HANDLE_VALUE) {
 320     BOOL fSuccess;
 321 
 322     char msg[32];
 323     _snprintf(msg, sizeof(msg), "%d\n", result);
 324     msg[sizeof(msg) - 1] = '\0';
 325 
 326     fSuccess = write_pipe(hPipe, msg, (int)strlen(msg));
 327     if (fSuccess) {
 328       fSuccess = write_pipe(hPipe, (char*)result_stream->base(), (int)(result_stream->size()));
 329     }
 330     lastError = (int)::GetLastError();
 331 
 332     // Need to flush buffers
 333     FlushFileBuffers(hPipe);
 334     CloseHandle(hPipe);
 335 
 336     if (fSuccess) {
 337       log_debug(attach)("wrote result of attach operation %s to pipe %s", name(), pipe());
 338     } else {
 339       log_error(attach)("failure (%d) writing result of operation %s to pipe %s", lastError, name(), pipe());
 340     }
 341   } else {
 342     log_error(attach)("could not open (%d) pipe %s to send result of operation %s", lastError, pipe(), name());
 343   }
 344 
 345   DWORD res = ::WaitForSingleObject(Win32AttachListener::mutex(), INFINITE);
 346   if (res == WAIT_OBJECT_0) {
 347 
 348     // put the operation back on the available list
 349     set_next(Win32AttachListener::available());
 350     Win32AttachListener::set_available(this);
 351 
 352     ::ReleaseMutex(Win32AttachListener::mutex());
 353   }
 354 
 355   // were we externally suspended while we were waiting?
 356   thread->check_and_wait_while_suspended();
 357 }
 358 
 359 
 360 // AttachOperation functions
 361 
 362 AttachOperation* AttachListener::dequeue() {
 363   JavaThread* thread = JavaThread::current();
 364   ThreadBlockInVM tbivm(thread);
 365 
 366   thread->set_suspend_equivalent();
 367   // cleared by handle_special_suspend_equivalent_condition() or
 368   // java_suspend_self() via check_and_wait_while_suspended()
 369 
 370   AttachOperation* op = Win32AttachListener::dequeue();
 371 
 372   // were we externally suspended while we were waiting?
 373   thread->check_and_wait_while_suspended();
 374 
 375   return op;
 376 }
 377 
 378 void AttachListener::vm_start() {
 379   // nothing to do
 380 }
 381 
 382 int AttachListener::pd_init() {
 383   return Win32AttachListener::init();
 384 }
 385 
 386 // This function is used for Un*x OSes only.
 387 // We need not to implement it for Windows.
 388 bool AttachListener::check_socket_file() {
 389   return false;
 390 }
 391 
 392 bool AttachListener::init_at_startup() {
 393   return true;
 394 }
 395 
 396 // no trigger mechanism on Windows to start Attach Listener lazily
 397 bool AttachListener::is_init_trigger() {
 398   return false;
 399 }
 400 
 401 void AttachListener::abort() {
 402   // nothing to do
 403 }
 404 
 405 void AttachListener::pd_data_dump() {
 406   os::signal_notify(SIGBREAK);
 407 }
 408 
 409 AttachOperationFunctionInfo* AttachListener::pd_find_operation(const char* n) {
 410   return NULL;
 411 }
 412 
 413 jint AttachListener::pd_set_flag(AttachOperation* op, outputStream* out) {
 414   out->print_cr("flag '%s' cannot be changed", op->arg(0));
 415   return JNI_ERR;
 416 }
 417 
 418 void AttachListener::pd_detachall() {
 419   // do nothing for now
 420 }
 421 
 422 // Native thread started by remote client executes this.
 423 extern "C" {
 424   JNIEXPORT jint JNICALL
 425     JVM_EnqueueOperation(char* cmd, char* arg0, char* arg1, char* arg2, char* pipename) {
 426       return (jint)Win32AttachListener::enqueue(cmd, arg0, arg1, arg2, pipename);
 427     }
 428 
 429 } // extern