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