Debian Codegraph @

native/jpype_module/src/main/java/org/jpype/JPypeContext.java

raw symbols SCIP
1 /* ****************************************************************************
2 Licensed under the Apache License, Version 2.0 (the "License");
3 you may not use this file except in compliance with the License.
4 You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS,
10 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 See the License for the specific language governing permissions and
12 limitations under the License.
13
14 See NOTICE file for details.
15 **************************************************************************** */
16 package org.jpype;
17
18 import java.io.File;
19 import java.io.IOException;
20 import java.lang.reflect.Array;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.nio.Buffer;
24 import java.nio.ByteOrder;
25 import java.nio.file.Paths;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.concurrent.atomic.AtomicInteger;
31 import org.jpype.manager.TypeFactory;
32 import org.jpype.manager.TypeFactoryNative;
33 import org.jpype.manager.TypeManager;
34 import org.jpype.pkg.JPypePackage;
35 import org.jpype.pkg.JPypePackageManager;
36 import org.jpype.ref.JPypeReferenceQueue;
37
38 /**
39 * Context for JPype.
40 * <p>
41 * This is the part of JPype that holds all resources. After the classloader is
42 * created this class is given the address of the context object in JPype. Any
43 * resources in JPype Java layer can be contacted using the context.
44 * <p>
45 * Boot order is - create the C++ portion of the context. - start the jvm - load
46 * the bootloader - install the jar into the bootloader - install all native
47 * methods using the bootloader - create the Java portion of the context. - use
48 * the Java context to access the resources (ReferenceQueue, TypeFactory,
49 * TypeManager)
50 * <p>
51 * Once started, python calls use the context to get a frame and attach their
52 * threads. Methods called from Java will get the env and use it to get their
53 * context from which they can create a frame.
54 * <p>
55 * The C++ context will hold all the previous global variables thus allowing the
56 * C++ portion to be cleaned up properly when the JVM is shutdown or
57 * disconnected.
58 * <p>
59 * As the JPypeContext can't be tested directly from Java code, it will need to
60 * be kept light.
61 * <p>
62 * Our goal is to remove as much direct contact methods as possible from the C++
63 * layer. Previous globals in JPTypeManager move to the context as do the
64 * contents of JPJni.
65 *
66 *
67 *
68 * @author nelson85
69 */
70 public class JPypeContext
71 {
72
73 public final String VERSION = "1.6.0";
74
75 private static final JPypeContext INSTANCE = new JPypeContext();
76 // This is the C++ portion of the context.
77 private long context;
78 private TypeFactory typeFactory;
79 private TypeManager typeManager;
80 private JPypeClassLoader classLoader;
81 private final AtomicInteger shutdownFlag = new AtomicInteger();
82 private final List<Thread> shutdownHooks = new ArrayList<>();
83 private final List<Runnable> postHooks = new ArrayList<>();
84 public static boolean freeResources = true;
85 public JPypeReflector reflector = null;
86
87 static public JPypeContext getInstance()
88 {
89 return INSTANCE;
90 }
91
92 /**
93 * Start the JPype system.
94 *
95 * @param context is the C++ portion of the context.
96 * @param loader is the classloader holding JPype resources.
97 * @return the created context.
98 */
99 private static JPypeContext createContext(long context, ClassLoader loader, String nativeLib, boolean interrupt) throws Throwable
100 {
101 try
102 {
103 if (nativeLib != null)
104 {
105 System.load(nativeLib);
106 }
107 INSTANCE.context = context;
108 INSTANCE.classLoader = (JPypeClassLoader) loader;
109 INSTANCE.typeFactory = new TypeFactoryNative();
110 INSTANCE.typeManager = new TypeManager(context, INSTANCE.typeFactory);
111 INSTANCE.initialize(interrupt);
112
113 try
114 {
115 INSTANCE.reflector = (JPypeReflector) Class.forName("org.jpype.Reflector0", true, loader)
116 .getConstructor()
117 .newInstance();
118 } catch (ClassNotFoundException | NoSuchMethodException | SecurityException
119 | InstantiationException | IllegalAccessException
120 | IllegalArgumentException | InvocationTargetException ex)
121 {
122 throw new RuntimeException("Unable to create reflector " + ex.getMessage(), ex);
123 }
124
125 scanExistingJars();
126 return INSTANCE;
127 } catch (Throwable ex)
128 {
129 ex.printStackTrace(System.err);
130 throw ex;
131 }
132 }
133
134 private JPypeContext()
135 {
136 }
137
138 private void initialize(boolean interrupt)
139 {
140 // Okay everything is setup so lets give it a go.
141 this.typeManager.init();
142 JPypeReferenceQueue.getInstance().start();
143 if (!interrupt)
144 JPypeSignal.installHandlers();
145
146 // Install a shutdown hook to clean up Python resources.
147 Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
148 {
149 @Override
150 public void run()
151 {
152 INSTANCE.shutdown();
153 }
154 }));
155
156 }
157
158 /**
159 * Shutdown and remove all Python resources.
160 *
161 * This hook is only called after the last user thread has died. Thus the only
162 * remaining connections are proxies that were attached to the JVM shutdown
163 * hook, the reference queue, and the typemanager.
164 *
165 * This routine will try to take out the last connections in an orderly
166 * fashion. Inherently this is a very dangerous time as portions of Java have
167 * already been deactivated.
168 */
169 @SuppressWarnings(
170 {
171 "CallToThreadYield", "SleepWhileInLoop"
172 })
173 private void shutdown()
174 {
175 try
176 {
177 // Try to yield in case there is a race condition. The user
178 // may have installed a shutdown hook, but we cannot verify
179 // the order that shutdown hook threads are executed. Thus we will
180 // try to intentionally lose the race.
181 //
182 // This will only occur if something registered a shutdown hook through
183 // a Java API. Those registered though the JPype API will be joined
184 // manually.
185 for (int i = 0; i < 5; i++)
186 {
187 try
188 {
189 Thread.sleep(1);
190 Thread.yield();
191 } catch (InterruptedException ex)
192 {
193 }
194 }
195
196 // Execute any used defined shutdown hooks registered with JPype.
197 if (!this.shutdownHooks.isEmpty())
198 {
199 for (Thread thread : this.shutdownHooks)
200 {
201 thread.start();
202 }
203 for (Thread thread : this.shutdownHooks)
204 {
205 try
206 {
207 thread.join();
208 } catch (InterruptedException ex)
209 {
210 }
211 }
212 }
213
214 // Disable all future calls to proxies
215 this.shutdownFlag.incrementAndGet();
216
217 // Past this point any further execution of a Python proxy would
218 // be fatal.
219 Thread t1 = Thread.currentThread();
220 Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
221
222 for (Thread t : threads.keySet())
223 {
224 if (t1 == t || t.isDaemon())
225 continue;
226 t.interrupt();
227 }
228
229 // Inform Python no more calls are permitted
230 onShutdown(this.context);
231 Thread.yield();
232
233 } catch (Throwable th)
234 {
235 }
236
237 if (freeResources)
238 {
239 // Release all Python references
240 try
241 {
242 JPypeReferenceQueue.getInstance().stop();
243 } catch (Throwable th)
244 {
245 }
246
247 // Release any C++ resources
248 try
249 {
250 this.typeManager.shutdown();
251 } catch (Throwable th)
252 {
253 }
254 }
255
256 // Execute post hooks
257 for (Runnable run : this.postHooks)
258 {
259 run.run();
260 }
261 try
262 {
263 classLoader.close();
264 } catch (IOException ex)
265 {
266 // ignored
267 }
268
269 }
270
271 private static native void onShutdown(long ctxt);
272
273 public void addShutdownHook(Thread th)
274 {
275 this.shutdownHooks.add(th);
276 }
277
278 public boolean removeShutdownHook(Thread th)
279 {
280 if (this.shutdownHooks.contains(th))
281 {
282 this.shutdownHooks.remove(th);
283 return true;
284 } else
285 return Runtime.getRuntime().removeShutdownHook(th);
286 }
287
288 /**
289 * Get the C++ portion.
290 *
291 * @return
292 */
293 public long getContext()
294 {
295 return context;
296 }
297
298 public ClassLoader getClassLoader()
299 {
300 if (this.classLoader == null)
301 this.classLoader = new JPypeClassLoader(ClassLoader.getSystemClassLoader());
302 return this.classLoader;
303 }
304
305 public TypeFactory getTypeFactory()
306 {
307 return this.typeFactory;
308 }
309
310 public TypeManager getTypeManager()
311 {
312 return this.typeManager;
313 }
314
315 /**
316 * Add a hook to run after Python interface is shutdown.
317 *
318 * This must never have a Python method attached.
319 *
320 * @param run
321 */
322 public void _addPost(Runnable run)
323 {
324 this.postHooks.add(run);
325 }
326
327 /**
328 * Helper function for collect rectangular,
329 */
330 private static boolean collect(List l, Object o, int q, int[] shape, int d)
331 {
332 if (Array.getLength(o) != shape[q])
333 return false;
334 if (q + 1 == d)
335 {
336 l.add(o);
337 return true;
338 }
339 for (int i = 0; i < shape[q]; ++i)
340 {
341 if (!collect(l, Array.get(o, i), q + 1, shape, d))
342 return false;
343 }
344 return true;
345 }
346
347 /**
348 * Collect up a rectangular primitive array for a Python memory view.
349 *
350 * If it is a rectangular primitive array then the result will be an object
351 * array containing. - the primitive type - an int array with the shape of the
352 * array - each of the primitive arrays that will need be visited in order.
353 *
354 * This is the safest way to provide a view as we are verifying and collected
355 * thus even if something mutates the shape of the array after we have
356 * visited, we have a locked copy.
357 *
358 * @param o is the object to be tested.
359 * @return null if the object is not a rectangular primitive array.
360 */
361 public Object[] collectRectangular(Object o)
362 {
363 if (o == null || !o.getClass().isArray())
364 return null;
365 int[] shape = new int[5];
366 int d = 0;
367 ArrayList<Object> out = new ArrayList<>();
368 Object o1 = o;
369 Class c1 = o1.getClass();
370 for (int i = 0; i < 5; ++i)
371 {
372 int l = Array.getLength(o1);
373 if (l == 0)
374 return null;
375 shape[d++] = l;
376 o1 = Array.get(o1, 0);
377 if (o1 == null)
378 return null;
379 c1 = c1.getComponentType();
380 if (!c1.isArray())
381 break;
382 }
383 if (!c1.isPrimitive())
384 return null;
385 out.add(c1);
386 shape = Arrays.copyOfRange(shape, 0, d);
387 out.add(shape);
388 int total = 1;
389 for (int i = 0; i < d - 1; i++)
390 total *= shape[i];
391 out.ensureCapacity(total + 2);
392 if (d == 5)
393 return null;
394 if (!collect(out, o, 0, shape, d))
395 return null;
396 return out.toArray();
397 }
398
399 private Object unpack(int size, Object parts)
400 {
401 Object e0 = Array.get(parts, 0);
402 Class c = e0.getClass();
403 int segments = Array.getLength(parts) / size;
404 Object a2 = Array.newInstance(c, size);
405 Object a1 = Array.newInstance(a2.getClass(), segments);
406 int k = 0;
407 for (int i = 0; i < segments; i++)
408 {
409 for (int j = 0; j < size; j++, k++)
410 {
411 Object o = Array.get(parts, k);
412 Array.set(a2, j, o);
413 }
414 Array.set(a1, i, a2);
415 if (i < segments - 1)
416 a2 = Array.newInstance(c, size);
417 }
418 return a1;
419 }
420
421 private Object assemble(int[] dims, Object parts)
422 {
423 int n = dims.length;
424 if (n == 1)
425 return Array.get(parts, 0);
426 if (n == 2)
427 return Array.get(unpack(dims[0], parts), 0);
428 for (int i = 0; i < n - 2; ++i)
429 {
430 parts = unpack(dims[n - i - 2], parts);
431 }
432 return parts;
433 }
434
435 public boolean isShutdown()
436 {
437 return shutdownFlag.get() > 0;
438 }
439
440 /**
441 * Clear the current interrupt.
442 *
443 * @param x is true if an exception should be thrown.
444 * @throws InterruptedException
445 */
446 public static void clearInterrupt(boolean x) throws InterruptedException
447 {
448 try
449 {
450 Thread th = Thread.currentThread();
451
452 // Only relevant if this is the main thread for signal handling
453 if (th != JPypeSignal.main)
454 return;
455
456 // Unconditionally clear the interrupt flag if we are called from
457 // C++. This happens when a field get() or method call() is
458 // invoked.
459 if (!x)
460 JPypeSignal.acknowledgePy();
461
462 // Check if this thread is interrupted
463 if (th.isInterrupted())
464 {
465 // Clear the flag in C++
466 JPypeSignal.acknowledgePy();
467
468 // Clear the flag in Java
469 Thread.sleep(1);
470 }
471 } catch (InterruptedException ex)
472 {
473 if (x)
474 throw ex;
475 }
476 }
477
478 public long getExcClass(Throwable th)
479 {
480 if (th instanceof PyExceptionProxy)
481 return ((PyExceptionProxy) th).cls;
482 return 0;
483 }
484
485 public long getExcValue(Throwable th)
486 {
487 if (th instanceof PyExceptionProxy)
488 return ((PyExceptionProxy) th).value;
489 return 0;
490 }
491
492 private Exception createException(long l0, long l1)
493 {
494 return new PyExceptionProxy(l0, l1);
495 }
496
497 private boolean order(Buffer b)
498 {
499 if (b instanceof java.nio.ByteBuffer)
500 return ((java.nio.ByteBuffer) b).order() == ByteOrder.LITTLE_ENDIAN;
501 if (b instanceof java.nio.ShortBuffer)
502 return ((java.nio.ShortBuffer) b).order() == ByteOrder.LITTLE_ENDIAN;
503 if (b instanceof java.nio.CharBuffer)
504 return ((java.nio.CharBuffer) b).order() == ByteOrder.LITTLE_ENDIAN;
505 if (b instanceof java.nio.IntBuffer)
506 return ((java.nio.IntBuffer) b).order() == ByteOrder.LITTLE_ENDIAN;
507 if (b instanceof java.nio.LongBuffer)
508 return ((java.nio.LongBuffer) b).order() == ByteOrder.LITTLE_ENDIAN;
509 if (b instanceof java.nio.FloatBuffer)
510 return ((java.nio.FloatBuffer) b).order() == ByteOrder.LITTLE_ENDIAN;
511 if (b instanceof java.nio.DoubleBuffer)
512 return ((java.nio.DoubleBuffer) b).order() == ByteOrder.LITTLE_ENDIAN;
513 return true;
514 }
515
516 public boolean isPackage(String s)
517 {
518 s = JPypeKeywords.safepkg(s);
519 return JPypePackageManager.isPackage(s);
520 }
521
522 public JPypePackage getPackage(String s)
523 {
524 s = JPypeKeywords.safepkg(s);
525 if (!JPypePackageManager.isPackage(s))
526 return null;
527 return new JPypePackage(s);
528 }
529
530 /**
531 * Utility to probe functional interfaces.
532 *
533 * @param cls
534 * @return
535 */
536 public static String getFunctional(Class cls)
537 {
538 Method m = JPypeUtilities.getFunctionalInterfaceMethod(cls);
539 return m != null ? m.getName() : null;
540 }
541
542 /**
543 * Utility function for extracting the unique portion of a stack trace.
544 *
545 * This is a bit different that the Java method which works from the back. We
546 * will be using fake stacktraces from Python at some point so finding the
547 * first common is a better approach.
548 *
549 * @param th is the throwable.
550 * @param enclosing is the throwsble that holds this or null if top level.
551 * @return the unique frames as an object array with 4 objects per frame.
552 */
553 public Object[] getStackTrace(Throwable th, Throwable enclosing)
554 {
555 StackTraceElement[] trace = th.getStackTrace();
556 if (trace == null || enclosing == null)
557 return toFrames(trace);
558 StackTraceElement[] te = enclosing.getStackTrace();
559 if (te == null)
560 return toFrames(trace);
561 for (int i = 0; i < trace.length; ++i)
562 {
563 if (trace[i].equals(te[0]))
564 {
565 return toFrames(Arrays.copyOfRange(trace, 0, i));
566 }
567 }
568 return toFrames(trace);
569 }
570
571 private Object[] toFrames(StackTraceElement[] stackTrace)
572 {
573 if (stackTrace == null)
574 return null;
575 Object[] out = new Object[4 * stackTrace.length];
576 int i = 0;
577 for (StackTraceElement fr : stackTrace)
578 {
579 out[i++] = fr.getClassName();
580 out[i++] = fr.getMethodName();
581 out[i++] = fr.getFileName();
582 out[i++] = fr.getLineNumber();
583 }
584 return out;
585
586 }
587
588 public void newWrapper(long l)
589 {
590 // We can only go through this point single file.
591 synchronized (this.typeFactory)
592 {
593 this.typeFactory.newWrapper(context, l);
594 }
595 }
596
597 private static void scanExistingJars()
598 {
599 // Scan existing jars for missing directory entries
600 String[] paths = System.getProperty("java.class.path").split(File.pathSeparator);
601 for (String path : paths)
602 {
603 INSTANCE.classLoader.scanJar(Paths.get(path));
604 }
605 }
606
607 private static long getTotalMemory()
608 {
609 return Runtime.getRuntime().totalMemory();
610 }
611
612 private static long getFreeMemory()
613 {
614 return Runtime.getRuntime().freeMemory();
615 }
616
617 private static long getMaxMemory()
618 {
619 return Runtime.getRuntime().maxMemory();
620 }
621
622 private static long getUsedMemory()
623 {
624 return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
625 }
626
627 private static long getHeapMemory()
628 {
629 java.lang.management.MemoryMXBean memoryBean = java.lang.management.ManagementFactory.getMemoryMXBean();
630 return memoryBean.getHeapMemoryUsage().getUsed();
631 }
632 }