1 /*
2  * Copyright (c) 2001, 2018, 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 package nsk.jdi.ThreadStartRequest.addThreadFilter;
25 
26 import nsk.share.*;
27 import nsk.share.jpda.*;
28 import nsk.share.jdi.*;
29 
30 import com.sun.jdi.*;
31 import com.sun.jdi.event.*;
32 import com.sun.jdi.request.*;
33 
34 import java.util.*;
35 import java.io.*;
36 
37 /**
38  * The test for the implementation of an object of the type     <BR>
39  * ThreadStartRequest.                                          <BR>
40  *                                                              <BR>
41  * The test checks that results of the method                   <BR>
42  * <code>com.sun.jdi.ThreadStartRequest.addThreadFilter()</code> <BR>
43  * complies with its spec.                                      <BR>
44  * <BR>
45  * The cases to check are as follows:
46  * (1) if this request is currently enabled,                    <BR>
47  *   - addThreadFilter(ThreadReference) results in throwing     <BR>
48  *     InvalidRequestStateException;                            <BR>
49  *   - addThreadFilter(null) results in throwing                <BR>
50  *     NullPointerException or InvalidRequestStateException;    <BR>
51  * (2) if this request is currently disabled,                   <BR>
52  *     addThreadFilter(null) results in throwing                <BR>
53  *     NullPointerException.                                    <BR>
54  * <BR>
55  * The test has three phases and works as follows.              <BR>
56  * <BR>
57  * In first phase,                                                      <BR>
58  * upon launching debuggee's VM which will be suspended,                <BR>
59  * a debugger waits for the VMStartEvent within a predefined            <BR>
60  * time interval. If no the VMStartEvent received, the test is FAILED.  <BR>
61  * Upon getting the VMStartEvent, it makes the request for debuggee's   <BR>
62  * ClassPrepareEvent with SUSPEND_EVENT_THREAD, resumes the VM,         <BR>
63  * and waits for the event within the predefined time interval.         <BR>
64  * If no the ClassPrepareEvent received, the test is FAILED.            <BR>
65  * Upon getting the ClassPrepareEvent,                                  <BR>
66  * the debugger sets up the breakpoint with SUSPEND_EVENT_THREAD        <BR>
67  * within debuggee's special methodForCommunication().                  <BR>
68  * <BR>
69  * In second phase, the debugger creates ThreadStartRequest             <BR>
70  * and performs the above checks.                                       <BR>
71  * <BR>
72  * In third phase, at the end of the test,                              <BR>
73  * the debuggee changes the value of the "instruction"                  <BR>
74  * to inform the debugger of checks finished, and both end.             <BR>
75  * <BR>
76  */
77 
78 public class addthreadfilter002 {
79 
80     //----------------------------------------------------- templete section
81     static final int PASSED = 0;
82     static final int FAILED = 2;
83     static final int PASS_BASE = 95;
84 
85     //----------------------------------------------------- templete parameters
86     static final String
87     sHeader1 = "\n==> nsk/jdi/ThreadStartRequest/addThreadFilter/addthreadfilter002 ",
88     sHeader2 = "--> debugger: ",
89     sHeader3 = "##> debugger: ";
90 
91     //----------------------------------------------------- main method
92 
main(String argv[])93     public static void main (String argv[]) {
94 
95         int result = run(argv, System.out);
96 
97         System.exit(result + PASS_BASE);
98     }
99 
run(String argv[], PrintStream out)100     public static int run (String argv[], PrintStream out) {
101 
102         int exitCode = new addthreadfilter002().runThis(argv, out);
103 
104         if (exitCode != PASSED) {
105             System.out.println("TEST FAILED");
106         }
107         return testExitCode;
108     }
109 
110     //--------------------------------------------------   log procedures
111 
112     private static Log  logHandler;
113 
log1(String message)114     private static void log1(String message) {
115         logHandler.display(sHeader1 + message);
116     }
log2(String message)117     private static void log2(String message) {
118         logHandler.display(sHeader2 + message);
119     }
log3(String message)120     private static void log3(String message) {
121         logHandler.complain(sHeader3 + message);
122     }
123 
124     //  ************************************************    test parameters
125 
126     private String debuggeeName =
127         "nsk.jdi.ThreadStartRequest.addThreadFilter.addthreadfilter002a";
128 
129     //====================================================== test program
130     //------------------------------------------------------ common section
131 
132     static Debugee          debuggee;
133     static ArgumentHandler  argsHandler;
134 
135     static int waitTime;
136 
137     static VirtualMachine      vm            = null;
138     static EventRequestManager eventRManager = null;
139     static EventQueue          eventQueue    = null;
140     static EventSet            eventSet      = null;
141     static EventIterator       eventIterator = null;
142 
143     static ReferenceType       debuggeeClass = null;
144 
145     static int  testExitCode = PASSED;
146 
147 
148     class JDITestRuntimeException extends RuntimeException {
JDITestRuntimeException(String str)149         JDITestRuntimeException(String str) {
150             super("JDITestRuntimeException : " + str);
151         }
152     }
153 
154     //------------------------------------------------------ methods
155 
runThis(String argv[], PrintStream out)156     private int runThis (String argv[], PrintStream out) {
157 
158         argsHandler     = new ArgumentHandler(argv);
159         logHandler      = new Log(out, argsHandler);
160         Binder binder   = new Binder(argsHandler, logHandler);
161 
162         waitTime        = argsHandler.getWaitTime() * 60000;
163 
164         try {
165             log2("launching a debuggee :");
166             log2("       " + debuggeeName);
167             if (argsHandler.verbose()) {
168                 debuggee = binder.bindToDebugee(debuggeeName + " -vbs");
169             } else {
170                 debuggee = binder.bindToDebugee(debuggeeName);
171             }
172             if (debuggee == null) {
173                 log3("ERROR: no debuggee launched");
174                 return FAILED;
175             }
176             log2("debuggee launched");
177         } catch ( Exception e ) {
178             log3("ERROR: Exception : " + e);
179             log2("       test cancelled");
180             return FAILED;
181         }
182 
183         debuggee.redirectOutput(logHandler);
184 
185         vm = debuggee.VM();
186 
187         eventQueue = vm.eventQueue();
188         if (eventQueue == null) {
189             log3("ERROR: eventQueue == null : TEST ABORTED");
190             vm.exit(PASS_BASE);
191             return FAILED;
192         }
193 
194         log2("invocation of the method runTest()");
195         switch (runTest()) {
196 
197             case 0 :  log2("test phase has finished normally");
198                       log2("   waiting for the debuggee to finish ...");
199                       debuggee.waitFor();
200 
201                       log2("......getting the debuggee's exit status");
202                       int status = debuggee.getStatus();
203                       if (status != PASS_BASE) {
204                           log3("ERROR: debuggee returned UNEXPECTED exit status: " +
205                               status + " != PASS_BASE");
206                           testExitCode = FAILED;
207                       } else {
208                           log2("......debuggee returned expected exit status: " +
209                               status + " == PASS_BASE");
210                       }
211                       break;
212 
213             default : log3("ERROR: runTest() returned unexpected value");
214 
215             case 1 :  log3("test phase has not finished normally: debuggee is still alive");
216                       log2("......forcing: vm.exit();");
217                       testExitCode = FAILED;
218                       try {
219                           vm.exit(PASS_BASE);
220                       } catch ( Exception e ) {
221                           log3("ERROR: Exception : e");
222                       }
223                       break;
224 
225             case 2 :  log3("test cancelled due to VMDisconnectedException");
226                       log2("......trying: vm.process().destroy();");
227                       testExitCode = FAILED;
228                       try {
229                           Process vmProcess = vm.process();
230                           if (vmProcess != null) {
231                               vmProcess.destroy();
232                           }
233                       } catch ( Exception e ) {
234                           log3("ERROR: Exception : e");
235                       }
236                       break;
237             }
238 
239         return testExitCode;
240     }
241 
242 
243    /*
244     * Return value: 0 - normal end of the test
245     *               1 - ubnormal end of the test
246     *               2 - VMDisconnectedException while test phase
247     */
248 
runTest()249     private int runTest() {
250 
251         try {
252             testRun();
253 
254             log2("waiting for VMDeathEvent");
255             getEventSet();
256             if (eventIterator.nextEvent() instanceof VMDeathEvent)
257                 return 0;
258 
259             log3("ERROR: last event is not the VMDeathEvent");
260             return 1;
261         } catch ( VMDisconnectedException e ) {
262             log3("ERROR: VMDisconnectedException : " + e);
263             return 2;
264         } catch ( Exception e ) {
265             log3("ERROR: Exception : " + e);
266             return 1;
267         }
268 
269     }
270 
271 
testRun()272     private void testRun()
273                  throws JDITestRuntimeException, Exception {
274 
275         eventRManager = vm.eventRequestManager();
276 
277         ClassPrepareRequest cpRequest = eventRManager.createClassPrepareRequest();
278         cpRequest.setSuspendPolicy( EventRequest.SUSPEND_EVENT_THREAD);
279         cpRequest.addClassFilter(debuggeeName);
280 
281         cpRequest.enable();
282         vm.resume();
283         getEventSet();
284         cpRequest.disable();
285 
286         ClassPrepareEvent event = (ClassPrepareEvent) eventIterator.next();
287         debuggeeClass = event.referenceType();
288 
289         if (!debuggeeClass.name().equals(debuggeeName))
290            throw new JDITestRuntimeException("** Unexpected ClassName for ClassPrepareEvent **");
291 
292         log2("      received: ClassPrepareEvent for debuggeeClass");
293 
294         String bPointMethod = "methodForCommunication";
295         String lineForComm  = "lineForComm";
296         BreakpointRequest bpRequest;
297 
298         ThreadReference mainThread = threadByName("main");
299 
300         bpRequest = settingBreakpoint(mainThread,
301                                       debuggeeClass,
302                                       bPointMethod, lineForComm, "zero");
303         bpRequest.enable();
304 
305     //------------------------------------------------------  testing section
306 
307         log1("     TESTING BEGINS");
308 
309 
310         for (int i = 0; ; i++) {
311 
312             vm.resume();
313             breakpointForCommunication();
314 
315             int instruction = ((IntegerValue)
316                                (debuggeeClass.getValue(debuggeeClass.fieldByName("instruction")))).value();
317 
318             if (instruction == 0) {
319                 vm.resume();
320                 break;
321             }
322 
323             log1(":::::: case: # " + i);
324 
325             //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ variable part
326 
327             log2("......setting up ThreadStartRequest");
328             log2("...... ThreadStartRequest tsr1 = eventRManager.createThreadStartRequest();");
329             ThreadStartRequest tsr1 = eventRManager.createThreadStartRequest();
330             tsr1.addCountFilter(1);
331             tsr1.setSuspendPolicy(EventRequest.SUSPEND_ALL);
332             tsr1.putProperty("number", "ThreadStartRequest1");
333 
334             log2("...... tsr1.enable();");
335             tsr1.enable();
336 
337             try {
338                 log2("...... tsr1.addThreadFilter(mainThread);");
339                 log2("         InvalidRequestStateException is expected");
340                 tsr1.addThreadFilter(mainThread);
341                 log3("ERROR: no InvalidRequestStateException ");
342                 testExitCode = FAILED;
343             } catch ( InvalidRequestStateException e ) {
344                 log2("          InvalidRequestStateException");
345             } catch ( Exception e ) {
346                 log3("ERROR: unexpected Exception : " + e);
347                 testExitCode = FAILED;
348             }
349             try {
350                 log2("...... tsr1.addThreadFilter(null);");
351                 log2("         NullPointerException or InvalidRequestStateException is expected");
352                 tsr1.addThreadFilter(null);
353                 log3("ERROR: no Exception thrown");
354                 testExitCode = FAILED;
355             } catch ( NullPointerException e ) {
356                 log2("          NullPointerException");
357             } catch ( InvalidRequestStateException e ) {
358                 log2("          InvalidRequestStateException");
359             } catch ( Exception e ) {
360                 log3("ERROR: unexpected Exception : " + e);
361                 testExitCode = FAILED;
362             }
363 
364             log2("...... tsr1.disable()");
365             tsr1.disable();
366 
367             try {
368                 log2("...... tsr1.addThreadFilter(null);");
369                 log2("         NullPointerException is expected");
370                 tsr1.addThreadFilter(null);
371                 log3("ERROR: no NullPointerException ");
372                 testExitCode = FAILED;
373             } catch ( NullPointerException e ) {
374                 log2("          NullPointerException");
375             } catch ( Exception e ) {
376                 log3("ERROR: unexpected Exception : " + e);
377                 testExitCode = FAILED;
378             }
379             //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
380         }
381         log1("    TESTING ENDS");
382         return;
383     }
384 
threadByName(String name)385     private ThreadReference threadByName(String name)
386                  throws JDITestRuntimeException {
387 
388         List         all = vm.allThreads();
389         ListIterator li  = all.listIterator();
390 
391         for (; li.hasNext(); ) {
392             ThreadReference thread = (ThreadReference) li.next();
393             if (thread.name().equals(name))
394                 return thread;
395         }
396         throw new JDITestRuntimeException("** Thread IS NOT found ** : " + name);
397     }
398 
399    /*
400     * private BreakpointRequest settingBreakpoint(ThreadReference, ReferenceType,
401     *                                             String, String, String)
402     *
403     * It sets up a breakpoint at given line number within a given method in a given class
404     * for a given thread.
405     *
406     * Return value: BreakpointRequest object  in case of success
407     *
408     * JDITestRuntimeException   in case of an Exception thrown within the method
409     */
410 
settingBreakpoint( ThreadReference thread, ReferenceType testedClass, String methodName, String bpLine, String property)411     private BreakpointRequest settingBreakpoint ( ThreadReference thread,
412                                                   ReferenceType testedClass,
413                                                   String methodName,
414                                                   String bpLine,
415                                                   String property)
416             throws JDITestRuntimeException {
417 
418         log2("......setting up a breakpoint:");
419         log2("       thread: " + thread + "; class: " + testedClass +
420                         "; method: " + methodName + "; line: " + bpLine);
421 
422         List              alllineLocations = null;
423         Location          lineLocation     = null;
424         BreakpointRequest breakpRequest    = null;
425 
426         try {
427             Method  method  = (Method) testedClass.methodsByName(methodName).get(0);
428 
429             alllineLocations = method.allLineLocations();
430 
431             int n =
432                 ( (IntegerValue) testedClass.getValue(testedClass.fieldByName(bpLine) ) ).value();
433             if (n > alllineLocations.size()) {
434                 log3("ERROR:  TEST_ERROR_IN_settingBreakpoint(): number is out of bound of method's lines");
435             } else {
436                 lineLocation = (Location) alllineLocations.get(n);
437                 try {
438                     breakpRequest = eventRManager.createBreakpointRequest(lineLocation);
439                     breakpRequest.putProperty("number", property);
440                     breakpRequest.addThreadFilter(thread);
441                     breakpRequest.setSuspendPolicy( EventRequest.SUSPEND_EVENT_THREAD);
442                 } catch ( Exception e1 ) {
443                     log3("ERROR: inner Exception within settingBreakpoint() : " + e1);
444                     breakpRequest    = null;
445                 }
446             }
447         } catch ( Exception e2 ) {
448             log3("ERROR: ATTENTION:  outer Exception within settingBreakpoint() : " + e2);
449             breakpRequest    = null;
450         }
451 
452         if (breakpRequest == null) {
453             log2("      A BREAKPOINT HAS NOT BEEN SET UP");
454             throw new JDITestRuntimeException("**FAILURE to set up a breakpoint**");
455         }
456 
457         log2("      a breakpoint has been set up");
458         return breakpRequest;
459     }
460 
461 
getEventSet()462     private void getEventSet()
463                  throws JDITestRuntimeException {
464         try {
465 //            log2("       eventSet = eventQueue.remove(waitTime);");
466             eventSet = eventQueue.remove(waitTime);
467             if (eventSet == null) {
468                 throw new JDITestRuntimeException("** TIMEOUT while waiting for event **");
469             }
470 //            log2("       eventIterator = eventSet.eventIterator;");
471             eventIterator = eventSet.eventIterator();
472         } catch ( Exception e ) {
473             throw new JDITestRuntimeException("** EXCEPTION while waiting for event ** : " + e);
474         }
475     }
476 
477 
breakpointForCommunication()478     private void breakpointForCommunication()
479                  throws JDITestRuntimeException {
480 
481         log2("breakpointForCommunication");
482         getEventSet();
483 
484         if (eventIterator.nextEvent() instanceof BreakpointEvent)
485             return;
486 
487         throw new JDITestRuntimeException("** event IS NOT a breakpoint **");
488     }
489 
490 }
491