Introducing Agent-Class to allow java.lang.instrument-like transforms of the @JavaScriptBody annotation
2 * HTML via Java(tm) Language Bindings
3 * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details. apidesign.org
13 * designates this particular file as subject to the
14 * "Classpath" exception as provided by apidesign.org
15 * in the License file that accompanied this code.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. Look for COPYING file in the top folder.
19 * If not, see http://wiki.apidesign.org/wiki/GPLwithClassPathException
21 package org.apidesign.html.boot.impl;
23 import java.io.Closeable;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.io.Reader;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.Enumeration;
31 import java.util.List;
32 import java.util.concurrent.Callable;
33 import org.apidesign.html.boot.spi.Fn;
34 import org.objectweb.asm.AnnotationVisitor;
35 import org.objectweb.asm.ClassReader;
36 import org.objectweb.asm.ClassVisitor;
37 import org.objectweb.asm.ClassWriter;
38 import org.objectweb.asm.Label;
39 import org.objectweb.asm.MethodVisitor;
40 import org.objectweb.asm.Opcodes;
41 import org.objectweb.asm.Type;
42 import org.objectweb.asm.signature.SignatureReader;
43 import org.objectweb.asm.signature.SignatureVisitor;
44 import org.objectweb.asm.signature.SignatureWriter;
48 * @author Jaroslav Tulach <jtulach@netbeans.org>
50 public final class FnUtils implements Fn.Presenter {
55 public static boolean isJavaScriptCapable(ClassLoader l) {
56 if (l instanceof JsClassLoader) {
60 try (Closeable c = Fn.activate(new FnUtils())) {
61 clazz = Class.forName(Test.class.getName(), true, l);
62 final Object is = ((Callable<?>)clazz.newInstance()).call();
63 return Boolean.TRUE.equals(is);
64 } catch (Exception ex) {
69 public static boolean isValid(Fn fn) {
70 return fn != null && fn.isValid();
73 public static ClassLoader newLoader(final FindResources f, final Fn.Presenter d, ClassLoader parent) {
74 return new JsClassLoader(parent) {
76 protected URL findResource(String name) {
77 List<URL> l = res(name, true);
78 return l.isEmpty() ? null : l.get(0);
82 protected Enumeration<URL> findResources(String name) {
83 return Collections.enumeration(res(name, false));
86 private List<URL> res(String name, boolean oneIsEnough) {
87 List<URL> l = new ArrayList<URL>();
88 f.findResources(name, l, oneIsEnough);
93 protected Fn defineFn(String code, String... names) {
94 return d.defineFn(code, names);
98 protected void loadScript(Reader code) throws Exception {
104 static String callback(final String body) {
105 return new JsCallback() {
107 protected CharSequence callMethod(
108 String ident, String fqn, String method, String params
110 StringBuilder sb = new StringBuilder();
111 sb.append("vm.").append(mangle(fqn, method, params));
122 static void loadScript(ClassLoader jcl, String resource) {
123 final InputStream script = jcl.getResourceAsStream(resource);
124 if (script == null) {
125 throw new NullPointerException("Can't find " + resource);
130 isr = new InputStreamReader(script, "UTF-8");
131 FnContext.currentPresenter().loadScript(isr);
137 } catch (Exception ex) {
138 throw new IllegalStateException("Can't execute " + resource, ex);
143 public Fn defineFn(String code, String... names) {
148 public void displayPage(URL page, Runnable onPageLoad) {
152 public void loadScript(Reader code) throws Exception {
155 private static final class FindInClass extends ClassVisitor {
158 private ClassLoader loader;
160 public FindInClass(ClassLoader l, ClassVisitor cv) {
161 super(Opcodes.ASM4, cv);
166 public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
168 super.visit(version, access, name, signature, superName, interfaces);
172 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
173 if ("Lnet/java/html/js/JavaScriptResource;".equals(desc)) {
174 return new LoadResource();
176 return super.visitAnnotation(desc, visible);
180 public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
181 return new FindInMethod(access, name, desc,
182 super.visitMethod(access & (~Opcodes.ACC_NATIVE), name, desc, signature, exceptions)
186 private final class FindInMethod extends MethodVisitor {
188 private final String name;
189 private final String desc;
190 private final int access;
191 private List<String> args;
193 private boolean bodyGenerated;
195 public FindInMethod(int access, String name, String desc, MethodVisitor mv) {
196 super(Opcodes.ASM4, mv);
197 this.access = access;
203 public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
204 if ("Lnet/java/html/js/JavaScriptBody;".equals(desc) // NOI18N
205 || "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;".equals(desc) // NOI18N
208 return new FindInAnno();
210 return super.visitAnnotation(desc, visible);
213 private void generateJSBody(List<String> args, String body) {
219 public void visitCode() {
226 private boolean generateBody() {
230 bodyGenerated = true;
232 super.visitFieldInsn(
233 Opcodes.GETSTATIC, FindInClass.this.name,
234 "$$fn$$" + name + "_" + found,
235 "Lorg/apidesign/html/boot/spi/Fn;"
237 super.visitInsn(Opcodes.DUP);
238 super.visitMethodInsn(
239 Opcodes.INVOKESTATIC,
240 "org/apidesign/html/boot/spi/Fn", "isValid",
241 "(Lorg/apidesign/html/boot/spi/Fn;)Z"
243 Label ifNotNull = new Label();
244 super.visitJumpInsn(Opcodes.IFNE, ifNotNull);
247 super.visitInsn(Opcodes.POP);
248 super.visitLdcInsn(Type.getObjectType(FindInClass.this.name));
249 super.visitLdcInsn(body);
250 super.visitIntInsn(Opcodes.SIPUSH, args.size());
251 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/String");
252 boolean needsVM = false;
253 for (int i = 0; i < args.size(); i++) {
255 String argName = args.get(i);
256 needsVM = "vm".equals(argName);
257 super.visitInsn(Opcodes.DUP);
258 super.visitIntInsn(Opcodes.BIPUSH, i);
259 super.visitLdcInsn(argName);
260 super.visitInsn(Opcodes.AASTORE);
262 super.visitMethodInsn(Opcodes.INVOKESTATIC,
263 "org/apidesign/html/boot/spi/Fn", "define",
264 "(Ljava/lang/Class;Ljava/lang/String;[Ljava/lang/String;)Lorg/apidesign/html/boot/spi/Fn;"
266 super.visitInsn(Opcodes.DUP);
267 super.visitFieldInsn(
268 Opcodes.PUTSTATIC, FindInClass.this.name,
269 "$$fn$$" + name + "_" + found,
270 "Lorg/apidesign/html/boot/spi/Fn;"
274 super.visitLabel(ifNotNull);
277 if ((access & Opcodes.ACC_STATIC) == 0) {
279 super.visitIntInsn(Opcodes.ALOAD, 0);
282 super.visitInsn(Opcodes.ACONST_NULL);
285 super.visitIntInsn(Opcodes.SIPUSH, args.size());
286 super.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
288 class SV extends SignatureVisitor {
290 private boolean nowReturn;
291 private Type returnType;
293 private int loadIndex = offset;
300 public void visitBaseType(char descriptor) {
301 final Type t = Type.getType("" + descriptor);
306 FindInMethod.super.visitInsn(Opcodes.DUP);
307 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
308 FindInMethod.super.visitVarInsn(t.getOpcode(Opcodes.ILOAD), loadIndex++);
310 switch (descriptor) {
312 factory = "java/lang/Integer";
315 factory = "java/lang/Long";
319 factory = "java/lang/Short";
322 factory = "java/lang/Float";
325 factory = "java/lang/Double";
329 factory = "java/lang/Boolean";
332 factory = "java/lang/Character";
335 factory = "java/lang/Byte";
338 throw new IllegalStateException(t.toString());
340 FindInMethod.super.visitMethodInsn(Opcodes.INVOKESTATIC,
341 factory, "valueOf", "(" + descriptor + ")L" + factory + ";"
343 FindInMethod.super.visitInsn(Opcodes.AASTORE);
347 public SignatureVisitor visitArrayType() {
349 throw new IllegalStateException("Not supported yet");
352 return new SignatureWriter();
356 public void visitClassType(String name) {
358 returnType = Type.getObjectType(name);
365 public SignatureVisitor visitReturnType() {
370 private void loadObject() {
371 FindInMethod.super.visitInsn(Opcodes.DUP);
372 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, index++);
373 FindInMethod.super.visitVarInsn(Opcodes.ALOAD, loadIndex++);
374 FindInMethod.super.visitInsn(Opcodes.AASTORE);
379 SignatureReader sr = new SignatureReader(desc);
383 FindInMethod.super.visitInsn(Opcodes.DUP);
384 FindInMethod.super.visitIntInsn(Opcodes.SIPUSH, sv.index);
385 int lastSlash = FindInClass.this.name.lastIndexOf('/');
386 String jsCallbacks = FindInClass.this.name.substring(0, lastSlash + 1) + "$JsCallbacks$";
387 FindInMethod.super.visitFieldInsn(Opcodes.GETSTATIC, jsCallbacks, "VM", "L" + jsCallbacks + ";");
388 FindInMethod.super.visitMethodInsn(Opcodes.INVOKEVIRTUAL, jsCallbacks, "current", "()L" + jsCallbacks + ";");
389 FindInMethod.super.visitInsn(Opcodes.AASTORE);
392 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
393 "org/apidesign/html/boot/spi/Fn", "invoke", "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"
395 switch (sv.returnType.getSort()) {
397 super.visitInsn(Opcodes.RETURN);
401 super.visitTypeInsn(Opcodes.CHECKCAST, sv.returnType.getInternalName());
402 super.visitInsn(Opcodes.ARETURN);
405 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Boolean");
406 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
407 "java/lang/Boolean", "booleanValue", "()Z"
409 super.visitInsn(Opcodes.IRETURN);
412 super.visitTypeInsn(Opcodes.CHECKCAST, "java/lang/Number");
413 super.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
414 "java/lang/Number", sv.returnType.getClassName() + "Value", "()" + sv.returnType.getDescriptor()
416 super.visitInsn(sv.returnType.getOpcode(Opcodes.IRETURN));
422 public void visitEnd() {
425 if (generateBody()) {
427 super.visitMaxs(1, 0);
429 FindInClass.this.visitField(
430 Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC,
431 "$$fn$$" + name + "_" + found,
432 "Lorg/apidesign/html/boot/spi/Fn;",
438 private final class FindInAnno extends AnnotationVisitor {
440 private List<String> args = new ArrayList<String>();
442 private boolean javacall = false;
444 public FindInAnno() {
449 public void visit(String name, Object value) {
451 args.add((String) value);
454 if (name.equals("javacall")) { // NOI18N
455 javacall = (Boolean) value;
458 assert name.equals("body");
459 body = (String) value;
463 public AnnotationVisitor visitArray(String name) {
468 public void visitEnd() {
471 body = callback(body);
474 generateJSBody(args, body);
480 private final class LoadResource extends AnnotationVisitor {
482 public LoadResource() {
487 public void visit(String attrName, Object value) {
488 String relPath = (String) value;
489 if (relPath.startsWith("/")) {
490 loadScript(loader, relPath);
492 int last = name.lastIndexOf('/');
493 String fullPath = name.substring(0, last + 1) + relPath;
494 loadScript(loader, fullPath);
500 private static class ClassWriterEx extends ClassWriter {
502 private ClassLoader loader;
504 public ClassWriterEx(ClassLoader l, ClassReader classReader, int flags) {
505 super(classReader, flags);
510 protected String getCommonSuperClass(final String type1, final String type2) {
513 c = Class.forName(type1.replace('/', '.'), false, loader);
514 d = Class.forName(type2.replace('/', '.'), false, loader);
515 } catch (Exception e) {
516 throw new RuntimeException(e.toString());
518 if (c.isAssignableFrom(d)) {
521 if (d.isAssignableFrom(c)) {
524 if (c.isInterface() || d.isInterface()) {
525 return "java/lang/Object";
528 c = c.getSuperclass();
529 } while (!c.isAssignableFrom(d));
530 return c.getName().replace('.', '/');
535 static byte[] transform(ClassLoader loader, byte[] arr) {
536 ClassReader cr = new ClassReader(arr) {
537 // to allow us to compile with -profile compact1 on
538 // JDK8 while processing the class as JDK7, the highest
539 // class format asm 4.1 understands to
541 public short readShort(int index) {
542 short s = super.readShort(index);
543 if (index == 6 && s > Opcodes.V1_7) {
549 FindInClass tst = new FindInClass(loader, null);
552 ClassWriter w = new ClassWriterEx(loader, cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
553 FindInClass fic = new FindInClass(loader, w);
555 arr = w.toByteArray();
560 private static final class TrueFn extends Fn {
562 public Object invoke(Object thiz, Object... args) throws Exception {