import java.util.*; import java.util.zip.*; import java.util.List; import java.util.regex.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; import javax.swing.table.*; import java.io.*; import java.net.*; import java.lang.reflect.*; import java.lang.ref.*; import java.lang.management.*; import java.security.*; import java.security.spec.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import java.math.*; /** JavaX runner version 31 Changes to v31: -trying to cache unchanged programs TODO when making x32: change program ID in source */ public class main { public static void main(String[] args) throws Exception { throw new RuntimeException("placebo"); } } interface StringFunc { String get(String s); } class x30 implements Runnable { static final String version = "JavaX 31"; static final int subversion = 1; static final String javaxProgramID = "#1004305"; // If programs run longer than this, they might have their class files // deleted. We make it way longer for now. static int tempFileRetentionTime = 30*24; // hours static int maxConsoleChars = 1024*1024; static boolean verbose = false, translate = false, list = false, virtualizeTranslators = true; static String translateTo = null; static boolean preferCached = false, noID = false, noPrefetch = false, noAWT = false; static boolean safeOnly = false, safeTranslate = false, javacOnly = false, logOn = true; static boolean runMainInProcess = true, consoleOn = true, hasHelloMessage = false; static List mainTranslators = new ArrayList(); private static Map memSnippetCache = new HashMap(); private static int processesStarted, compilations; // snippet ID -> md5 private static HashMap prefetched = new HashMap(); private static File virtCache; // doesn't work yet private static Map> programCache = new HashMap>(); static boolean cacheTranslators = false; // this should work (caches transpiled translators) private static HashMap translationCache = new HashMap(); static boolean cacheTranspiledTranslators = true; // which snippets are available pre-transpiled server-side? private static Set hasTranspiledSet = new HashSet(); static boolean useServerTranspiled = true; static Object androidContext; static boolean android = isAndroid(); // We stick to 1.7 for now to support android. // Scripts like #1001155 might change to 1.6 static String javaTarget = System.getProperty("java.version").startsWith("1.6.") ? "1.6" : "1.7"; // Translators currently being translated (to detect recursions) private static Set translating = new HashSet(); static String lastOutput; static String[] fullArgs; private static Console console; static String javaCompilerOutput; static int systemOutPipeSize = 128*1024; // 128 K static int systemErrPipeSize = 4*1024; // 4 K static int systemInPipeSize = 4*1024; // 4 K public static void main(String[] args) { try { goMain(args); } catch (Throwable e) { e.printStackTrace(); } } static void goMain(String[] args) throws Exception { __javax = x30.class; // for hotwire if (args.length != 0 && args[0].equals("-v")) verbose = true; redirectSystemOutAndErr(); for (String arg : args) if (arg.equals("-noawt")) noAWT = true; if (consoleOn && console == null && !noAWT) tryToOpenConsole(args); String autoReport = loadTextFile(new File(userHome(), ".javax/auto-report-to-chat").getPath(), "").trim(); //print("autoReport=" + autoReport); if (!isChatServer(args) && autoReport.equals("1")) autoReportToChat(); if (!hasHelloMessage) { hasHelloMessage = true; //installHelloMessage(args.length == 0 ? "JavaX Start-Up VM" : "JavaX VM (" + smartJoin(args) + ")"); makeVMAndroid(); } File ioBaseDir = new File("."), inputDir = null, outputDir = null; String src = null; List programArgs = new ArrayList(); fullArgs = args; for (int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.equals("-version")) { showVersion(); System.exit(0); } if (arg.equals("-sysprop")) { showSystemProperties(); return; } if (arg.equals("-v") || arg.equals("-verbose")) verbose = true; else if (arg.equals("-finderror")) verbose = true; else if (arg.equals("-offline") || arg.equalsIgnoreCase("-prefercached")) preferCached = true; else if (arg.equals("-novirt")) virtualizeTranslators = false; else if (arg.equals("-safeonly")) safeOnly = true; else if (arg.equals("-safetranslate")) safeTranslate = true; else if (arg.equals("-noawt")) noAWT = true; else if (arg.equals("-noid")) noID = true; else if (arg.equals("-nocachetranspiled")) cacheTranspiledTranslators = false; else if (arg.equals("-javac")) javacOnly = true; else if (arg.equals("-localtranspile")) useServerTranspiled = false; else if (arg.equals("translate") && src == null) translate = true; else if (arg.equals("list") && src == null) { list = true; virtualizeTranslators = false; // so they are silenced } else if (arg.equals("run") && src == null) { // it's the default command anyway } else if (arg.startsWith("input=")) inputDir = new File(arg.substring(6)); else if (arg.startsWith("output=")) outputDir = new File(arg.substring(7)); else if (arg.equals("with")) mainTranslators.add(new String[] {args[++i], null}); else if (translate && arg.equals("to")) translateTo = args[++i]; else if (src == null) { //System.out.println("src=" + arg); src = arg; } else programArgs.add(arg); } cleanCache(); if (useServerTranspiled) noPrefetch = true; if (src == null) src = "."; // Might actually want to write to 2 disk caches (global/per program). if (virtualizeTranslators && !preferCached) virtCache = TempDirMaker_make(); if (inputDir != null) { ioBaseDir = TempDirMaker_make(); System.out.println("Taking input from: " + inputDir.getAbsolutePath()); System.out.println("Output is in: " + new File(ioBaseDir, "output").getAbsolutePath()); copyInput(inputDir, new File(ioBaseDir, "input")); } if (logOn) logStart(args); javaxmain(src, ioBaseDir, translate, list, programArgs.toArray(new String[programArgs.size()])); if (outputDir != null) { copyInput(new File(ioBaseDir, "output"), outputDir); System.out.println("Output copied to: " + outputDir.getAbsolutePath()); } if (verbose) { // print stats System.out.println("Processes started: " + processesStarted + ", compilations: " + compilations); } } public static void javaxmain(String src, File ioDir, boolean translate, boolean list, String[] args) throws Exception { String programID = isSnippetID(src) ? "" + parseSnippetID(src) : null; if (programID != null) System.err.println("JavaX TRANSLATE " + programID + " " + smartJoin(args)); List libraries = new ArrayList(); File X = transpileMain(src, libraries); if (verbose) print("After transpileMain: " + X); if (X == null) { showVersion(); if (fullArgs != null) { String[] nargs; if (fullArgs.length == 0) nargs = new String[] {"1000825"}; // swing-start else { // forward to search nargs = new String[fullArgs.length+1]; nargs[0] = "636"; // nargs[1] = "search-runnables"; System.arraycopy(fullArgs, 0, nargs, 1, fullArgs.length); } main(nargs); // Hopefully we get no infinite recursion :) return; } System.out.println("No main.java found, exiting"); return; } info.transpiledSrc = X; // list or run if (translate) { File to = X; if (translateTo != null) { StringBuilder buf = new StringBuilder(); for (File f : libraries) buf.append(f.getName()+"\n"); if (new File(translateTo).isDirectory()) { to = new File(translateTo, "main.java"); saveTextFile(new File(translateTo, "libraries.txt").getPath(), buf.toString()); } else { to = new File(translateTo); saveTextFile(new File(translateTo + "_libraries").getPath(), buf.toString()); } } if (to != X) copy(new File(X, "main.java"), to); System.out.println("Program translated to: " + to.getAbsolutePath()); } else if (list) System.out.println(loadTextFile(new File(X, "main.java").getPath(), null)); else { if (programID != null) System.err.println("JavaX RUN " + programID + " " + smartJoin(args)); System.err.println(); // Make empty line before actual program starts javax2(X, ioDir, false, runMainInProcess, libraries, args, null, programID, info); System.out.println("[main done]"); // cleanup reportToChat thread if (reportToChat_q != null) { if (customSystemOut != null) Thread.sleep(1000); // delay to finish autoReportToChat. Yes it's hacky. if (verbose) System.out.println("Closing reportToChat queue"); reportToChat_q.done(); } } } static File transpileMain(String src, List libraries) throws Exception { File srcDir = null; boolean isTranspiled = false; if (isSnippetID(src)) { String transpiledSrc = getTranspilationFromBossBot(parseSnippetID(src)); if (transpiledSrc != null) { int i = transpiledSrc.indexOf('\n'); String libs = transpiledSrc.substring(0, Math.max(0, i)); transpiledSrc = transpiledSrc.substring(i+1); if (!transpiledSrc.isEmpty()) { srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc); isTranspiled = true; Matcher m = Pattern.compile("\\d+").matcher(libs); while (m.find()) { String libid = m.group(); File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(libid)); loadLibrary(libid, libraries, libraryFile); } } } if (srcDir == null) { prefetch(src); long id = parseSnippetID(src); prefetched.remove(id); // hackfix to ensure transpiled main program is found. srcDir = loadSnippetAsMainJava(src); if (verbose) System.err.println("hasTranspiledSet: " + hasTranspiledSet); if (hasTranspiledSet.contains(id) && useServerTranspiled) { //System.err.println("Trying pretranspiled main program: #" + id); transpiledSrc = getServerTranspiled("#" + id); int i = transpiledSrc.indexOf('\n'); String libs = transpiledSrc.substring(0, Math.max(0, i)); transpiledSrc = transpiledSrc.substring(i+1); if (!transpiledSrc.isEmpty()) { srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc); isTranspiled = true; //translationCache.put(id, new Object[] {srcDir, libraries}); Matcher m = Pattern.compile("\\d+").matcher(libs); while (m.find()) { String libid = m.group(); File libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(libid)); loadLibrary(libid, libraries, libraryFile); } } } } } else { srcDir = new File(src); // if the argument is a file, it is assumed to be main.java if (srcDir.isFile()) { srcDir = TempDirMaker_make(); copy(new File(src), new File(srcDir, "main.java")); } if (!new File(srcDir, "main.java").exists()) return null; } // translate File X = srcDir; if (!isTranspiled) { X = topLevelTranslate(X, libraries); System.err.println("Translated " + src); // save prefetch data if (isSnippetID(src)) savePrefetchData(src); } return X; } private static void prefetch(String mainSnippetID) throws IOException { if (noPrefetch) return; long mainID = parseSnippetID(mainSnippetID); String s = mainID + " " + loadTextFile(new File(userHome(), ".tinybrain/prefetch/" + mainID + ".txt").getPath(), ""); String[] ids = s.trim().split(" "); if (ids.length > 1) { String url = "http://tinybrain.de:8080/tb-int/prefetch.php?ids=" + URLEncoder.encode(s, "UTF-8"); String data = loadPage(new URL(url)); String[] split = data.split(" "); if (split.length == ids.length) for (int i = 0; i < ids.length; i++) prefetched.put(parseSnippetID(ids[i]), split[i]); } } static String userHome() { if (android) return ((File) call(androidContext, "getFilesDir")).getAbsolutePath(); else return System.getProperty("user.home"); } private static void savePrefetchData(String mainSnippetID) throws IOException { List ids = new ArrayList(); long mainID = parseSnippetID(mainSnippetID); for (long id : memSnippetCache.keySet()) if (id != mainID) ids.add(String.valueOf(id)); saveTextFile(new File(userHome(),".tinybrain/prefetch/" + mainID + ".txt").getPath(), join(" ", ids)); } static File topLevelTranslate(File srcDir, List libraries_out) throws Exception { File X = srcDir; X = applyTranslators(X, mainTranslators, libraries_out); // translators supplied on command line (unusual) // actual inner translation of the JavaX source X = defaultTranslate(X, libraries_out); return X; } private static File defaultTranslate(File x, List libraries_out) throws Exception { x = luaPrintToJavaPrint(x); x = repeatAutoTranslate(x, libraries_out); return x; } private static File repeatAutoTranslate(File x, List libraries_out) throws Exception { List postTranslators = new ArrayList(); while (true) { String main = loadTextFile(new File(x, "main.java").getPath(), null); List lines = toLines(main); List t = findPostTranslators(lines); postTranslators.addAll(t); if (!t.isEmpty()) { main = fromLines(lines); x = TempDirMaker_make(); saveTextFile(new File(x, "main.java").getPath(), main); } File y = autoTranslate(x, libraries_out); if (y == x) break; x = y; } x = applyTranslators(x, postTranslators, libraries_out); return x; } private static File autoTranslate(File x, List libraries_out) throws Exception { String main = loadTextFile(new File(x, "main.java").getPath(), null); List lines = toLines(main); List translators = findTranslators(lines); if (translators.isEmpty()) return x; main = fromLines(lines); File newDir = TempDirMaker_make(); saveTextFile(new File(newDir, "main.java").getPath(), main); return applyTranslators(newDir, translators, libraries_out); } static List findTranslators(List lines) { List translators = new ArrayList(); Pattern pattern = Pattern.compile("^!([0-9# \t]+)"); Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)"); for (ListIterator iterator = lines.listIterator(); iterator.hasNext(); ) { String line = iterator.next(); line = line.trim(); Matcher matcher = pattern.matcher(line); if (matcher.find()) { String[] t = matcher.group(1).split("[ \t]+"); String rest = line.substring(matcher.end()); String arg = null; if (t.length == 1) { Matcher mArgs = pArgs.matcher(rest); if (mArgs.find()) arg = mArgs.group(1); } for (String transi : t) translators.add(new String[]{transi, arg}); iterator.remove(); } } return translators; } static List findPostTranslators(List lines) { List translators = new ArrayList(); Pattern pattern = Pattern.compile("^!post\\s*([0-9# \t]+)"); Pattern pArgs = Pattern.compile("^\\s*\\((.*)\\)"); for (ListIterator iterator = lines.listIterator(); iterator.hasNext(); ) { String line = iterator.next(); line = line.trim(); Matcher matcher = pattern.matcher(line); if (matcher.find()) { String[] t = matcher.group(1).split("[ \t]+"); String rest = line.substring(matcher.end()); String arg = null; if (t.length == 1) { Matcher mArgs = pArgs.matcher(rest); if (mArgs.find()) arg = mArgs.group(1); } for (String transi : t) translators.add(new String[]{transi, arg}); iterator.remove(); } } return translators; } public static List toLines(String s) { List lines = new ArrayList(); int start = 0; while (true) { int i = toLines_nextLineBreak(s, start); if (i < 0) { if (s.length() > start) lines.add(s.substring(start)); break; } lines.add(s.substring(start, i)); if (s.charAt(i) == '\r' && i+1 < s.length() && s.charAt(i+1) == '\n') i += 2; else ++i; start = i; } return lines; } private static int toLines_nextLineBreak(String s, int start) { for (int i = start; i < s.length(); i++) { char c = s.charAt(i); if (c == '\r' || c == '\n') return i; } return -1; } public static String fromLines(List lines) { StringBuilder buf = new StringBuilder(); for (String line : lines) { buf.append(line).append('\n'); } return buf.toString(); } private static File applyTranslators(File x, List translators, List libraries_out) throws Exception { for (String[] translator : translators) x = applyTranslator(x, translator[0], translator[1], libraries_out); return x; } // also takes a library private static File applyTranslator(File x, String translator, String arg, List libraries_out) throws Exception { if (verbose) System.out.println("Using translator " + translator + " on sources in " + x.getPath()); File newDir = runTranslatorOnInput(translator, null, arg, x, !verbose, libraries_out); if (!new File(newDir, "main.java").exists()) { throw new Exception("Translator " + translator + " did not generate main.java"); // TODO: show translator output } if (verbose) System.out.println("Translated with " + translator + " from " + x.getPath() + " to " + newDir.getPath()); x = newDir; return x; } private static File luaPrintToJavaPrint(File x) throws IOException { File newDir = TempDirMaker_make(); String code = loadTextFile(new File(x, "main.java").getPath(), null); code = luaPrintToJavaPrint(code); saveTextFile(new File(newDir, "main.java").getPath(), code); return newDir; } public static String luaPrintToJavaPrint(String code) { return ("\n" + code).replaceAll( "(\n\\s*)print (\".*\")", "$1System.out.println($2);").substring(1); } public static File loadSnippetAsMainJava(String snippetID) throws IOException { checkProgramSafety(snippetID); File srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippet(snippetID)); return srcDir; } public static File loadSnippetAsMainJavaVerified(String snippetID, String hash) throws IOException { checkProgramSafety(snippetID); File srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), loadSnippetVerified(snippetID, hash)); return srcDir; } @SuppressWarnings( "unchecked" ) /** returns output dir */ private static File runTranslatorOnInput(String snippetID, String hash, String arg, File input, boolean silent, List libraries_out) throws Exception { if (safeTranslate) checkProgramSafetyImpl(snippetID); long id = parseSnippetID(snippetID); // It's a library, not a translator. File libraryFile = DiskSnippetCache_getLibrary(id); if (verbose) System.out.println("Library file for " + id + ": " + libraryFile); if (libraryFile != null) { loadLibrary(snippetID, libraries_out, libraryFile); return input; } String[] args = arg != null ? new String[]{arg} : new String[0]; File srcDir = hash == null ? loadSnippetAsMainJava(snippetID) : loadSnippetAsMainJavaVerified(snippetID, hash); long mainJavaSize = new File(srcDir, "main.java").length(); if (verbose) System.out.println(snippetID + ": length = " + mainJavaSize); if (mainJavaSize == 0) { // no text in snippet? assume it's a library loadLibrary(snippetID, libraries_out, libraryFile); return input; } List libraries = new ArrayList(); Object[] cached = translationCache.get(id); if (cached != null) { //System.err.println("Taking translator " + snippetID + " from cache!"); srcDir = (File) cached[0]; libraries = (List) cached[1]; } else if (hasTranspiledSet.contains(id) && useServerTranspiled) { System.err.println("Trying pretranspiled translator: #" + snippetID); String transpiledSrc = getServerTranspiled(snippetID); transpiledSrc = transpiledSrc.substring(transpiledSrc.indexOf('\n')+1); // TODO: check for libraries if (!transpiledSrc.isEmpty()) { srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), transpiledSrc); translationCache.put(id, cached = new Object[] {srcDir, libraries}); } } File ioBaseDir = TempDirMaker_make(); /*Class mainClass = programCache.get("" + parseSnippetID(snippetID)); if (mainClass != null) return runCached(ioBaseDir, input, args);*/ // Doesn't work yet because virtualized directories are hardcoded in translator... if (cached == null) { System.err.println("Translating translator #" + id); if (translating.contains(id)) throw new RuntimeException("Recursive translator reference chain: " + structure(translating)); translating.add(id); try { srcDir = defaultTranslate(srcDir, libraries); } finally { translating.remove(id); } System.err.println("Translated translator #" + id); translationCache.put(id, new Object[]{srcDir, libraries}); } boolean runInProcess = false; if (virtualizeTranslators) { if (verbose) System.out.println("Virtualizing translator"); // TODO: don't virtualize class _javax (as included in, say, #636) //srcDir = applyTranslator(srcDir, "#2000351"); // I/O-virtualize the translator // that doesn't work because it recurses infinitely... // So we do it right here: String s = loadTextFile(new File(srcDir, "main.java").getPath(), null); s = s.replaceAll("new\\s+File\\(", "virtual.newFile("); s = s.replaceAll("new\\s+FileInputStream\\(", "virtual.newFileInputStream("); s = s.replaceAll("new\\s+FileOutputStream\\(", "virtual.newFileOutputStream("); s += "\n\n" + loadSnippet("#2000355"); // load class virtual // forward snippet cache (virtualized one) File dir = virtCache != null ? virtCache : DiskSnippetCache_dir; s = s.replace("static File DiskSnippetCache_dir" + ";", "static File DiskSnippetCache_dir " + "= new File(" + javaQuote(dir.getAbsolutePath()) + ");"); // extra + is necessary for Dumb TinyBrain :) s = s.replace("static boolean preferCached = false;", "static boolean preferCached = true;"); if (verbose) { System.out.println("==BEGIN VIRTUALIZED TRANSLATOR=="); System.out.println(s); System.out.println("==END VIRTUALIZED TRANSLATOR=="); } srcDir = TempDirMaker_make(); saveTextFile(new File(srcDir, "main.java").getPath(), s); // TODO: silence translator also runInProcess = true; } return runJavaX(ioBaseDir, srcDir, input, silent, runInProcess, libraries, args, cacheTranslators ? "" + id : null, "" + id); } static void checkProgramSafety(String snippetID) throws IOException { if (!safeOnly) return; checkProgramSafetyImpl(snippetID); } static void checkProgramSafetyImpl(String snippetID) throws IOException { URL url = new URL("http://tinybrain.de:8080/tb-int/is-javax-safe.php?id=" + parseSnippetID(snippetID)); String text = loadPage(url); if (!text.startsWith("{\"safe\":\"1\"}")) throw new RuntimeException("Program not safe: #" + parseSnippetID(snippetID)); } static void loadLibrary(String snippetID, List libraries_out, File libraryFile) throws IOException { if (verbose) System.out.println("Assuming " + snippetID + " is a library."); if (libraryFile == null) { byte[] data = loadDataSnippetImpl(snippetID); DiskSnippetCache_putLibrary(parseSnippetID(snippetID), data); libraryFile = DiskSnippetCache_getLibrary(parseSnippetID(snippetID)); } if (!libraries_out.contains(libraryFile)) libraries_out.add(libraryFile); } /** returns output dir */ private static File runJavaX(File ioBaseDir, File originalSrcDir, File originalInput, boolean silent, boolean runInProcess, List libraries, String[] args, String cacheAs, String programID) throws Exception { File srcDir = new File(ioBaseDir, "src"); File inputDir = new File(ioBaseDir, "input"); File outputDir = new File(ioBaseDir, "output"); copyInput(originalSrcDir, srcDir); copyInput(originalInput, inputDir); javax2(srcDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID, null); return outputDir; } private static void copyInput(File src, File dst) throws IOException { copyDirectory(src, dst); } public static boolean hasFile(File inputDir, String name) { return new File(inputDir, name).exists(); } public static void copyDirectory(File src, File dst) throws IOException { if (verbose) System.out.println("Copying " + src.getAbsolutePath() + " to " + dst.getAbsolutePath()); dst.mkdirs(); File[] files = src.listFiles(); if (files == null) return; for (File file : files) { File dst1 = new File(dst, file.getName()); if (file.isDirectory()) copyDirectory(file, dst1); else { if (verbose) System.out.println("Copying " + file.getAbsolutePath() + " to " + dst1.getAbsolutePath()); copy(file, dst1); } } } /** Quickly copy a file without a progress bar or any other fancy GUI... :) */ public static void copy(File src, File dest) throws IOException { FileInputStream inputStream = newFileInputStream(src); FileOutputStream outputStream = newFileOutputStream(dest); try { copy(inputStream, outputStream); inputStream.close(); } finally { outputStream.close(); } } private static FileInputStream newFileInputStream(File f) throws FileNotFoundException { /*if (androidContext != null) return (FileInputStream) call(androidContext, "openFileInput", f.getPath()); else*/ return new // line break for Dumb TinyBrain :) FileInputStream(f); } private static FileOutputStream newFileOutputStream(File f) throws FileNotFoundException { /*if (androidContext != null) return (FileOutputStream) call(androidContext, "openFileOutput", f.getPath(), 0); else*/ return new // line break for Dumb TinyBrain :) FileOutputStream(f); } public static void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[65536]; while (true) { int n = in.read(buf); if (n <= 0) return; out.write(buf, 0, n); } } /** writes safely (to temp file, then rename) */ public static void saveTextFile(String fileName, String contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName)); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, charsetForTextFiles); PrintWriter printWriter = new PrintWriter(outputStreamWriter); printWriter.print(contents); printWriter.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } /** writes safely (to temp file, then rename) */ public static void saveBinaryFile(String fileName, byte[] contents) throws IOException { File file = new File(fileName); File parentFile = file.getParentFile(); if (parentFile != null) parentFile.mkdirs(); String tempFileName = fileName + "_temp"; FileOutputStream fileOutputStream = newFileOutputStream(new File(tempFileName)); fileOutputStream.write(contents); fileOutputStream.close(); if (file.exists() && !file.delete()) throw new IOException("Can't delete " + fileName); if (!new File(tempFileName).renameTo(file)) throw new IOException("Can't rename " + tempFileName + " to " + fileName); } public static String loadTextFile(String fileName) { try { return loadTextFile(fileName, null); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadTextFile(String fileName, String defaultContents) throws IOException { if (!new File(fileName).exists()) return defaultContents; FileInputStream fileInputStream = new FileInputStream(fileName); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); return loadTextFile(inputStreamReader); } public static String loadTextFile(File fileName) { try { return loadTextFile(fileName, null); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadTextFile(File fileName, String defaultContents) throws IOException { try { return loadTextFile(fileName.getPath(), defaultContents); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadTextFile(Reader reader) throws IOException { StringBuilder builder = new StringBuilder(); try { char[] buffer = new char[1024]; int n; while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n); } finally { reader.close(); } return builder.toString(); } // loadTextFile static File DiskSnippetCache_dir; public static void initDiskSnippetCache(File dir) { DiskSnippetCache_dir = dir; dir.mkdirs(); } // Data files are immutable, use centralized cache public static synchronized File DiskSnippetCache_getLibrary(long snippetID) throws IOException { File file = new File(getGlobalCache(), "data_" + snippetID + ".jar"); if (verbose) System.out.println("Checking data cache: " + file.getPath()); return file.exists() ? file : null; } public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException { return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null); } private static File DiskSnippetCache_getFile(long snippetID) { return new File(DiskSnippetCache_dir, "" + snippetID); } public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException { saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet); } public static synchronized void DiskSnippetCache_putLibrary(long snippetID, byte[] data) throws IOException { saveBinaryFile(new File(getGlobalCache(), "data_" + snippetID).getPath() + ".jar", data); } public static File DiskSnippetCache_getDir() { return DiskSnippetCache_dir; } public static void initSnippetCache() { if (DiskSnippetCache_dir == null) initDiskSnippetCache(getGlobalCache()); } private static File getGlobalCache() { File file = new File(userHome(), ".tinybrain/snippet-cache"); file.mkdirs(); return file; } public static String loadSnippetVerified(String snippetID, String hash) throws IOException { String text = loadSnippet(snippetID); String realHash = getHash(text.getBytes("UTF-8")); if (!realHash.equals(hash)) { String msg; if (hash.isEmpty()) msg = "Here's your hash for " + snippetID + ", please put in your program: " + realHash; else msg = "Hash mismatch for " + snippetID + ": " + realHash + " (new) vs " + hash + " - has tinybrain.de been hacked??"; throw new RuntimeException(msg); } return text; } public static String getHash(byte[] data) { return bytesToHex(getFullFingerprint(data)); } public static byte[] getFullFingerprint(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static String bytesToHex(byte[] bytes) { return bytesToHex(bytes, 0, bytes.length); } public static String bytesToHex(byte[] bytes, int ofs, int len) { StringBuilder stringBuilder = new StringBuilder(len*2); for (int i = 0; i < len; i++) { String s = "0" + Integer.toHexString(bytes[ofs+i]); stringBuilder.append(s.substring(s.length()-2, s.length())); } return stringBuilder.toString(); } public static String loadSnippet(String snippetID) throws IOException { return loadSnippet(parseSnippetID(snippetID)); } public static long parseSnippetID(String snippetID) { return Long.parseLong(shortenSnippetID(snippetID)); } private static String shortenSnippetID(String snippetID) { if (snippetID.startsWith("#")) snippetID = snippetID.substring(1); String httpBlaBla = "http://tinybrain.de/"; if (snippetID.startsWith(httpBlaBla)) snippetID = snippetID.substring(httpBlaBla.length()); return snippetID; } public static boolean isSnippetID(String snippetID) { snippetID = shortenSnippetID(snippetID); return isInteger(snippetID) && Long.parseLong(snippetID) != 0; } public static boolean isInteger(String s) { return Pattern.matches("\\-?\\d+", s); } static String getTranspilationFromBossBot(long snippetID) { return boss(format3("get transpilation for *", snippetID)); } // This is DIFFERENT from the std library loadSnippet // (this is only for code!) public static String loadSnippet(long snippetID) throws IOException { String text = getSnippetFromBossBot(snippetID); if (text != null) return text; text = memSnippetCache.get(snippetID); if (text != null) { if (verbose) System.out.println("Getting " + snippetID + " from mem cache"); return text; } initSnippetCache(); text = DiskSnippetCache_get(snippetID); if (preferCached && text != null) { if (verbose) System.out.println("Getting " + snippetID + " from disk cache (preferCached)"); return text; } String md5 = text != null ? md5(text) : "-"; if (text != null) { String hash = prefetched.get(snippetID); if (hash != null) { if (md5.equals(hash)) { memSnippetCache.put(snippetID, text); if (verbose) System.out.println("Getting " + snippetID + " from prefetched"); return text; } else prefetched.remove(snippetID); // (maybe this is not necessary) } } try { /*URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID); text = loadPage(url);*/ String theURL = "http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&getmd5=1&utf8=1&usetranspiled=1"; if (text != null) { //System.err.println("MD5: " + md5); theURL += "&md5=" + md5; } URL url = new URL(theURL); String page = loadPage(url); // parse & drop transpilation flag available line int i = page.indexOf('\n'); boolean hasTranspiled = page.substring(0, i).trim().equals("1"); if (hasTranspiled) hasTranspiledSet.add(snippetID); else hasTranspiledSet.remove(snippetID); page = page.substring(i+1); if (page.startsWith("==*#*==")) { // same, keep text //System.err.println("Snippet unchanged, keeping."); } else { // drop md5 line i = page.indexOf('\n'); String hash = page.substring(0, i).trim(); text = page.substring(i+1); String myHash = md5(text); if (myHash.equals(hash)) { //System.err.println("Hash match: " + hash); } else System.err.println("Hash mismatch"); } } catch (Exception e) { e.printStackTrace(); throw new IOException("Snippet #" + snippetID + " not found or not public"); } memSnippetCache.put(snippetID, text); try { initSnippetCache(); DiskSnippetCache_put(snippetID, text); } catch (IOException e) { System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")"); } return text; } private static String md5(String text) { try { return bytesToHex(md5impl(text.getBytes("UTF-8"))); // maybe different than the way PHP does it... } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } public static byte[] md5impl(byte[] data) { try { return MessageDigest.getInstance("MD5").digest(data); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public static byte[] loadBinaryPage(URLConnection con) throws IOException { setHeaders(con); return loadBinaryPage_noHeaders(con); } private static byte[] loadBinaryPage_noHeaders(URLConnection con) throws IOException { ByteArrayOutputStream buf = new ByteArrayOutputStream(); InputStream inputStream = con.getInputStream(); int n = 0; while (true) { int ch = inputStream.read(); if (ch < 0) break; buf.write(ch); if (++n % 100000 == 0) System.err.println(" " + n + " bytes loaded."); } inputStream.close(); return buf.toByteArray(); } private static void setHeaders(URLConnection con) throws IOException { String computerID = getComputerID(); if (computerID != null) con.setRequestProperty("X-ComputerID", computerID); } public static String guessCharset(String contentType) { Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*"); Matcher m = p.matcher(contentType); /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ return m.matches() ? m.group(1) : "ISO-8859-1"; } /** runs a transpiled set of sources */ public static void javax2(File srcDir, File ioBaseDir, boolean silent, boolean runInProcess, List libraries, String[] args, String cacheAs, String programID, Info info) throws Exception { if (android) { // TODO: no translator virtualization? huh? javax2android(srcDir, args, programID); } else { File classesDir = TempDirMaker_make(); String javacOutput = compileJava(srcDir, libraries, classesDir); // run if (verbose) System.out.println("Running program (" + srcDir.getAbsolutePath() + ") on io dir " + ioBaseDir.getAbsolutePath() + (runInProcess ? "[in-process]" : "") + "\n"); runProgram(javacOutput, classesDir, ioBaseDir, silent, runInProcess, libraries, args, cacheAs, programID, info); } } static Class loadx2android(File srcDir, String programID) throws Exception { // TODO: optimize if it's a loaded snippet anyway URL url = new URL("http://tinybrain.de:8080/dexcompile.php"); URLConnection conn = url.openConnection(); String postData = "src=" + URLEncoder.encode(loadTextFile(new File(srcDir, "main.java").getPath(), null), "UTF-8"); byte[] dexData = doPostBinary(postData, conn); if (!isDex(dexData)) throw new RuntimeException("Dex generation error: " + dexData.length + " bytes - " + new String(dexData, "UTF-8")); System.out.println("Dex loaded: " + dexData.length + "b"); File dexDir = TempDirMaker_make(); File dexFile = new File(dexDir, System.currentTimeMillis() + ".dex"); File dexOutputDir = TempDirMaker_make(); System.out.println("Saving dex to: " + dexDir.getAbsolutePath()); try { saveBinaryFile(dexFile.getPath(), dexData); } catch (Throwable e) { System.out.println("Whoa!"); throw new RuntimeException(e); } System.out.println("Getting parent class loader."); ClassLoader parentClassLoader = //ClassLoader.getSystemClassLoader(); // does not find support jar //getClass().getClassLoader(); // Let's try this... x30.class.getClassLoader().getParent(); // XXX ! //System.out.println("Making DexClassLoader."); //DexClassLoader classLoader = new DexClassLoader(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null, // parentClassLoader); Class dcl = Class.forName("dalvik.system.DexClassLoader"); Object classLoader = dcl.getConstructors()[0].newInstance(dexFile.getAbsolutePath(), dexOutputDir.getAbsolutePath(), null, parentClassLoader); //System.out.println("Loading main class."); //Class theClass = classLoader.loadClass(mainClassName); Class theClass = (Class) call(classLoader, "loadClass", "main"); //System.out.println("Main class loaded."); try { set(theClass, "androidContext", androidContext); } catch (Throwable e) {} setVars(theClass, programID); addInstance(programID, theClass); return theClass; } static void addInstance(String programID, Class mainClass) { programID = "" + parseSnippetID(programID); instances.put(programID, new WeakReference(mainClass)); } static Class getInstance(String programID) { programID = "" + parseSnippetID(programID); List> l = instances.get(programID); for (WeakReference c : l) { Class theClass = c.get(); // TODO: shorten the list if (theClass != null) return theClass; } return null; } static MultiMap> instances = new MultiMap>(); static class MultiMap { Map> data = new HashMap>(); MultiMap() {} MultiMap(boolean useTreeMap) { if (useTreeMap) data = new TreeMap(); } MultiMap(MultiMap map) { putAll(map); } synchronized void put(A key, B value) { List list = data.get(key); if (list == null) data.put(key, list = new ArrayList()); list.add(value); } synchronized void addAll(A key, Collection values) { putAll(key, values); } synchronized void addAllIfNotThere(A key, Collection values) { for (B value : values) setPut(key, value); } synchronized void setPut(A key, B value) { if (!containsPair(key, value)) put(key, value); } synchronized boolean containsPair(A key, B value) { return get(key).contains(value); } synchronized void putAll(A key, Collection values) { for (B value : values) put(key, value); } synchronized void removeAll(A key, Collection values) { for (B value : values) remove(key, value); } synchronized List get(A key) { List list = data.get(key); return list == null ? Collections. emptyList() : list; } // returns actual mutable live list // creates the list if not there synchronized List getActual(A key) { List list = data.get(key); if (list == null) data.put(key, list = litlist()); return list; } synchronized void clean(A key) { List list = data.get(key); if (list != null && list.isEmpty()) data.remove(key); } synchronized Set keySet() { return data.keySet(); } synchronized Set keys() { return data.keySet(); } synchronized void remove(A key) { data.remove(key); } synchronized void remove(A key, B value) { List list = data.get(key); if (list != null) { list.remove(value); if (list.isEmpty()) data.remove(key); } } synchronized void clear() { data.clear(); } synchronized boolean containsKey(A key) { return data.containsKey(key); } synchronized B getFirst(A key) { List list = get(key); return list.isEmpty() ? null : list.get(0); } synchronized void putAll(MultiMap map) { for (A key : map.keySet()) putAll(key, map.get(key)); } // note: expensive operation synchronized int size() { int n = 0; for (List l : data.values()) n += l(l); return n; } // expensive operation synchronized List reverseGet(B b) { List l = new ArrayList(); for (A key : data.keySet()) if (data.get(key).contains(b)) l.add(key); return l; } } // MultiMap static void javax2android(File srcDir, String[] args, String programID) throws Exception { Class theClass = loadx2android(srcDir, programID); Method main = null; try { main = call_findStaticMethod(theClass, "main", new Object[]{androidContext}, false); } catch (RuntimeException e) { } //System.out.println("main method for " + androidContext + " of " + theClass + ": " + main); if (main != null) { // old style main program that returns a View // TODO: maybe allow programs without main method, although it doesn't seem to make sense here really (Android main program) System.out.println("Calling main (old-style)"); Object view = main.invoke(null, androidContext); System.out.println("Calling setContentView with " + view); call(Class.forName("main"), "setContentViewInUIThread", view); //call(androidContext, "setContentView", view); System.out.println("Done."); } else { System.out.println("New-style main method running.\n\n====\n"); runMainMethod(args, theClass); } } static byte[] DEX_FILE_MAGIC = { 0x64, 0x65, 0x78, 0x0a, 0x30, 0x33, 0x35, 0x00 }; static boolean isDex(byte[] dexData) { if (dexData.length < DEX_FILE_MAGIC.length) return false; for (int i = 0; i < DEX_FILE_MAGIC.length; i++) if (dexData[i] != DEX_FILE_MAGIC[i]) return false; return true; } static byte[] doPostBinary(String urlParameters, URLConnection conn) throws IOException { // connect and do POST setHeaders(conn); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); byte[] contents = loadBinaryPage_noHeaders(conn); writer.close(); return contents; } static String compileJava(File srcDir, List libraries, File classesDir) throws IOException { javaCompilerOutput = null; ++compilations; // collect sources List sources = new ArrayList(); if (verbose) System.out.println("Scanning for sources in " + srcDir.getPath()); scanForSources(srcDir, sources, true); if (sources.isEmpty()) throw new IOException("No sources found"); // compile File optionsFile = File.createTempFile("javax", ""); if (verbose) System.out.println("Compiling " + sources.size() + " source(s) to " + classesDir.getPath()); if (verbose) System.out.println("Libraries: " + libraries); String options = "-d " + bashQuote(classesDir.getPath()); writeOptions(sources, libraries, optionsFile, options); classesDir.mkdirs(); return invokeJavaCompiler(optionsFile); } private static void runProgram(String javacOutput, File classesDir, File ioBaseDir, boolean silent, boolean runInProcess, List libraries, String[] args, String cacheAs, String programID, Info info) throws Exception { // print javac output if compile failed and it hasn't been printed yet if (info != null) { info.programID = programID; info.programArgs = args; } boolean didNotCompile = !didCompile(classesDir); if (verbose || didNotCompile) System.out.println(javacOutput); if (didNotCompile) return; if (runInProcess || (ioBaseDir.getAbsolutePath().equals(new File(".").getAbsolutePath()) && !silent)) { runProgramQuick(classesDir, libraries, args, cacheAs, programID, info, ioBaseDir); return; } boolean echoOK = false; // TODO: add libraries to class path String bashCmd = "(cd " + bashQuote(ioBaseDir.getAbsolutePath()) + " && (java -cp " + bashQuote(classesDir.getAbsolutePath()) + " main" + (echoOK ? "; echo ok" : "") + "))"; if (verbose) System.out.println(bashCmd); String output = backtick(bashCmd); lastOutput = output; if (verbose || !silent) System.out.println(output); } static boolean didCompile(File classesDir) { return hasFile(classesDir, "main.class"); } private static void runProgramQuick(File classesDir, List libraries, String[] args, String cacheAs, String programID, Info info, File ioBaseDir) throws Exception { // make class loader JavaXClassLoader classLoader = new JavaXClassLoader(concatLists(ll(classesDir), libraries)); // load JavaX main class Class mainClass = classLoader.loadClass("main"); if (info != null) { info.mainClass = mainClass; if (info.transpiledSrc != null) registerSourceCode(mainClass, loadTextFile(new File(info.transpiledSrc, "main.java"))); } if (cacheAs != null) programCache.put(cacheAs, mainClass); // record injection final PaA paa = new PaA(programID, args); paa.injectionID = randomID(8); paa.mainClass = mainClass; addInjection(paa); // change baseDir try { //print("Changing base dir to " + ioBaseDir.getAbsolutePath()); Class virtual = mainClass.getClassLoader().loadClass("virtual"); set(virtual, "virtual_baseDir", ioBaseDir.getAbsolutePath()); } catch (Throwable e) { /* whatever */ } setVars(mainClass, programID); addInstance(programID, mainClass); try { runMainMethod(args, mainClass); } catch (Exception e) { paa.exception = e; throw e; } finally { paa.mainDone = true; } } static void setVars(Class theClass, String programID) { try { set(theClass, "programID", programID); } catch (Throwable e) {} try { set(theClass, "__javax", x30.class); } catch (Throwable e) {} } static void runMainMethod(String[] args, Class mainClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { callMain(mainClass, args); } static String invokeJavaCompiler(File optionsFile) throws IOException { String output; if (hasEcj() && !javacOnly) output = invokeEcj(optionsFile); else output = invokeJavac(optionsFile); if (verbose) System.out.println(output); return output; } private static boolean hasEcj() { try { Class.forName("org.eclipse.jdt.internal.compiler.batch.Main"); return true; } catch (ClassNotFoundException e) { return false; } } // TODO: fix UTF-8 here too private static String invokeJavac(File optionsFile) throws IOException { String output; output = backtick("javac " + bashQuote("@" + optionsFile.getPath())); javaCompilerOutput = output; if (exitValue != 0) { System.out.println(output); throw new RuntimeException("javac returned errors."); } return output; } // throws ClassNotFoundException if ecj is not in classpath static String invokeEcj(File optionsFile) { try { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); // add more eclipse options in the line below String[] args = { "-source", javaTarget, "-target", javaTarget, "-nowarn", "-encoding", "UTF-8", "@" + optionsFile.getPath() }; if (verbose) print("ECJ options: " + structure(args)); Class ecjClass = Class.forName("org.eclipse.jdt.internal.compiler.batch.Main"); Object main = newInstance(ecjClass, printWriter, printWriter, false); call(main, "compile", new Object[]{args}); int errors = (Integer) get(main, "globalErrorsCount"); String output = writer.toString(); javaCompilerOutput = output; if (errors != 0) { System.out.println(output); throw new RuntimeException("Java compiler returned errors."); } return output; } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } static Object newInstance(Class c, Object... args) { try { Constructor m = findConstructor(c, args); m.setAccessible(true); return m.newInstance(args); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Constructor findConstructor(Class c, Object... args) { for (Constructor m : c.getDeclaredConstructors()) { if (!checkArgs(m.getParameterTypes(), args, verbose)) continue; return m; } throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName()); } static boolean checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } private static void writeOptions(List sources, List libraries, File optionsFile, String moreOptions) throws IOException { FileWriter writer = new FileWriter(optionsFile); for (File source : sources) writer.write(bashQuote(source.getPath()) + " "); if (!libraries.isEmpty()) { List cp = new ArrayList(); for (File lib : libraries) cp.add(lib.getAbsolutePath()); writer.write("-cp " + bashQuote(join(File.pathSeparator, cp)) + " "); } writer.write(moreOptions); writer.close(); } static void scanForSources(File source, List sources, boolean topLevel) { if (source.isFile() && source.getName().endsWith(".java")) sources.add(source); else if (source.isDirectory() && !isSkippedDirectoryName(source.getName(), topLevel)) { File[] files = source.listFiles(); for (File file : files) scanForSources(file, sources, false); } } private static boolean isSkippedDirectoryName(String name, boolean topLevel) { if (topLevel) return false; // input or output ok as highest directory (intentionally specified by user, not just found by a directory scan in which case we probably don't want it. it's more like heuristics actually.) return name.equalsIgnoreCase("input") || name.equalsIgnoreCase("output"); } public final static String charsetForTextFiles = "UTF8"; static long TempDirMaker_lastValue; public static File TempDirMaker_make() { File dir = new File(userHome(), ".javax/" + TempDirMaker_newValue()); dir.mkdirs(); return dir; } private static long TempDirMaker_newValue() { long value; do value = System.currentTimeMillis(); while (value == TempDirMaker_lastValue); TempDirMaker_lastValue = value; return value; } public static String join(String glue, Iterable strings) { StringBuilder buf = new StringBuilder(); Iterator i = strings.iterator(); if (i.hasNext()) { buf.append(i.next()); while (i.hasNext()) buf.append(glue).append(i.next()); } return buf.toString(); } public static String join(String glue, String[] strings) { return join(glue, Arrays.asList(strings)); } public static String join(Iterable strings) { return join("", strings); } public static String join(String[] strings) { return join("", strings); } // join public static boolean isWindows() { return System.getProperty("os.name").contains("Windows"); } public static String makeRandomID(int length) { Random random = new Random(); char[] id = new char[length]; for (int i = 0; i< id.length; i++) id[i] = (char) ((int) 'a' + random.nextInt(26)); return new String(id); } static String computerID; public static String getComputerID() throws IOException { if (noID) return null; if (computerID == null) { File file = new File(userHome(), ".tinybrain/computer-id"); computerID = loadTextFile(file.getPath(), null); if (computerID == null) { computerID = makeRandomID(12); saveTextFile(file.getPath(), computerID); } if (verbose) System.out.println("Local computer ID: " + computerID); } return computerID; } static void cleanCache() { cleanJavaXCache(tempFileRetentionTime, verbose); } static void showSystemProperties() { System.out.println("System properties:\n"); for (Map.Entry entry : System.getProperties().entrySet()) { System.out.println(" " + entry.getKey() + " = " + entry.getValue()); } System.out.println(); } static void showVersion() { //showSystemProperties(); boolean eclipseFound = hasEcj(); //String platform = System.getProperty("java.vendor") + " " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.version"); String platform = System.getProperty("java.vm.name") + " " + System.getProperty("java.version"); String os = System.getProperty("os.name"), arch = System.getProperty("os.arch"); System.out.println("This is " + version + "."); System.out.println("[Details: " + (eclipseFound ? "Eclipse compiler (good)" : "javac (not so good)") + ", " + platform + ", " + arch + ", " + os + "]"); } static boolean isAndroid() { return System.getProperty("java.vendor").toLowerCase().indexOf("android") >= 0; } static void set(Object o, String field, Object value) { if (o instanceof Class) set((Class) o, field, value); else try { Field f = set_findField(o.getClass(), field); smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } } static void set(Class c, String field, Object value) { try { Field f = set_findStaticField(c, field); smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static Field set_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static Field set_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } // set function static String smartJoin(String[] args) { String[] a2 = new String[args.length]; for (int i = 0; i < args.length; i++) { a2[i] = Pattern.compile("\\w+").matcher(args[i]).matches() ? args[i] : quote(args[i]); } return join(" ", a2); } static void logStart(String[] args) throws IOException { String line = smartJoin(args); appendToLog(new File(userHome(), ".javax/log.txt").getPath(), line); } static String quote(String s) { if (s == null) return "null"; return "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r", "\\r").replace("\n", "\\n") + "\""; } static void appendToLog(String path, String line) throws IOException { appendToFile(path, "\n" + line + "\n"); } static void appendToFile(String path, String s) throws IOException { new File(path).getParentFile().mkdirs(); Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(path, true), "UTF-8")); writer.write(s); writer.close(); } static class DelayedUpdate { Runnable renderer; volatile long version; long lastUpdate; // AWT time int delay = 1000; DelayedUpdate(Runnable renderer) { this.renderer = renderer;} void trigger() { swingLater(new Runnable() { public void run() { try { awt_quickUpdate(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); final long n = ++version; javax.swing.Timer timer = new javax.swing.Timer(delay, new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { awt_show(n); }}); timer.setRepeats(false); timer.start(); } void awt_quickUpdate() { if (lastUpdate < now()-delay) { render(); lastUpdate = now(); // This can be rough, no problem } } void awt_show(long n) { if (n == version) { render(); lastUpdate = now(); } } void render() { try { renderer.run(); } catch (Throwable e) { e.printStackTrace(); } } } static PrintStream oldOut, oldErr; static Thread reader, reader2; static boolean quit; // always false now static PipedInputStream pin=new PipedInputStream(systemOutPipeSize); static PipedInputStream pin2=new PipedInputStream(systemErrPipeSize); static PipedInputStream pin3=new PipedInputStream(systemInPipeSize); static PipedOutputStream pout3; static class Console /*extends WindowAdapter implements WindowListener,*/ implements ActionListener { JFrame frame; JTextArea textArea; JTextField tfInput; StringBuffer buf = new StringBuffer(); JButton buttonclear, buttonkill, buttonrestart, buttonduplicate, buttonstacktrace, buttonpause, buttonhide; String[] args; volatile boolean autoScroll = true; JScrollPane scrollPane; String title; final DelayedUpdate du = new DelayedUpdate(new Runnable() { public void run() { try { synchronized(buf) { int max = maxConsoleChars; if (buf.length() > max) { try { int newLength = max/2; int ofs = buf.length()-newLength; String newString = buf.substring(ofs); buf.setLength(0); buf.append("[...] ").append(newString); } catch (Exception e) { buf.setLength(0); } textArea.setText(""); } } textArea.append(buf.substring(textArea.getText().length())); if (autoScroll) scrollToBottom(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); public Console(final String[] args) { try { this.args = args; // create all components and add them frame=new JFrame(args.length == 0 ? "JavaX Starter Output" : "JavaX Output - " + join(" ", args)); /*Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize=new Dimension((int)(screenSize.width/2),(int)(screenSize.height/2)); int x=(int)(frameSize.width/2); int y=(int)(frameSize.height/2); frame.setBounds(x,y,frameSize.width,frameSize.height);*/ // put in right-bottom corner Rectangle r = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); int w = 550, h = 200; frame.setBounds(r.x+r.width-w, r.y+r.height-h, w, h); textArea=new JTextArea(); textArea.setEditable(false); buttonclear = new JButton("clear"); buttonkill = new JButton("kill"); buttonrestart = new JButton("restart"); buttonduplicate = new JButton("duplicate"); buttonstacktrace = new JButton("status"); buttonstacktrace.setToolTipText("Show threads & stack traces."); buttonpause = new JButton("pause"); buttonhide = new JButton("hide"); JPanel buttons = new JPanel(new GridLayout(1, 7)); buttons.add(buttonclear); buttons.add(buttonkill); buttons.add(buttonrestart); buttons.add(buttonduplicate); buttons.add(buttonstacktrace); buttons.add(buttonpause); buttons.add(buttonhide); pout3=new PipedOutputStream(pin3); tfInput = new JTextField(); tfInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { String line = tfInput.getText(); try { pout3.write((line + "\n").getBytes("UTF-8")); pout3.flush(); } catch (Exception e) {} //tfInput.setText(""); tfInput.selectAll(); }}); addHistoryToTextField(tfInput); JPanel panel = new JPanel(new BorderLayout()); panel.add(scrollPane = new JScrollPane(textArea), BorderLayout.CENTER); panel.add(tfInput, BorderLayout.SOUTH); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { tfInput.requestFocus(); } public synchronized void windowClosing(WindowEvent evt) { if (JOptionPane.showConfirmDialog(frame, "Close " + (empty(title) ? "JavaX Application" : title) + "?", "JavaX", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) System.exit(0); } }); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(panel, BorderLayout.CENTER); frame.getContentPane().add(buttons, BorderLayout.SOUTH); frame.setVisible(true); setFrameIconLater(frame, "#1004249"); //frame.addWindowListener(this); // disabled for now buttonclear.addActionListener(this); buttonkill.addActionListener(this); buttonrestart.addActionListener(this); buttonduplicate.addActionListener(this); buttonstacktrace.addActionListener(this); buttonpause.addActionListener(this); buttonhide.addActionListener(this); quit=false; // signals the Threads that they should exit if (args.length != 0) { print("Starting title updater"); new Thread("Console Title Updater :)") { public void run() { if (args.length != 0) { int i = 0; while (i < args.length && !isSnippetID(args[i])) ++i; print("Getting title for " + args[i]); title = getSnippetTitle(args[i]); print("Title: " + title); if (title != null && title.length() != 0) frame.setTitle(title + " [Output]"); } } }.start(); } System.setIn(pin3); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} void scrollToBottom() { JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setValue(vertical.getMaximum()); } /*public synchronized void windowClosed(WindowEvent evt) { console = null; //quit=true; //this.notifyAll(); // stop all threads //try { reader.join(1000);pin.close(); } catch (Exception e){} //try { reader2.join(1000);pin2.close(); } catch (Exception e){} //System.exit(0); }*/ /*public synchronized void windowClosing(WindowEvent evt) { frame.setVisible(false); // default behaviour of JFrame frame.dispose(); }*/ public synchronized void actionPerformed(ActionEvent evt) { if (evt.getSource() == buttonkill) { print("Console: Kill button pressed!"); // TODO: give threads time to finish, e.g. reportToChat? System.exit(0); } else if (evt.getSource() == buttonrestart) { print("Console: Restart button pressed."); nohupJavax(smartJoin(args)); System.exit(0); } else if (evt.getSource() == buttonduplicate) { print("Console: Duplicate button pressed."); nohupJavax(smartJoin(args)); } else if (evt.getSource() == buttonstacktrace) { listUserThreadsWithStackTraces(); } else if (evt.getSource() == buttonpause) { Object mainClass = getMainMainClass(); if (mainClass != null) { if (eq(buttonpause.getText(), "pause")) { buttonpause.setText("resume"); setOpt(mainClass, "ping_pauseAll", true); } else { buttonpause.setText("pause"); setOpt(mainClass, "ping_pauseAll", false); } } } else if (evt.getSource() == buttonhide) { hideConsole(); } else { textArea.setText(""); buf = new StringBuffer(); } } void showConsole() { frame.setVisible(true); } void hideConsole() { autoVMExit(); frame.setVisible(false); } public void appendText(String s, boolean outNotErr) { //if (verbose) oldOut.println("Console appendText " + outNotErr + " " + quote(s)); synchronized(buf) { buf.append(s); } du.trigger(); } } // Console static void tryToOpenConsole(String[] args) { try { console = new Console(args); } catch (HeadlessException e) { // ok, we're headless. } catch (Throwable e) { // some other error in console - continue without it e.printStackTrace(); } } //// END CONSOLE STUFF static long now_virtualTime; static long now() { return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis(); } static void print(Object o) { System.out.println(o); } public synchronized void run() { try { while (Thread.currentThread()==reader) { try { this.wait(100);}catch(InterruptedException ie) {} if (pin.available()!=0) { String input=readLine(pin); //if (verbose) oldOut.println("reader: " + quote(input)); appendText(input, true); } if (quit) return; } while (Thread.currentThread()==reader2) { try { this.wait(100);}catch(InterruptedException ie) {} if (pin2.available()!=0) { String input=readLine(pin2); //if (verbose) oldOut.println("reader2: " + quote(input)); appendText(input, false); } if (quit) return; } } catch (Exception e) { appendText("\nConsole reports an Internal error.", false); appendText("The error is: "+e, false); } } static void redirectSystemOutAndErr() { if (reader != null) return; // did this already x30 _this = new x30(); if (verbose) System.out.println("Redirecting System.out"); try { PipedOutputStream pout=new PipedOutputStream(pin); oldOut = System.out; TeeOutputStream tee = new TeeOutputStream(oldOut, pout); System.setOut(new PrintStream(tee,true)); } catch (Exception io) { System.err.println("Couldn't redirect STDOUT - " + io.getMessage()); } if (verbose) System.out.println("Redirecting System.err"); try { PipedOutputStream pout2=new PipedOutputStream(pin2); oldErr = System.err; TeeOutputStream tee = new TeeOutputStream(oldErr, pout2); System.setErr(new PrintStream(tee,true)); } catch (Exception io) { System.err.println("Couldn't redirect STDERR - " + io.getMessage()); } if (verbose) System.out.println("Redirects done. Starting readers"); // Starting two seperate threads to read from the PipedInputStreams // reader=new Thread(_this, "StdOut Piper"); reader.setDaemon(true); reader.start(); // reader2 = new Thread(_this, "StdErr Piper"); reader2.setDaemon(true); reader2.start(); } static Appendable customSystemOut; static StringBuffer outBuf = new StringBuffer(); // We now log it all. static ArrayDeque systemInBuf = new ArrayDeque(); static void appendText(String s, boolean outNotErr) { // We do this with a TeeOutputStream now (safer). // (outNotErr ? oldOut : oldErr).print(s); if (console != null) console.appendText(s, outNotErr); outBuf.append(s); if (customSystemOut != null) try { customSystemOut.append(s); } catch (IOException e) { e.printStackTrace(); } } static String readLine(PipedInputStream in) throws IOException { String input=""; do { int available=in.available(); if (available==0) break; byte b[]=new byte[available]; in.read(b); input=input+new String(b,0,b.length); }while( !input.endsWith("\n") && !input.endsWith("\r\n") && !quit); return input; } static void nohupJavax(String javaxargs) { try { File xfile = new File(userHome(), ".javax/x30.jar"); if (!xfile.isFile()) { String url = "http://tinybrain.de/x30.jar"; byte[] data = loadBinaryPage(new URL(url).openConnection()); if (data.length < 1000000) throw new RuntimeException("Could not load " + url); saveBinaryFile(xfile.getPath(), data); } String jarPath = xfile.getPath(); nohup("java -jar " + (isWindows() ? winQuote(jarPath) : bashQuote(jarPath)) + " " + javaxargs); } catch (Exception e) { throw new RuntimeException(e); } } /** possibly improvable */ public static String winQuote(String text) { if (text == null) return null; return "\"" + text .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\r", "\\r") + "\""; } public static File nohup(String cmd) throws IOException { File outFile = File.createTempFile("nohup_" + nohup_sanitize(cmd), ".out"); nohup(cmd, outFile, false); return outFile; } static String nohup_sanitize(String s) { return s.replaceAll("[^a-zA-Z0-9\\-_]", ""); } /** outFile takes stdout and stderr. */ public static void nohup(String cmd, File outFile, boolean append) throws IOException { String command = nohup_makeNohupCommand(cmd, outFile, append); File scriptFile = File.createTempFile("_realnohup", isWindows() ? ".bat" : ""); System.out.println("[Nohup] " + command); try { //System.out.println("[RealNohup] Script file: " + scriptFile.getPath()); saveTextFile(scriptFile.getPath(), command); String[] command2; if (isWindows()) command2 = new String[] {"cmd", "/c", "start", "/b", scriptFile.getPath() }; else command2 = new String[] {"/bin/bash", scriptFile.getPath() }; Process process = Runtime.getRuntime().exec(command2); try { process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } int value = process.exitValue(); //System.out.println("exit value: " + value); } finally { if (!isWindows()) scriptFile.delete(); } } public static String nohup_makeNohupCommand(String cmd, File outFile, boolean append) { mkdirsForFile(outFile); String command; if (isWindows()) command = cmd + (append ? " >>" : " >") + winQuote(outFile.getPath()) + " 2>&1"; else command = "nohup " + cmd + (append ? " >>" : " >") + bashQuote(outFile.getPath()) + " 2>&1 &"; return command; } public static void mkdirsForFile(File file) { File dir = file.getParentFile(); if (dir != null) // is null if file is in current dir dir.mkdirs(); } static void autoReportToChat() { if (customSystemOut == null) { print("Auto-reporting to chat."); customSystemOut = new Appendable() { LineBuf buf = new LineBuf(); // only using this one public Appendable append(CharSequence cs) { buf.append(cs.toString()); while (true) { String s = buf.nextLine(); if (s == null) break; reportToChat(s, true); } return this; } public Appendable append(char c) { return this; } public Appendable append(CharSequence s, int start, int end) { return this; } }; } } static class Q { LinkedBlockingQueue q = new LinkedBlockingQueue(); static class Done extends RuntimeException {} Q() {} Q(String name, boolean startThread) { if (startThread) new Thread(name) { public void run() { Q.this.run(); } }.start(); } Iterable master() { return new Iterable() { public Iterator iterator() { return new Iterator() { Runnable x; public boolean hasNext() { try { //debug("hasNext"); while (x == null) x = q.poll(1, TimeUnit.DAYS); //debug("hasNext true"); return true; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} public Runnable next() { //debug("next"); hasNext(); Runnable _x = x; x = null; //debug("next " + structure(x)); return _x; } public void remove() { } }; } }; } void add(Runnable r) { q.add(r); } void run() { for (Runnable r : master()) { try { r.run(); } catch (Done e) { return; // break signal } catch (Throwable e) { e.printStackTrace(); } } } void done() { add(new Runnable() { public void run() { throw new Done(); } }); } } // class Q static void reportToChat(final String s, boolean silent) { if (s == null || s.length() == 0) return; if (!silent) print("reportToChat: " + quote(s)); reportToChat_getChatThread().add(new Runnable() { public void run() { try { startChatServerIfNotUp(); waitForChatServer(); chatSend(s); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}}); } static Q reportToChat_q; static Q reportToChat_getChatThread() { if (reportToChat_q == null) reportToChat_q = new Q("reportToChat", true); return reportToChat_q; } static void startChatServerIfNotUp() { if (portIsBound(9751)) { //print("Chat seems to be up."); } else { nohupJavax("1000867"); print("Chat server should be coming up any minute now."); } } static void waitForChatServer() { if (!portIsBound(9751)) { //System.out.print("Waiting for chat server... "); do { sleep(1000); } while (!portIsBound(9751)); //print("OK."); } } static boolean portIsBound(int port) { try { ServerSocket s = new ServerSocket(port); s.close(); return false; } catch (IOException e) { return true; } } static class LineBuf { StringBuffer buf = new StringBuffer(); void append(String s) { buf.append(s); } String nextLine() { int i = buf.indexOf("\n"); if (i >= 0) { String s = buf.substring(0, i > 0 && buf.charAt(i-1) == '\r' ? i-1 : i); buf.delete(0, i+1); return s; } return null; } } // LineBuf static int chatSend_chatPort = 9751; static abstract class DialogIO { String line; boolean eos; abstract String readLineImpl(); abstract boolean isStillConnected(); abstract void sendLine(String line); abstract boolean isLocalConnection(); abstract Socket getSocket(); abstract void close(); int getPort() { return getSocket().getPort(); } boolean helloRead; String readLineNoBlock() { String l = line; line = null; return l; } boolean waitForLine() { try { if (line != null) return true; //print("Readline"); line = readLineImpl(); //print("Readline done: " + line); if (line == null) eos = true; return line != null; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} String readLine() { waitForLine(); helloRead = true; return readLineNoBlock(); } String ask(String s, Object... args) { if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); sendLine(s); return readLine(); } String askLoudly(String s, Object... args) { if (!helloRead) readLine(); if (args.length != 0) s = format3(s, args); print("> " + s); sendLine(s); String answer = readLine(); print("< " + answer); return answer; } void pushback(String l) { if (line != null) throw fail(); line = l; helloRead = false; } } static abstract class DialogHandler { abstract void run(DialogIO io); } // DialogIO static DialogIO chatSend_dialog; static String chatSend_id; static void chatSend(String line) { try { if (chatSend_dialog == null) { chatSend_dialog = talkTo("localhost", chatSend_chatPort); chatSend_dialog.waitForLine(); String l = chatSend_dialog.readLineNoBlock(); if (l.startsWith("Your ID: ")) chatSend_id = l.substring("Your ID: ".length()); } chatSend_dialog.sendLine(line); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // chatSend static class TeeOutputStream extends OutputStream { protected OutputStream out, branch; public TeeOutputStream( OutputStream out, OutputStream branch ) { this.out = out; this.branch = branch; } @Override public synchronized void write(byte[] b) throws IOException { write(b, 0, b.length); } @Override public synchronized void write(byte[] b, int off, int len) throws IOException { //if (verbose) oldOut.println("Tee write " + new String(b, "UTF-8")); out.write(b, off, len); this.branch.write(b, off, len); } @Override public synchronized void write(int b) throws IOException { write(new byte[] {(byte) b}); } /** * Flushes both streams. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { out.flush(); this.branch.flush(); } /** * Closes both streams. * @throws IOException if an I/O error occurs */ @Override public void close() throws IOException { out.close(); this.branch.close(); } } static boolean isChatServer(String[] args) { for (int i = 0; i < args.length; i++) if (isSnippetID(args[i])) return parseSnippetID(args[i]) == 1000867; return false; } static String getSnippetTitle(String id) { try { return loadPage(new URL("http://tinybrain.de:8080/tb-int/getfield.php?id=" + parseSnippetID(id) + "&field=title")); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } static void listUserThreadsWithStackTraces() { print(""); Map threadMap = Thread.getAllStackTraces(); int n = 0; for (Thread t : threadMap.keySet()) { ThreadGroup g = t.getThreadGroup(); if (g != null && g.getName().equals("system")) continue; ++n; print(t); for (StackTraceElement e : threadMap.get(t)) { print(" " + e); } print(""); } print(n + " user threads."); } static void killMyself() { print("Killing myself. (insert overall feeling here)"); System.exit(0); } static void makeVMAndroid() { Android3 a = new Android3("This is a JavaX VM."); a.responder = new Responder() { String answer(String s, List history) { return x30.answer(s, history); } }; a.daemon = true; a.console = false; a.incomingSilent = true; // to avoid too much printing a.useMultiPort = false; makeAndroid3(a); } static class Info { String programID; String[] programArgs; File transpiledSrc; Class mainClass; } static Info info = new Info(); // hmm... // injectable info static List injectable_programsInjected = new ArrayList(); static boolean injectable_on = true; static class PaA { String injectionID; String progID; String[] arguments; Class mainClass; // TODO: release eventually... WeakReference mainThread; volatile boolean mainDone; volatile Throwable exception; PaA(String progID, String[] arguments) { this.arguments = arguments; this.progID = progID;} PaA() {} } static String vmID = makeRandomID(10); static synchronized void addInjection(PaA paa) { injectable_programsInjected.add(paa); } static synchronized void removeInjection(PaA paa) { injectable_programsInjected.remove(paa); } static synchronized List getInjections() { return cloneList(injectable_programsInjected); } static String answer(String s, List history) { try { Matches m = new Matches(); if (match3("kill!", s)) { killMyself(); return "ok"; } if (match3("What is your process ID?", s) || match3("what is your pid?", s)) return getPID(); if (match3("get vm id", s)) return vmID; if (match3("what is the javax program id?", s)) return javaxProgramID; if (match3("what is the main program id?", s)) return info.programID; if (match3("what are your program arguments?", s)) return structure(info.programArgs); if (match3("get output", s)) return quote(outBuf.toString()); if (match3("get output length", s)) return "" + outBuf.length(); if (match3("get output substring from *", s, m)) return quote(outBuf.substring(parseInt(m.get(0)))); if (match3("get output substring from * to *", s, m)) return quote(outBuf.substring(parseInt(m.get(0)), parseInt(m.get(1)))); if (match3("clear output", s)) { synchronized(x30.class) { int len = outBuf.length(); outBuf.setLength(0); return "OK, deleted " + len + " chars."; } } if (match3("send line * to system.in", s, m)) { String line = m.unq(0); synchronized(x30.class) { systemInBuf.add(line); } return "ok"; } if (match3("get fields of main class", s)) return structure(listFields(info.mainClass)); if (match3("get field * of main class", s, m)) return structure(get(info.mainClass, m.m[0])); if (match3("invoke function * of main class", s, m)) return structure(call(info.mainClass, m.m[0])); if (match3("set field * of main class to *", s, m)) { set(info.mainClass, m.m[0], unstructure(m.m[1])); return "ok"; } if (match3("how much memory are you consuming", s)) return "Java heap size: " + (Runtime.getRuntime().totalMemory()+1024*1024-1)/1024/1024 + " MB"; if (match3("how much memory is used after GC?", s)) { System.gc(); return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB"; } if (match3("how much memory is used?", s)) return "Java heap used: " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()+1024*1024-1)/1024/1024 + " MB"; if (match3("please inject program *", s, m) || match3("please inject program * with arguments *", s, m)) { synchronized(x30.class) { final String progID = formatSnippetID(unquote(m.m[0])); final String[] arguments = m.m.length > 1 ? toStringArray(unstructure(unquote(m.m[1]))) : new String[0]; final PaA paa = new PaA(progID, arguments); paa.injectionID = randomID(8); addInjection(paa); // better call JavaX for translation in a single thread. paa.mainClass = hotwire(progID); // program may run in its own thread. { /*nt*/ Thread _t_2 = new Thread(progID) { public void run() { /* in run */ try { /* pcall 1*/ /* in thread */ paa.mainThread = new WeakReference(currentThread()); try { callMain(paa.mainClass, arguments); } catch (Throwable e) { paa.exception = e; e.printStackTrace(); } finally { paa.mainDone = true; synchronized(x30.class) {} } /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ } }; _t_2.start(); } return format3("OK. Injection ID: *", paa.injectionID); } } if (match3("get injection exception *", s, m)) { String injectionID = unquote(m.m[0]); PaA paa = findInjection(injectionID); if (paa == null) return "Sorry. Injection not found"; return "OK: " + paa.exception == null ? "no exception" : getStackTrace(paa.exception); } if (match3("get injection * variable *", s, m)) { String injectionID = unquote(m.m[0]); String var = unquote(m.m[1]); PaA paa = findInjection(injectionID); if (paa == null) return "Sorry. Injection not found"; return "OK: " + structure(getOpt(paa.mainClass, var)); } if (match3("get injection result *", s, m)) { String injectionID = unquote(m.m[0]); PaA paa = findInjection(injectionID); if (paa == null) return "Sorry. Injection not found"; return "OK: " + structure(getOpt(paa.mainClass, "result")); } if (match3("is injection's * main done", s, m)) { String injectionID = unquote(m.m[0]); PaA paa = findInjection(injectionID); if (paa == null) return "Sorry. Injection not found"; return paa.mainDone ? "Yes." : "No."; } if (match3("get injections", s, m)) { return structure(getInjections()); } if (match3("remove injection *", s, m)) { String injectionID = unquote(m.m[0]); PaA paa = findInjection(injectionID); if (paa == null) return "Sorry. Injection not found"; removeInjection(paa); return "OK, removed."; } if (match3("which programs are you running (ids only)", s, m)) { synchronized(x30.class) { List l = new ArrayList(); for (String progID : instances.keySet()) if (getInstance(progID) != null) l.add(progID); return format3("these: *", structure(l)); } } if (match("show console", s, m)) { if (console != null) { console.showConsole(); return "ok"; } return "no console"; } if (match("hide console", s, m)) { if (console != null) { console.hideConsole(); return "ok"; } return "no console"; } List multiPorts = getMultiPorts(); if (!multiPorts.isEmpty()) { Object multiPort = multiPorts.get(0); String answer = makeResponder(multiPort).answer(s, history); if (answer != null) return answer; } if (match3("list bots", s)) return structure(litmap()); return null; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static synchronized PaA findInjection(String injectionID) { for (PaA paa : injectable_programsInjected) if (eq(paa.injectionID, injectionID)) return paa; return null; } static int makeAndroid(String greeting) { return makeAndroid3(greeting).port; } static void makeAndroid(Android3 a) { makeAndroid3(a); } // makeAndroid / makeAndroidNoConsole static void setOpt(Object o, String field, Object value) { if (o instanceof Class) setOpt((Class) o, field, value); else try { Field f = setOpt_findField(o.getClass(), field); if (f != null) smartSet(f, o, value); } catch (Exception e) { throw new RuntimeException(e); } } static void setOpt(Class c, String field, Object value) { try { Field f = setOpt_findStaticField(c, field); if (f != null) smartSet(f, null, value); } catch (Exception e) { throw new RuntimeException(e); } } static Field setOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static Field setOpt_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } // setOpt // get purpose 1: access a list/array (safer version of x.get(y)) static A get(List l, int idx) { return idx >= 0 && idx < l(l) ? l.get(idx) : null; } static A get(A[] l, int idx) { return idx >= 0 && idx < l(l) ? l[idx] : null; } // get purpose 2: access a field by reflection or a map static Object get(Object o, String field) { if (o instanceof Class) return get((Class) o, field); if (o instanceof Map) return ((Map) o).get(field); if (o.getClass().getName().equals("main$DynamicObject")) return call(get_raw(o, "fieldValues"), "get", field); return get_raw(o, field); } static Object get_raw(Object o, String field) { try { Field f = get_findField(o.getClass(), field); f.setAccessible(true); return f.get(o); } catch (Exception e) { throw new RuntimeException(e); } } static Object get(Class c, String field) { try { Field f = get_findStaticField(c, field); f.setAccessible(true); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } static Field get_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Static field '" + field + "' not found in " + c.getName()); } static Field get_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); throw new RuntimeException("Field '" + field + "' not found in " + c.getName()); } // get static Class getMainClass() { try { return Class.forName("main"); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Class getMainClass(Object o) { try { return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main"); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // getMainClass static DialogIO talkTo(int port) { return talkTo("localhost", port); } static int talkTo_defaultTimeout = 10000; static DialogIO talkTo(String ip, int port) { try { final Socket s = new Socket(); s.connect(new InetSocketAddress(ip, port), talkTo_defaultTimeout); //print("Talking to " + ip + ":" + port); final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); final BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8")); return new DialogIO() { boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } boolean isStillConnected() { return !(eos || s.isClosed()); } void sendLine(String line) { try { w.write(line + "\n"); w.flush(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} String readLineImpl() { try { return in.readLine(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} void close() { try { s.close(); } catch (IOException e) { // whatever } } Socket getSocket() { return s; } }; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} // talkTo static String[] toStringArray(List list) { return list.toArray(new String[list.size()]); } static String[] toStringArray(Object o) { if (o instanceof String[]) return (String[]) o; else if (o instanceof List) return toStringArray((List) o); else throw fail("Not a list or array: " + structure(o)); } // toStringArray static byte[] loadDataSnippetImpl(String snippetID) throws IOException { byte[] data; try { URL url = new URL("http://eyeocr.sourceforge.net/filestore/filestore.php?cmd=serve&file=blob_" + parseSnippetID(snippetID) + "&contentType=application/binary"); System.err.println("Loading library: " + url); try { data = loadBinaryPage(url.openConnection()); } catch (IOException e) { data = null; } if (data == null || data.length == 0) { url = new URL("http://data.tinybrain.de/blobs/" + parseSnippetID(snippetID)); System.err.println("Loading library: " + url); data = loadBinaryPage(url.openConnection()); } System.err.println("Bytes loaded: " + data.length); } catch (FileNotFoundException e) { throw new IOException("Binary snippet #" + snippetID + " not found or not public"); } return data; } static AtomicBoolean readLine_used = new AtomicBoolean(); static BufferedReader readLine_reader; static synchronized String pollSystemInBuf() { return systemInBuf.poll(); } static String readLine() { try { if (!readLine_used.compareAndSet(false, true)) throw fail("readLine is in use."); try { while (true) { String s = pollSystemInBuf(); if (s != null) { print(s); return s; } if (readLine_reader == null) readLine_reader = new BufferedReader(new InputStreamReader(System.in, "UTF-8")); // XX - is that right? if (!readLine_reader.ready()) sleep(100); else { s = readLine_reader.readLine(); if (s != null) { print(s); return s; } } } } finally { readLine_used.set(false); } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static HashMap weakrefs = new HashMap(); // static WeakIdentityHashMap reverseWeakrefs = new WeakIdentityHashMap(); static long weakRefCounter; // TODO: lookup in reverse map static synchronized String weakref(Object o) { if (o == null) return "null"; String id = vmID + "/" + ++weakRefCounter; weakrefs.put(id, new WeakReference(o)); return id; } static synchronized Object getRef(String id) { // TODO: clean up the list some time WeakReference ref = weakrefs.get(id); if (ref == null) return null; return ref.get(); } static List multiPorts = new ArrayList(); static synchronized List getMultiPorts() { return cloneList(multiPorts); } // true if you're the first one static synchronized boolean addMultiPort(Object o) { multiPorts.add(o); if (multiPorts.size() == 1) { { /*nt*/ Thread _t_0 = new Thread("keep alive") { public void run() { /* in run */ try { /* pcall 1*/ /* in thread */ x30.sleep(); /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ } }; _t_0.start(); } // keep VM alive since there is a multiport } return multiPorts.size() == 1; } static synchronized void removeMultiPort(Object o) { multiPorts.remove(o); } static String getInjectionID(Class mainClass) { List l = getInjections(); for (PaA injection : l) if (injection.mainClass == mainClass) return injection.injectionID; return null; } static String getInjectionID() { return null; } // used somewhere... static void sleep(long ms) { try { Thread.sleep(ms); } catch (Exception e) { throw new RuntimeException(e); } } static void sleep() { try { print("Sleeping."); synchronized(x30.class) { x30.class.wait(); } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static WeakHashMap classToSourceCode = new WeakHashMap(); synchronized static void registerSourceCode(Class c, String src) { classToSourceCode.put(c, src); } synchronized static String getSourceCodeForClass(Class c) { return classToSourceCode.get(c); } static class Matches { String[] m; String get(int i) { return i < m.length ? m[i] : null; } String unq(int i) { return unquote(get(i)); } String fsi(int i) { return formatSnippetID(unq(i)); } String fsi() { return fsi(0); } String tlc(int i) { return unq(i).toLowerCase(); } boolean bool(int i) { return "true".equals(unq(i)); } String rest() { return m[m.length-1]; } // for matchStart int psi(int i) { return Integer.parseInt(unq(i)); } } // Matches static void autoScroll(boolean on) { if (console == null) return; console.autoScroll = on; if (on) swingLater(new Runnable() { public void run() { try { console.scrollToBottom(); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); } // get main class of first program (for console) static Object getMainMainClass() { PaA paa = first(getInjections()); return paa == null ? null : paa.mainClass; } static boolean _inCore() { return true; } // This is for main classes that are all static. // (We don't go to base classes.) static Set listFields(Object c) { TreeSet fields = new TreeSet(); for (Field f : ((Class) c).getDeclaredFields()) fields.add(f.getName()); return fields; } /** possibly improvable */ static String bashQuote(String text) { if (text == null) return null; return "\"" + text .replace("\\", "\\\\") .replace("\"", "\\\"") .replace("\n", "\\n") .replace("\r", "\\r") + "\""; } static String bashQuote(File f) { return bashQuote(f.getAbsolutePath()); } static Thread currentThread() { return Thread.currentThread(); } static List cloneList(Collection l) { //O mutex = getOpt(l, "mutex"); /*if (mutex != null) synchronized(mutex) { ret new ArrayList(l); } else ret new ArrayList(l);*/ // assume mutex is equal to collection, which will be true unless you explicitly pass a mutex to synchronizedList() which no one ever does. synchronized(l) { return new ArrayList(l); } } // Call this AFTER other action listeners have been registered. static void addHistoryToTextField(final JTextField input) { final Var historyIdx = new Var(0); final List history = new ArrayList(); input.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP) { //print("up"); listSet(history, historyIdx.get(), input.getText(), ""); historyIdx.set(max(0, historyIdx.get()-1)); String text = get(history, historyIdx.get()); if (text != null) { input.setText(text); input.selectAll(); } } if (e.getKeyCode() == KeyEvent.VK_DOWN) { //print("down"); String text = input.getText(); if (historyIdx.get() < l(history) || neq(last(history), text)) listSet(history, historyIdx.get(), text, ""); historyIdx.set(min(l(history), historyIdx.get()+1)); text = get(history, historyIdx.get()); input.setText(unnull(text)); input.selectAll(); } } }); input.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { String text = input.getText(); //print("Text: " + text); while (history.contains("")) history.remove(""); history.remove(text); history.add(text); historyIdx.set(l(history)); }}); } static Map litmap(Object... x) { TreeMap map = new TreeMap(); litmap_impl(map, x); return map; } static void litmap_impl(Map map, Object... x) { for (int i = 0; i < x.length-1; i += 2) if (x[i+1] != null) map.put(x[i], x[i+1]); } static RuntimeException fail() { throw new RuntimeException("fail"); } static RuntimeException fail(Object msg) { throw new RuntimeException(String.valueOf(msg)); } static RuntimeException fail(String msg) { throw new RuntimeException(unnull(msg)); } // disabled for now to shorten some programs /*static RuntimeException fail(S msg, O... args) { throw new RuntimeException(format(msg, args)); }*/ static void cleanJavaXCache(int retentionHours, boolean verbose) { try { /* pcall 1*/ if (verbose) System.out.println("Cleaning JavaX Cache (" + retentionHours + " hours retention time)"); int fileDeletions = 0; File javax = new File(userHome(), ".javax"); long now = now(); File[] files = javax.listFiles(); if (files != null) for (File dir : files) { if (dir.isDirectory() && Pattern.compile("\\d+").matcher(dir.getName()).matches()) { long time = Long.parseLong(dir.getName()); long seconds = (now - time) / 1000; long minutes = seconds / 60; long hours = minutes / 60; if (hours >= retentionHours) { //System.out.println("Can delete " + dir.getAbsolutePath() + ", age: " + hours + " h"); fileDeletions += cleanJavaXCache_removeDir(dir, verbose); } } } if (verbose && fileDeletions != 0) print("Cleaned cache. File deletions: " + fileDeletions); /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } } static int cleanJavaXCache_removeDir(File dir, boolean verbose) { int fileDeletions = 0; if (dir.getAbsolutePath().indexOf(".javax") < 0) // security check! throw fail("WHAT ARE YOU DOING!? >> " + dir.getAbsolutePath()); for (File f : dir.listFiles()) { if (f.isDirectory()) cleanJavaXCache_removeDir(f, verbose); else { if (verbose) print("Deleting " + f.getAbsolutePath()); f.delete(); ++fileDeletions; } } dir.delete(); return fileDeletions; } static void hideConsole() { JFrame frame = consoleFrame(); if (frame != null) { autoVMExit(); frame.setVisible(false); } } static String fsi(String id) { return formatSnippetID(id); } static String boss(String line) { try { //S s = sendToLocalBotOpt("Boss Bot", line); DialogIO io = talkTo(4990); // Boss Bot port io.readLine(); io.sendLine(line); String s = io.readLine(); Matches m = new Matches(); if (match3("text: *", s, m)) return unquote(m.m[0]); return null; } catch (Exception e) { //e.printStackTrace(); return null; } } static Object unstructure(String text) { return unstructure(text, false); } static Object unstructure(String text, final boolean allDynamic) { return unstructure(text, allDynamic, null); } // TODO: backrefs for hashmap{} etc // classFinder: name -> class static Object unstructure(String text, final boolean allDynamic, final Object classFinder) { if (text == null) return null; final List tok = javaTok(text); final boolean debug = unstructure_debug; class X { int i = 1; HashMap refs = new HashMap(); Object parse() { String t = tok.get(i); int refID = 0; if (t.startsWith("m") && isInteger(t.substring(1))) { refID = parseInt(t.substring(1)); i += 2; t = tok.get(i); } if (debug) print("parse: " + quote(t)); if (t.startsWith("\"")) { String s = unquote(tok.get(i)); i += 2; return s; } if (t.startsWith("'")) { char c = unquoteCharacter(tok.get(i)); i += 2; return c; } if (t.equals("bigint")) return parseBigInt(); if (t.equals("d")) return parseDouble(); if (t.equals("f")) return parseFloat(); if (t.equals("false") || t.equals("f")) { i += 2; return false; } if (t.equals("true") || t.equals("t")) { i += 2; return true; } if (t.equals("-")) { t = tok.get(i+2); i += 4; return isLongConstant(t) ? (Object) (-parseLong(t)) : (Object) (-parseInt(t)); } if (isInteger(t) || isLongConstant(t)) { i += 2; if (debug) print("isLongConstant " + quote(t) + " => " + isLongConstant(t)); if (isLongConstant(t)) return parseLong(t); long l = parseLong(t); return l != (int) l ? new Long(l) : new Integer((int) l); } if (t.equals("File")) { File f = new File(unquote(tok.get(i+2))); i += 4; return f; } if (t.startsWith("r") && isInteger(t.substring(1))) { i += 2; int ref = Integer.parseInt(t.substring(1)); Object o = refs.get(ref); if (o == null) print("Warning: unsatisfied back reference " + ref); return o; } return parse_inner(refID); } // everything that can be backreferenced Object parse_inner(int refID) { String t = tok.get(i); if (debug) print("parse_inner: " + quote(t)); if (t.equals("hashset")) return parseHashSet(); if (t.equals("treeset")) return parseTreeSet(); if (t.equals("hashmap")) return parseHashMap(); if (t.equals("{")) return parseMap(); if (t.equals("[")) return parseList(); if (t.equals("array")) return parseArray(); if (t.equals("ba")) { String hex = unquote(tok.get(i+2)); i += 4; return hexToBytes(hex); } if (t.equals("class")) return parseClass(); if (t.equals("l")) return parseLisp(); if (t.equals("null")) { i += 2; return null; } // any other class name if (isJavaIdentifier(t)) { Class c; if (allDynamic) c = null; else if (classFinder != null) c = (Class) callF(classFinder, t); else c = findClass(t); DynamicObject dO = null; Object o = null; if (c != null) o = nuObject(c); else { dO = new DynamicObject(); dO.className = t; } if (refID != 0) refs.put(refID, o); i += 2; if (i < tok.size() && tok.get(i).equals("(")) { consume("("); while (!tok.get(i).equals(")")) { // It's like parsing a map. //Object key = parse(); //if (tok.get(i).equals(")")) // key = onlyField(); String key = unquote(tok.get(i)); i += 2; consume("="); Object value = parse(); if (o != null) setOpt(o, key, value); else dO.fieldValues.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume(")"); } return o != null ? o : dO; } throw new RuntimeException("Unknown token " + (i+1) + ": " + t); } Object parseSet(Set set) { set.addAll((List) parseList()); return set; } Object parseLisp() { consume("l"); consume("("); List list = new ArrayList(); while (!tok.get(i).equals(")")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume(")"); return newObject("main$Lisp", (String) list.get(0), subList(list, 1)); } Object parseList() { consume("["); List list = new ArrayList(); while (!tok.get(i).equals("]")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume("]"); return list; } Object parseArray() { consume("array"); consume("{"); List list = new ArrayList(); while (!tok.get(i).equals("}")) { list.add(parse()); if (tok.get(i).equals(",")) i += 2; } consume("}"); return list.toArray(); } Object parseClass() { consume("class"); consume("("); String name = tok.get(i); i += 2; consume(")"); Class c = allDynamic ? null : findClass(name); if (c != null) return c; DynamicObject dO = new DynamicObject(); dO.className = "java.lang.Class"; dO.fieldValues.put("name", name); return dO; } Object parseBigInt() { consume("bigint"); consume("("); String val = tok.get(i); i += 2; if (eq(val, "-")) { val = "-" + tok.get(i); i += 2; } consume(")"); return new BigInteger(val); } Object parseDouble() { consume("d"); consume("("); String val = unquote(tok.get(i)); i += 2; consume(")"); return Double.parseDouble(val); } Object parseFloat() { consume("f"); String val; if (eq(tok.get(i), "(")) { consume("("); val = unquote(tok.get(i)); i += 2; consume(")"); } else { val = unquote(tok.get(i)); i += 2; } return Float.parseFloat(val); } Object parseHashMap() { consume("hashmap"); return parseMap(new HashMap()); } Object parseHashSet() { consume("hashset"); return parseSet(new HashSet()); } Object parseTreeSet() { consume("treeset"); return parseSet(new TreeSet()); } Object parseMap() { return parseMap(new TreeMap()); } Object parseMap(Map map) { consume("{"); while (!tok.get(i).equals("}")) { Object key = parse(); consume("="); Object value = parse(); map.put(key, value); if (tok.get(i).equals(",")) i += 2; } consume("}"); return map; } void consume(String s) { if (!tok.get(i).equals(s)) { String prevToken = i-2 >= 0 ? tok.get(i-2) : ""; String nextTokens = join(tok.subList(i, Math.min(i+4, tok.size()))); throw fail(quote(s) + " expected: " + prevToken + " " + nextTokens + " (" + i + "/" + tok.size() + ")"); } i += 2; } } return new X().parse(); } static boolean unstructure_debug; static ArrayList litlist(A... a) { return new ArrayList(Arrays.asList(a)); } static ThreadLocal loadPage_charset = new ThreadLocal(); static boolean loadPage_allowGzip = true, loadPage_debug; static boolean loadPage_anonymous; // don't send computer ID static int loadPage_verboseness = 100000; static int loadPage_retries = 60; // seconds public static String loadPageSilently(String url) { try { return loadPageSilently(new URL(loadPage_preprocess(url))); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadPageSilently(URL url) { try { IOException e = null; for (int tries = 0; tries < loadPage_retries; tries++) try { URLConnection con = url.openConnection(); return loadPage(con, url); } catch (IOException _e) { e = _e; print("Trying proxy because of: " + e); try { return loadPageThroughProxy(str(url)); } catch (Throwable e2) { print(" " + exceptionToStringShort(e2)); } sleepSeconds(1); } throw e; } catch (IOException e) { throw new RuntimeException(e); } } static String loadPage_preprocess(String url) { if (url.startsWith("tb/")) url = "tinybrain.de:8080/" + url; if (url.indexOf("://") < 0) url = "http://" + url; return url; } public static String loadPage(String url) { try { url = loadPage_preprocess(url); print("Loading: " + url); return loadPageSilently(new URL(url)); } catch (IOException e) { throw new RuntimeException(e); } } public static String loadPage(URL url) { print("Loading: " + url.toExternalForm()); return loadPageSilently(url); } public static String loadPage(URLConnection con, URL url) throws IOException { try { if (!loadPage_anonymous) { String computerID = getComputerID(); if (computerID != null) con.setRequestProperty("X-ComputerID", computerID); } if (loadPage_allowGzip) con.setRequestProperty("Accept-Encoding", "gzip"); } catch (Throwable e) {} // fails if within doPost String contentType = con.getContentType(); if (contentType == null) throw new IOException("Page could not be read: " + url); //print("Content-Type: " + contentType); String charset = loadPage_charset == null ? null : loadPage_charset.get(); if (charset == null) charset = loadPage_guessCharset(contentType); InputStream in = con.getInputStream(); if ("gzip".equals(con.getContentEncoding())) { if (loadPage_debug) print("loadPage: Using gzip."); in = new GZIPInputStream(in); } Reader r = new InputStreamReader(in, charset); StringBuilder buf = new StringBuilder(); int n = 0; while (true) { int ch = r.read(); if (ch < 0) break; buf.append((char) ch); ++n; if ((n % loadPage_verboseness) == 0) print(" " + n + " chars read"); } return buf.toString(); } static String loadPage_guessCharset(String contentType) { Pattern p = Pattern.compile("text/[a-z]+;\\s+charset=([^\\s]+)\\s*"); Matcher m = p.matcher(contentType); /* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */ return m.matches() ? m.group(1) : "ISO-8859-1"; } static int l(Object[] a) { return a == null ? 0 : a.length; } static int l(byte[] a) { return a == null ? 0 : a.length; } static int l(int[] a) { return a == null ? 0 : a.length; } static int l(float[] a) { return a == null ? 0 : a.length; } static int l(char[] a) { return a == null ? 0 : a.length; } static int l(Collection c) { return c == null ? 0 : c.size(); } static int l(Map m) { return m == null ? 0 : m.size(); } static int l(CharSequence s) { return s == null ? 0 : s.length(); } static int l(Object o) { return l((List) o); // incomplete } static Object call(Object o) { return callFunction(o); } // varargs assignment fixer for a single string array argument static Object call(Object o, String method, String[] arg) { return call(o, method, new Object[] {arg}); } static Object call(Object o, String method, Object... args) { try { if (o instanceof Class) { Method m = call_findStaticMethod((Class) o, method, args, false); m.setAccessible(true); return m.invoke(null, args); } else { Method m = call_findMethod(o, method, args, false); m.setAccessible(true); return m.invoke(o, args); } } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } static Method call_findStaticMethod(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !call_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } throw new RuntimeException("Method '" + method + "' (static) with " + args.length + " parameter(s) not found in " + _c.getName()); } static Method call_findMethod(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (m.getName().equals(method) && call_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } throw new RuntimeException("Method '" + method + "' (non-static) with " + args.length + " parameter(s) not found in " + o.getClass().getName()); } private static boolean call_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static int backtick_exitValue; static boolean backtick_verbose; public static String backtick(String cmd) { try { File outFile = File.createTempFile("_backtick", ""); File scriptFile = File.createTempFile("_backtick", isWindows() ? ".bat" : ""); String command = cmd + " >" + bashQuote(outFile.getPath()) + " 2>&1"; //Log.info("[Backtick] " + command); try { if (backtick_verbose) print("backtick: command " + command); saveTextFile(scriptFile.getPath(), command); String[] command2; if (isWindows()) command2 = new String[] { scriptFile.getPath() }; else command2 = new String[] { "/bin/bash", scriptFile.getPath() }; if (backtick_verbose) print("backtick: command2 " + structure(command2)); Process process = Runtime.getRuntime().exec(command2); try { process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e); } backtick_exitValue = process.exitValue(); if (backtick_verbose) System.out.println("Process return code: " + backtick_exitValue); String result = loadTextFile(outFile.getPath(), ""); if (backtick_verbose) print("[[\n" + result + "]]"); return result; } finally { scriptFile.delete(); } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Object first(Object list) { return ((List) list).isEmpty() ? null : ((List) list).get(0); } static A first(List list) { return list.isEmpty() ? null : list.get(0); } static A first(A[] bla) { return bla == null || bla.length == 0 ? null : bla[0]; } static A first(Iterable i) { if (i == null) return null; Iterator it = i.iterator(); return it.hasNext() ? it.next() : null; } static ArrayList ll(A... a) { return litlist(a); } static String javaQuote(String s) { return quote(s); } static String format3(String pat, Object... args) { if (args.length == 0) return pat; List tok = javaTokPlusPeriod(pat); int argidx = 0; for (int i = 1; i < tok.size(); i += 2) if (tok.get(i).equals("*")) tok.set(i, format3_formatArg(argidx < args.length ? args[argidx++] : "null")); return join(tok); } static String format3_formatArg(Object arg) { if (arg == null) return "null"; if (arg instanceof String) { String s = (String) arg; return isIdentifier(s) || isNonNegativeInteger(s) ? s : quote(s); } if (arg instanceof Integer || arg instanceof Long) return String.valueOf(arg); return quote(structure(arg)); } // class Matches is added by #752 static boolean match3(String pat, String s) { return match3(pat, s, null); } static boolean match3(String pat, String s, Matches matches) { if (s == null) return false; return match3(pat, parse3(s), matches); } static boolean match3(String pat, List toks, Matches matches) { List tokpat = parse3(pat); return match3(tokpat,toks,matches); } static boolean match3(List tokpat, List toks, Matches matches) { String[] m = match2(tokpat, toks); //print(structure(tokpat) + " on " + structure(toks) + " => " + structure(m)); if (m == null) return false; else { if (matches != null) matches.m = m; return true; } } static class Android3 { String greeting; boolean publicOverride; // optionally set this in client int startPort = 5000; // optionally set this in client Responder responder; boolean console = true; boolean daemon = false; boolean incomingSilent = false; boolean useMultiPort = true; boolean verbose; // set by system int port; long vport; DialogHandler handler; ServerSocket server; Android3(String greeting) { this.greeting = greeting;} Android3() {} synchronized void dispose() { if (server != null) { try { server.close(); } catch (IOException e) { print("[internal] " + e); } server = null; } if (vport != 0) try { /* pcall 1*/ //print("Dispoing virtual port " + vport); removeFromMultiPort(vport); vport = 0; /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } } } static abstract class Responder { abstract String answer(String s, List history); } static Android3 makeAndroid3(final String greeting) { return makeAndroid3(new Android3(greeting)); } static Android3 makeAndroid3(final String greeting, Responder responder) { Android3 android = new Android3(greeting); android.responder = responder; return makeAndroid3(android); } static Android3 makeAndroid3(final Android3 a) { if (a.responder == null) a.responder = new Responder() { String answer(String s, List history) { return callStaticAnswerMethod(s, history); } }; print(a.greeting); if (a.useMultiPort) { a.vport = addToMultiPort(a.greeting, makeAndroid3_verboseResponder(a)); if (a.vport == 1) makeAndroid3_handleConsole(a); return a; } a.handler = makeAndroid3_makeDialogHandler(a); a.port = a.daemon ? startDialogServerOnPortAboveDaemon(a.startPort, a.handler) : startDialogServerOnPortAbove(a.startPort, a.handler); a.server = startDialogServer_serverSocket; if (a.console && makeAndroid3_consoleInUse()) a.console = false; if (a.console) makeAndroid3_handleConsole(a); record(a); return a; } static void makeAndroid3_handleConsole(final Android3 a) { // Console handling stuff print("You may also type on this console."); { Thread _t_0 = new Thread() { public void run() { try { /* pcall 1*/ List history = new ArrayList(); String line; while ((line = readLine()) != null) { /*if (eq(line, "bye")) { print("> bye stranger"); history = new ArrayList(); } else*/ { history.add(line); history.add(makeAndroid3_getAnswer(line, history, a)); // prints answer on console too } } /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } } }; _t_0.start(); } } static DialogHandler makeAndroid3_makeDialogHandler(final Android3 a) { return new DialogHandler() { public void run(final DialogIO io) { if (!a.publicOverride && !(publicCommOn() || io.isLocalConnection())) { io.sendLine("Sorry, not allowed"); return; } String dialogID = randomID(8); io.sendLine(a.greeting + " / Your ID: " + dialogID); List history = new ArrayList(); while (io.isStillConnected()) { if (io.waitForLine()) { final String line = io.readLineNoBlock(); String s = dialogID + " at " + now() + ": " + quote(line); if (!a.incomingSilent) print(s); if (eq(line, "bye")) { io.sendLine("bye stranger"); return; } Matches m = new Matches(); history.add(line); String answer; if (match3("this is a continuation of talk *", s, m) || match3("hello bot! this is a continuation of talk *", s, m)) { dialogID = unquote(m.m[0]); answer = "ok"; } else try { makeAndroid3_io.set(io); answer = makeAndroid3_getAnswer(line, history, a); } finally { makeAndroid3_io.set(null); } history.add(answer); io.sendLine(answer); //appendToLog(logFile, s); } } }}; } static String makeAndroid3_getAnswer(String line, List history, Android3 a) { String answer; try { answer = makeAndroid3_fallback(line, history, a.responder.answer(line, history)); } catch (Throwable e) { e = getInnerException(e); printStackTrace(e); answer = e.toString(); } if (!a.incomingSilent) print("> " + shorten(answer, 500)); return answer; } static String makeAndroid3_fallback(String s, List history, String answer) { // Now we only do the safe thing instead of VM inspection - give out our process ID if (answer == null && match3("what is your pid", s)) return getPID(); if (answer == null && match3("what is your program id", s)) // should be fairly safe, right? return getProgramID(); if (match3("get injection id", s)) return getInjectionID(); if (answer == null) answer = "?"; if (answer.indexOf('\n') >= 0 || answer.indexOf('\r') >= 0) answer = quote(answer); return answer; } static boolean makeAndroid3_consoleInUse() { for (Object o : record_list) if (o instanceof Android3 && ((Android3) o).console) return true; return false; } static Responder makeAndroid3_verboseResponder(final Android3 a) { return new Responder() { String answer(String s, List history) { if (a.verbose) print("> " + s); String answer = a.responder.answer(s, history); if (a.verbose) print("< " + answer); return answer; } }; } static ThreadLocal makeAndroid3_io = new ThreadLocal(); static void callMain(Object c, String... args) { callOpt(c, "main", new Object[] {args}); } static boolean empty(Collection c) { return isEmpty(c); } static boolean empty(String s) { return isEmpty(s); } static boolean empty(Map map) { return map == null || map.isEmpty(); } static boolean empty(Object[] o) { return o == null || o.length == 0; } static boolean empty(Object o) { if (o instanceof Collection) return empty((Collection) o); if (o instanceof String) return empty((String) o); if (o instanceof Map) return empty((Map) o); if (o instanceof Object[]) return empty((Object[]) o); throw fail("unknown type for 'empty': " + getType(o)); } static String getServerTranspiled(String snippetID) { return getServerTranspiled(snippetID, null); } // returns "SAME" if md5 matches static String getServerTranspiled(String snippetID, String expectedMD5) { try { long id = parseSnippetID(snippetID); /*S t = getTranspilationFromBossBot(id); if (t != null) return t;*/ String text = loadPage_utf8("http://tinybrain.de:8080/tb-int/get-transpiled.php?raw=1&withlibs=1&id=" + id + "&utf8=1" + (l(expectedMD5) > 1 ? "&md5=" + urlencode(expectedMD5) : "")); if (nempty(text) && neq(text, "SAME")) saveTranspiledCode(snippetID, text); return text; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static String getStackTrace(Throwable throwable) { StringWriter writer = new StringWriter(); throwable.printStackTrace(new PrintWriter(writer)); return writer.toString(); } static String formatSnippetID(String id) { return "#" + parseSnippetID(id); } static String formatSnippetID(long id) { return "#" + id; } // extended over Class.isInstance() to handle primitive types static boolean isInstanceX(Class type, Object arg) { if (type == boolean.class) return arg instanceof Boolean; if (type == int.class) return arg instanceof Integer; if (type == long.class) return arg instanceof Long; if (type == float.class) return arg instanceof Float; if (type == short.class) return arg instanceof Short; if (type == char.class) return arg instanceof Character; if (type == byte.class) return arg instanceof Byte; if (type == double.class) return arg instanceof Double; return type.isInstance(arg); } static boolean eq(Object a, Object b) { if (a == null) return b == null; if (a.equals(b)) return true; if (a instanceof BigInteger) { if (b instanceof Integer) return a.equals(BigInteger.valueOf((Integer) b)); if (b instanceof Long) return a.equals(BigInteger.valueOf((Long) b)); } return false; } static String getSnippetFromBossBot(long snippetID) { return boss(format3("get text for *", snippetID)); } static List concatLists(List... lists) { List l = new ArrayList(); for (List list : lists) if (list != null) l.addAll(list); return l; } static List concatLists(Collection> lists) { List l = new ArrayList(); for (List list : lists) if (list != null) l.addAll(list); return l; } static JFrame setFrameIconLater(final JFrame frame, final String imageID) { if (frame != null) { /*nt*/ Thread _t_1 = new Thread("Loading Icon") { public void run() { /* in run */ try { /* pcall 1*/ /* in thread */ final Image i = imageIcon(imageID).getImage(); swingLater(new Runnable() { public void run() { try { frame.setIconImage(i); } catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); } } }); /* in thread */ /* pcall 2 */ } catch (Throwable __e) { printStackTrace(__e); } /* in run */ } }; _t_1.start(); } return frame; } static Set keys(Map map) { return map.keySet(); } static Set keys(Object map) { return keys((Map) map); } static List emptyList() { return new ArrayList(); //ret Collections.emptyList(); } // try to get our current process ID static String getPID() { String name = ManagementFactory.getRuntimeMXBean().getName(); return name.replaceAll("@.*", ""); } public static String unquote(String s) { if (s == null) return null; if (s.startsWith("[")) { int i = 1; while (i < s.length() && s.charAt(i) == '=') ++i; if (i < s.length() && s.charAt(i) == '[') { String m = s.substring(1, i); if (s.endsWith("]" + m + "]")) return s.substring(i+1, s.length()-i-1); } } if (s.startsWith("\"") /*&& s.endsWith("\"")*/ && s.length() > 1) { String st = s.substring(1, s.endsWith("\"") ? s.length()-1 : s.length()); StringBuilder sb = new StringBuilder(st.length()); for (int i = 0; i < st.length(); i++) { char ch = st.charAt(i); if (ch == '\\') { char nextChar = (i == st.length() - 1) ? '\\' : st .charAt(i + 1); // Octal escape? if (nextChar >= '0' && nextChar <= '7') { String code = "" + nextChar; i++; if ((i < st.length() - 1) && st.charAt(i + 1) >= '0' && st.charAt(i + 1) <= '7') { code += st.charAt(i + 1); i++; if ((i < st.length() - 1) && st.charAt(i + 1) >= '0' && st.charAt(i + 1) <= '7') { code += st.charAt(i + 1); i++; } } sb.append((char) Integer.parseInt(code, 8)); continue; } switch (nextChar) { case '\\': ch = '\\'; break; case 'b': ch = '\b'; break; case 'f': ch = '\f'; break; case 'n': ch = '\n'; break; case 'r': ch = '\r'; break; case 't': ch = '\t'; break; case '\"': ch = '\"'; break; case '\'': ch = '\''; break; // Hex Unicode: u???? case 'u': if (i >= st.length() - 5) { ch = 'u'; break; } int code = Integer.parseInt( "" + st.charAt(i + 2) + st.charAt(i + 3) + st.charAt(i + 4) + st.charAt(i + 5), 16); sb.append(Character.toChars(code)); i += 5; continue; default: ch = nextChar; // added by Stefan } i++; } sb.append(ch); } return sb.toString(); } else return s; // return original } // compile JavaX source, load classes & return main class // src can be a snippet ID or actual source code // TODO: record injection? static Class hotwire(String src) { try { Class j = getJavaX(); synchronized(j) { // hopefully this goes well... List libraries = new ArrayList(); File srcDir = (File) call(j, "transpileMain", src, libraries); if (srcDir == null) throw fail("transpileMain returned null (src=" + quote(src) + ")"); Object androidContext = get(j, "androidContext"); if (androidContext != null) return (Class) call(j, "loadx2android", srcDir, src); File classesDir = (File) call(j, "TempDirMaker_make"); String javacOutput = (String) call(j, "compileJava", srcDir, libraries, classesDir); System.out.println(javacOutput); URL[] urls = new URL[libraries.size()+1]; urls[0] = classesDir.toURI().toURL(); for (int i = 0; i < libraries.size(); i++) urls[i+1] = libraries.get(i).toURI().toURL(); // make class loader URLClassLoader classLoader = new URLClassLoader(urls); // load & return main class Class theClass = classLoader.loadClass("main"); callOpt(j, "registerSourceCode", theClass, loadTextFile(new File(srcDir, "main.java"))); call(j, "setVars", theClass, isSnippetID(src) ? src: null); if (isSnippetID(src)) callOpt(j, "addInstance", src, theClass); if (!_inCore()) hotwire_copyOver(theClass); return theClass; } } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } static void smartSet(Field f, Object o, Object value) throws Exception { f.setAccessible(true); // take care of common case (long to int) if (f.getType() == int.class && value instanceof Long) value = ((Long) value).intValue(); f.set(o, value); } static String structure(Object o) { HashSet refd = new HashSet(); return structure_2(structure_1(o, 0, new IdentityHashMap(), refd), refd); } // leave to false, unless unstructure() breaks static boolean structure_allowShortening = false; static String structure_1(Object o, int stringSizeLimit, IdentityHashMap seen, HashSet refd) { if (o == null) return "null"; // these are never back-referenced (for readability) if (o instanceof String) return quote(stringSizeLimit != 0 ? shorten((String) o, stringSizeLimit) : (String) o); if (o instanceof BigInteger) return "bigint(" + o + ")"; if (o instanceof Double) return "d(" + quote(str(o)) + ")"; if (o instanceof Float) return "f " + quote(str(o)); if (o instanceof Long) return o + "L"; if (o instanceof Integer) return str(o); if (o instanceof Boolean) return ((Boolean) o).booleanValue() ? "t" : "f"; if (o instanceof Character) return quoteCharacter((Character) o); if (o instanceof File) return "File " + quote(((File) o).getPath()); // referencable objects follow Integer ref = seen.get(o); if (ref != null) { refd.add(ref); return "r" + ref; } ref = seen.size()+1; seen.put(o, ref); String r = "m" + ref + " "; // marker String name = o.getClass().getName(); StringBuilder buf = new StringBuilder(); if (o instanceof HashSet) return r + "hashset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd); if (o instanceof TreeSet) return r + "treeset " + structure_1(new ArrayList((Set) o), stringSizeLimit, seen, refd); if (o instanceof Collection) { for (Object x : (Collection) o) { if (buf.length() != 0) buf.append(", "); buf.append(structure_1(x, stringSizeLimit, seen, refd)); } return r + "[" + buf + "]"; } if (o instanceof Map) { for (Object e : ((Map) o).entrySet()) { if (buf.length() != 0) buf.append(", "); buf.append(structure_1(((Map.Entry) e).getKey(), stringSizeLimit, seen, refd)); buf.append("="); buf.append(structure_1(((Map.Entry) e).getValue(), stringSizeLimit, seen, refd)); } return r + (o instanceof HashMap ? "hashmap" : "") + "{" + buf + "}"; } if (o.getClass().isArray()) { if (o instanceof byte[]) return "ba " + quote(bytesToHex((byte[]) o)); int n = Array.getLength(o); for (int i = 0; i < n; i++) { if (buf.length() != 0) buf.append(", "); buf.append(structure_1(Array.get(o, i), stringSizeLimit, seen, refd)); } return r + "array{" + buf + "}"; } if (o instanceof Class) return r + "class(" + quote(((Class) o).getName()) + ")"; if (o instanceof Throwable) return r + "exception(" + quote(((Throwable) o).getMessage()) + ")"; if (o instanceof BitSet) { BitSet bs = (BitSet) o; for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { if (buf.length() != 0) buf.append(", "); buf.append(i); } return "bitset{" + buf + "}"; } // Need more cases? This should cover all library classes... if (name.startsWith("java.") || name.startsWith("javax.")) return r + String.valueOf(o); String shortName = o.getClass().getName().replaceAll("^main\\$", ""); if (shortName.equals("Lisp")) { buf.append("l(" + structure_1(getOpt(o, "head"), stringSizeLimit, seen, refd)); List args = (List) ( getOpt(o, "args")); if (nempty(args)) for (int i = 0; i < l(args); i++) { buf.append(", "); Object arg = args.get(i); // sweet shortening if (arg != null && eq(arg.getClass().getName(), "main$Lisp") && isTrue(call(arg, "isEmpty"))) arg = get(arg, "head"); buf.append(structure_1(arg, stringSizeLimit, seen, refd)); } buf.append(")"); return r + str(buf); } int numFields = 0; String fieldName = ""; if (shortName.equals("DynamicObject")) { shortName = (String) get_raw(o, "className"); Map fieldValues = (Map) get_raw(o, "fieldValues"); for (String _fieldName : fieldValues.keySet()) { fieldName = _fieldName; Object value = fieldValues.get(fieldName); if (value != null) { if (buf.length() != 0) buf.append(", "); buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd)); } ++numFields; } } else { // regular class Class c = o.getClass(); while (c != Object.class) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { if ((field.getModifiers() & Modifier.STATIC) != 0) continue; fieldName = field.getName(); // skip outer object reference if (fieldName.indexOf("$") >= 0) continue; Object value; try { field.setAccessible(true); value = field.get(o); } catch (Exception e) { value = "?"; } // put special cases here... if (value != null) { if (buf.length() != 0) buf.append(", "); buf.append(fieldName + "=" + structure_1(value, stringSizeLimit, seen, refd)); } ++numFields; } c = c.getSuperclass(); } } String b = buf.toString(); if (numFields == 1 && structure_allowShortening) b = b.replaceAll("^" + fieldName + "=", ""); // drop field name if only one String s = shortName; if (buf.length() != 0) s += "(" + b + ")"; return r + s; } // drop unused markers static String structure_2(String s, HashSet refd) { List tok = javaTok(s); StringBuilder out = new StringBuilder(); for (int i = 1; i < l(tok); i += 2) { String t = tok.get(i); if (t.startsWith("m") && isInteger(t.substring(1)) && !refd.contains(parseInt(t.substring(1)))) continue; out.append(t).append(tok.get(i+1)); } return str(out); } static boolean master() { return webAuthed() || litlist("stefanreich", "bgrgndz", "okhan", "mrshutco").contains(getUserName()); } static int parseInt(String s) { return empty(s) ? 0 : Integer.parseInt(s); } static boolean autoVMExit_debug; // TODO: don't ship the class in clients anymore, it's in JavaX // anyway. static synchronized void autoVMExit() { if (!_inCore() && hasMethod(getJavaX(), "autoVMExit")) { if (autoVMExit_debug) print("autoVMExit -> core"); call(getJavaX(), "autoVMExit"); // do it centrally } else AutoVMExit.install(); } static class AutoVMExit extends TimerTask { static boolean installed; static boolean disabled; int lastObjectCount = -1; static java.util.Timer timer; static int firstDelay = 30000; static int delay = 5000; public static void install() { if (!installed) { installed = true; if (!disabled) { timer = new java.util.Timer("AutoVMExit"); timer.scheduleAtFixedRate(new AutoVMExit(), firstDelay, delay); } } } /** Looks for objects that give us a reason to keep the VM alive. * Right now we count windows and tray icons. */ public void run() { int objectCount = 0; // Scan for windows Window[] windowList = Window.getWindows(); for (Window window : windowList) { if (window.isVisible()) ++objectCount; } // Scan for tray icons try { objectCount += SystemTray.getSystemTray().getTrayIcons().length; } catch (Throwable e) { // ignore } // Scan for JavaFX stages try { objectCount += l((List) call(_getClass("com.sun.javafx.robot.impl.FXRobotHelper"), "getStages")); } catch (Throwable _e) { } //System.out.println("Windows: " + objectCount); if (objectCount == 0 && lastObjectCount == 0) { System.out.println("AutoVMExit: No windows open or tray icons installed - exiting"); System.exit(0); } lastObjectCount = objectCount; } public static void disable() { disabled = true; if (timer != null) timer.cancel(); } public static int getFirstDelay() { return firstDelay; } public static void setFirstDelay(int firstDelay) { AutoVMExit.firstDelay = firstDelay; } public static int getDelay() { return delay; } public static void setDelay(int delay) { AutoVMExit.delay = delay; } } static int randomID_defaultLength = 12; static String randomID(int length) { return makeRandomID(length); } static String randomID() { return randomID(randomID_defaultLength); } static String makeResponder_callAnswerMethod(Object bot, String s, List history) { String answer = (String) callOpt(bot, "answer", s, history); if (answer == null) answer = (String) callOpt(bot, "answer", s); return answer; } static Responder makeResponder(final Object bot) { if (bot instanceof Responder) return (Responder) bot; return new Responder() { String answer(String s, List history) { return makeResponder_callAnswerMethod(bot, s, history); } }; } static Object getOpt(Object o, String field) { if (o instanceof String) o = getBot ((String) o); if (o == null) return null; if (o instanceof Class) return getOpt((Class) o, field); if (o.getClass().getName().equals("main$DynamicObject")) return ((Map) getOpt_raw(o, "fieldValues")).get(field); if (o instanceof Map) return ((Map) o).get(field); return getOpt_raw(o, field); } static Object getOpt_raw(Object o, String field) { try { Field f = getOpt_findField(o.getClass(), field); if (f == null) return null; f.setAccessible(true); return f.get(o); } catch (Exception e) { throw new RuntimeException(e); } } static Object getOpt(Class c, String field) { try { if (c == null) return null; Field f = getOpt_findStaticField(c, field); if (f == null) return null; f.setAccessible(true); return f.get(null); } catch (Exception e) { throw new RuntimeException(e); } } static Field getOpt_findStaticField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & Modifier.STATIC) != 0) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static Field getOpt_findField(Class c, String field) { Class _c = c; do { for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field)) return f; _c = _c.getSuperclass(); } while (_c != null); return null; } static JFrame consoleFrame() { return (JFrame) getOpt(get(getJavaX(), "console"), "frame"); } static String urlencode(String x) { try { return URLEncoder.encode(unnull(x), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } static Object callF(Object f, Object... args) { return callFunction(f, args); } static Object callFunction(Object f, Object... args) { if (f == null) return null; if (f instanceof Runnable) { ((Runnable) f).run(); return null; } else if (f instanceof String) return call(mc(), (String) f, args); else return call(f, "get", args); //else throw fail("Can't call a " + getClassName(f)); } static String shorten(String s, int max) { if (s == null) return ""; return s.length() <= max ? s : s.substring(0, Math.min(s.length(), max)) + "..."; } static List record_list = synchroList(); static void record(Object o) { record_list.add(o); } static Object getBot(String botID) { return callOpt(getMainBot(), "getBot", botID); } static String quoteCharacter(char c) { if (c == '\'') return "'\\''"; if (c == '\\') return "'\\\\'"; return "'" + c + "'"; } static String loadPage_utf8(String url) { loadPage_charset.set("UTF-8"); try { return loadPage(url); } finally { loadPage_charset.set(null); } } static void printStackTrace(Throwable e) { // we go to system.out now - system.err is nonsense print(getStackTrace(e)); } static void printStackTrace() { printStackTrace(new Throwable()); } static byte[] hexToBytes(String s) { int n = l(s) / 2; byte[] bytes = new byte[n]; for (int i = 0; i < n; i++) bytes[i] = (byte) parseHexByte(substring(s, i*2, i*2+2)); return bytes; } // currently finds only inner classes of class "main" // returns null on not found // this is the simple version that is not case-tolerant static Class findClass(String name) { try { return Class.forName("main$" + name); } catch (ClassNotFoundException e) { return null; } } static void removeFromMultiPort(long vport) { for (Object port : getMultiPorts()) call(port, "removePort", vport); } static String str(Object o) { return String.valueOf(o); } static String getType(Object o) { return getClassName(o); } static void listSet(List l, int i, A a, A emptyElement) { if (i < 0) return; while (i >= l(l)) l.add(emptyElement); l.set(i, a); } static boolean isJavaIdentifier(String s) { if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) return false; for (int i = 1; i < s.length(); i++) if (!Character.isJavaIdentifierPart(s.charAt(i))) return false; return true; } static Object addToMultiPort_responder; static long addToMultiPort(final String botName) { return addToMultiPort(botName, new Object() { public String answer(String s, List history) { String answer = (String) ( callOpt(getMainClass(), "answer", s, history)); if (answer != null) return answer; answer = (String) callOpt(getMainClass(), "answer", s); if (answer != null) return answer; if (match3("get injection id", s)) return getInjectionID(); return null; } }); } static long addToMultiPort(final String botName, final Object responder) { print(botName); addToMultiPort_responder = responder; startMultiPort(); List ports = getMultiPorts(); if (ports == null) return 0; if (ports.isEmpty()) throw fail("No multiports!"); if (ports.size() > 1) print("Multiple multi-ports. Using last one."); Object port = last(ports); Object responder2 = new Object() { public String answer(String s, List history) { if (match3("get injection id", s)) return getInjectionID(); if (match3("your name", s)) return botName; return (String) call(responder, "answer", s, history); } }; record(responder2); return (Long) call(port, "addResponder", botName, responder2); } static String programID; static String getProgramID() { return nempty(programID) ? formatSnippetID(programID) : "?"; } // TODO: ask JavaX instead static String getProgramID(Class c) { String id = (String) getOpt(c, "programID"); if (nempty(id)) return formatSnippetID(id); return "?"; } static String getProgramID(Object o) { return getProgramID(getMainClass(o)); } static String unnull(String s) { return s == null ? "" : s; } static List unnull(List l) { return l == null ? emptyList() : l; } static Iterable unnull(Iterable i) { return i == null ? emptyList() : i; } static Object[] unnull(Object[] a) { return a == null ? new Object[0] : a; } // replacement for class JavaTok // maybe incomplete, might want to add floating point numbers // todo also: extended multi-line strings static int javaTok_n, javaTok_elements; static boolean javaTok_opt; static List javaTok(String s) { return javaTok(s, null); } static List javaTok(String s, List existing) { ++javaTok_n; int nExisting = javaTok_opt && existing != null ? existing.size() : 0; List tok = existing != null ? new ArrayList(nExisting) : new ArrayList(); int l = s.length(); int i = 0, n = 0; while (i < l) { int j = i; char c; String cc; // scan for whitespace while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j+2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/")); j = Math.min(j+2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(quickSubstring(s, i, j)); ++n; i = j; if (i >= l) break; c = s.charAt(i); // cc is not needed in rest of loop body cc = s.substring(i, Math.min(i+2, l)); // scan for non-whitespace if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { if (s.charAt(j) == opener || s.charAt(j) == '\n') { // end at \n to not propagate unclosed string literal errors ++j; break; } else if (s.charAt(j) == '\\' && j+1 < l) j += 2; else ++j; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || "'".indexOf(s.charAt(j)) >= 0)); // for stuff like "don't" else if (Character.isDigit(c)) { do ++j; while (j < l && Character.isDigit(s.charAt(j))); if (j < l && s.charAt(j) == 'L') ++j; // Long constants like 1L } else if (cc.equals("[[")) { do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]")); j = Math.min(j+2, l); } else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') { do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]")); j = Math.min(j+3, l); } else ++j; if (n < nExisting && javaTok_isCopyable(existing.get(n), s, i, j)) tok.add(existing.get(n)); else tok.add(quickSubstring(s, i, j)); ++n; i = j; } if ((tok.size() % 2) == 0) tok.add(""); javaTok_elements += tok.size(); return tok; } static List javaTok(List tok) { return javaTok(join(tok), tok); } static boolean javaTok_isCopyable(String t, String s, int i, int j) { return t.length() == j-i && s.regionMatches(i, t, 0, j-i); // << could be left out, but that's brave } static List parse3(String s) { return dropPunctuation(javaTokPlusPeriod(s)); } static int min(int a, int b) { return Math.min(a, b); } static double min(double[] c) { double x = Double.MAX_VALUE; for (double d : c) x = Math.min(x, d); return x; } static byte min(byte[] c) { byte x = 127; for (byte d : c) if (d < x) x = d; return x; } static Object newObject(Class c, Object... args) { return nuObject(c, args); } static Object newObject(String className, Object... args) { return nuObject(className, args); } static boolean isLongConstant(String s) { if (!s.endsWith("L")) return false; s = s.substring(0, l(s)-1); return isInteger(s); } static Class __javax; static Class getJavaX() { return __javax; } static List subList(List l, int startIndex) { return subList(l, startIndex, l(l)); } static List subList(List l, int startIndex, int endIndex) { startIndex = max(0, min(l(l), startIndex)); endIndex = max(0, min(l(l), endIndex)); if (startIndex > endIndex) return litlist(); return l.subList(startIndex, endIndex); } static int max(int a, int b) { return Math.max(a, b); } static long max(int a, long b) { return Math.max((long) a, b); } static long max(long a, long b) { return Math.max(a, b); } static double max(int a, double b) { return Math.max((double) a, b); } static int max(Collection c) { int x = Integer.MIN_VALUE; for (int i : c) x = max(x, i); return x; } static double max(double[] c) { if (c.length == 0) return Double.MIN_VALUE; double x = c[0]; for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]); return x; } static byte max(byte[] c) { byte x = -128; for (byte d : c) if (d > x) x = d; return x; } static String exceptionToStringShort(Throwable e) { e = getInnerException(e); String msg = unnull(e.getMessage()); if (msg.indexOf("Error") < 0 && msg.indexOf("Exception") < 0) return baseClassName(e) + ": " + msg; else return msg; } static Throwable getInnerException(Throwable e) { while (e.getCause() != null) e = e.getCause(); return e; } // hmm, this shouldn't call functions really. That was just // for coroutines. static boolean isTrue(Object o) { if (o instanceof Boolean) return ((Boolean) o).booleanValue(); if (o == null) return false; return ((Boolean) callF(o)).booleanValue(); } static boolean isTrue(Object pred, Object arg) { return booleanValue(callF(pred, arg)); } static long parseLong(String s) { if (s == null) return 0; return Long.parseLong(dropSuffix("L", s)); } static long parseLong(Object s) { return Long.parseLong((String) s); } static String loadPageThroughProxy(String url) { adbForward(); DialogIO io = talkToOpt("localhost", 4995); // Test ADB Bridge if (io == null) io = talkToOpt(gateway(), 4999); // Phone, Public Comm Bot if (io == null) return null; String answer = unquote(io.ask(forward("Awareness", format("loadPage *", url)))); io.close(); if (swic(answer, "ok ")) return answer.substring(3); throw fail(answer); } static void saveTranspiledCode(String progID, String code) { saveTextFile(new File(getCodeProgramDir(progID), "Transpilation"), code); } static boolean isIdentifier(String s) { return isJavaIdentifier(s); } // match2 matches multiple "*" (matches a single token) wildcards and zero or one "..." wildcards (matches multiple tokens) static String[] match2(List pat, List tok) { // standard case (no ...) int i = pat.indexOf("..."); if (i < 0) return match2_match(pat, tok); pat = new ArrayList(pat); // We're modifying it, so copy first pat.set(i, "*"); while (pat.size() < tok.size()) { pat.add(i, "*"); pat.add(i+1, ""); // doesn't matter } return match2_match(pat, tok); } static String[] match2_match(List pat, List tok) { List result = new ArrayList(); if (pat.size() != tok.size()) { /*if (debug) print("Size mismatch: " + structure(pat) + " vs " + structure(tok));*/ return null; } for (int i = 1; i < pat.size(); i += 2) { String p = pat.get(i), t = tok.get(i); /*if (debug) print("Checking " + p + " against " + t);*/ if (eq(p, "*")) result.add(t); else if (!equalsIgnoreCase(unquote(p), unquote(t))) // bold change - match quoted and unquoted now return null; } return result.toArray(new String[result.size()]); } static void hotwire_copyOver(Class c) { synchronized(StringBuffer.class) { for (String field : litlist("print_log", "print_silent", "androidContext")) { Object o = getOpt(mc(), field); if (o != null) setOpt(c, field, o); } Object mainBot = getMainBot(); if (mainBot != null) setOpt(c, "mainBot", mainBot); setOpt(c, "creator_class", new WeakReference(mc())); } } static Class _getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } static Class _getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } static Class _getClass(Object realm, String name) { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static boolean publicCommOn() { return "1".equals(loadTextFile(new File(userHome(), ".javax/public-communication"))); } static String getUserName() { return (String) callOpt(getMainBot(), "getUserName"); } static boolean neq(Object a, Object b) { return !eq(a, b); } static boolean isNonNegativeInteger(String s) { return s != null && Pattern.matches("\\d+", s); } static A last(List l) { return l.isEmpty() ? null : l.get(l.size()-1); } static boolean hasMethod(Object o, String method, Object... args) { return findMethod(o, method, args) != null; } static Object nuObject(String className, Object... args) { try { return nuObject(Class.forName(className), args); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Object nuObject(Object realm, String className, Object... args) { return nuObject(_getClass(realm, className), args); } static A nuObject(Class c, Object... args) { try { Constructor m = nuObject_findConstructor(c, args); m.setAccessible(true); return (A) m.newInstance(args); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Constructor nuObject_findConstructor(Class c, Object... args) { for (Constructor m : c.getDeclaredConstructors()) { if (!nuObject_checkArgs(m.getParameterTypes(), args, false)) continue; return m; } throw new RuntimeException("Constructor with " + args.length + " matching parameter(s) not found in " + c.getName()); } static boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) { if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } // This is made for NL parsing. // It's javaTok extended with "..." token, "$n" and "#n" and // special quotes (which are converted to normal ones). static List javaTokPlusPeriod(String s) { List tok = new ArrayList(); int l = s.length(); int i = 0; while (i < l) { int j = i; char c; String cc; // scan for whitespace while (j < l) { c = s.charAt(j); cc = s.substring(j, Math.min(j+2, l)); if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++j; else if (cc.equals("/*")) { do ++j; while (j < l && !s.substring(j, Math.min(j+2, l)).equals("*/")); j = Math.min(j+2, l); } else if (cc.equals("//")) { do ++j; while (j < l && "\r\n".indexOf(s.charAt(j)) < 0); } else break; } tok.add(s.substring(i, j)); i = j; if (i >= l) break; c = s.charAt(i); cc = s.substring(i, Math.min(i+2, l)); // scan for non-whitespace if (c == '\u201C' || c == '\u201D') c = '"'; // normalize quotes if (c == '\'' || c == '"') { char opener = c; ++j; while (j < l) { char _c = s.charAt(j); if (_c == '\u201C' || _c == '\u201D') _c = '"'; // normalize quotes if (_c == opener) { ++j; break; } else if (s.charAt(j) == '\\' && j+1 < l) j += 2; else ++j; } if (j-1 >= i+1) { tok.add(opener + s.substring(i+1, j-1) + opener); i = j; continue; } } else if (Character.isJavaIdentifierStart(c)) do ++j; while (j < l && (Character.isJavaIdentifierPart(s.charAt(j)) || s.charAt(j) == '\'')); // for things like "this one's" else if (Character.isDigit(c)) do ++j; while (j < l && Character.isDigit(s.charAt(j))); else if (cc.equals("[[")) { do ++j; while (j+1 < l && !s.substring(j, j+2).equals("]]")); j = Math.min(j+2, l); } else if (cc.equals("[=") && i+2 < l && s.charAt(i+2) == '[') { do ++j; while (j+2 < l && !s.substring(j, j+3).equals("]=]")); j = Math.min(j+3, l); } else if (s.substring(j, Math.min(j+3, l)).equals("...")) j += 3; else if (c == '$' || c == '#') do ++j; while (j < l && Character.isDigit(s.charAt(j))); else ++j; tok.add(s.substring(i, j)); i = j; } if ((tok.size() % 2) == 0) tok.add(""); return tok; } static void sleepSeconds(double s) { if (s > 0) sleep(round(s*1000)); } static Object callOpt(Object o) { if (o == null) return null; return callF(o); } static Object callOpt(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Method m = callOpt_findStaticMethod((Class) o, method, args, false); if (m == null) return null; m.setAccessible(true); return m.invoke(null, args); } else { Method m = callOpt_findMethod(o, method, args, false); if (m == null) return null; m.setAccessible(true); return m.invoke(o, args); } } catch (Exception e) { throw new RuntimeException(e); } } static Method callOpt_findStaticMethod(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !callOpt_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } return null; } static Method callOpt_findMethod(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (m.getName().equals(method) && callOpt_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } return null; } private static boolean callOpt_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static double parseDouble(String s) { return Double.parseDouble(s); } static AtomicInteger dialogServer_clients = new AtomicInteger(); static boolean dialogServer_printConnects; static Set dialogServer_knownClients = synchroTreeSet(); static int startDialogServerOnPortAbove(int port, DialogHandler handler) { while (!startDialogServerIfPortAvailable(port, handler)) ++port; return port; } static int startDialogServerOnPortAboveDaemon(int port, DialogHandler handler) { while (!startDialogServerIfPortAvailable(port, handler, true)) ++port; return port; } static void startDialogServer(int port, DialogHandler handler) { if (!startDialogServerIfPortAvailable(port, handler)) throw fail("Can't start dialog server on port " + port); } static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler) { return startDialogServerIfPortAvailable(port, handler, false); } static ServerSocket startDialogServer_serverSocket; static boolean startDialogServerIfPortAvailable(int port, final DialogHandler handler, boolean daemon) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(port); } catch (IOException e) { // probably the port number is used - let's assume there already is a chat server. return false; } final ServerSocket _serverSocket = serverSocket; startDialogServer_serverSocket = serverSocket; Thread thread = new Thread("Socket accept port " + port) { public void run() { try { while (true) { try { final Socket s = _serverSocket.accept(); String client = s.getInetAddress().toString(); if (!dialogServer_knownClients.contains(client) && neq(client, "/127.0.0.1")) { print("connect from " + client + " - clients: " + dialogServer_clients.incrementAndGet()); dialogServer_knownClients.add(client); } String threadName = "Handling client " + s.getInetAddress(); Thread t2 = new Thread(threadName) { public void run() { try { final Writer w = new OutputStreamWriter(s.getOutputStream(), "UTF-8"); final BufferedReader in = new BufferedReader( new InputStreamReader(s.getInputStream(), "UTF-8")); DialogIO io = new DialogIO() { // This should be the same as #1001076 (talkTo) boolean isLocalConnection() { return s.getInetAddress().isLoopbackAddress(); } boolean isStillConnected() { return !(eos || s.isClosed()); } void sendLine(String line) { try { w.write(line + "\n"); w.flush(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} String readLineImpl() { try { return in.readLine(); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} void close() { try { s.close(); } catch (IOException e) { // whatever } } Socket getSocket() { return s; } }; try { handler.run(io); } finally { s.close(); } } catch (IOException e) { print("[internal] " + e); } finally { //print("client disconnect - " + dialogServer_clients.decrementAndGet() + " remaining"); } } }; // Thread t2 t2.setDaemon(true); // ? t2.start(); } catch (SocketTimeoutException e) { } } } catch (IOException e) { print("[internal] " + e); } }}; if (daemon) thread.setDaemon(true); thread.start(); print("Dialog server on port " + port + " started."); return true; } static ImageIcon imageIcon(String imageID) { try { return new ImageIcon(loadBinarySnippet(imageID).toURI().toURL()); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static ImageIcon imageIcon(BufferedImage img) { return new ImageIcon(img); } static boolean webAuthed() { return eq(Boolean.TRUE, callOpt(getBot("#1002590"), "currentHttpRequestAuthorized")); } static boolean isEmpty(Collection c) { return c == null || c.isEmpty(); } static boolean isEmpty(CharSequence s) { return s == null || s.length() == 0; } static boolean isEmpty(Object[] a) { return a == null || a.length == 0; } static boolean isEmpty(Map map) { return map == null || map.isEmpty(); } static boolean nempty(Collection c) { return !isEmpty(c); } static boolean nempty(CharSequence s) { return !isEmpty(s); } static boolean nempty(Object[] o) { return !isEmpty(o); } static boolean nempty(Map m) { return !isEmpty(m); } static boolean nempty(Iterator i) { return i != null && i.hasNext(); } static String callStaticAnswerMethod(List bots, String s) { for (Class c : bots) try { String answer = callStaticAnswerMethod(c, s); if (!empty(answer)) return answer; } catch (Throwable e) { print("Error calling " + getProgramID(c)); e.printStackTrace(); } return null; } static String callStaticAnswerMethod(Class c, String s) { String answer = (String) callOpt(c, "answer", s, litlist(s)); if (answer == null) answer = (String) callOpt(c, "answer", s); return emptyToNull(answer); } static String callStaticAnswerMethod(String s, List history) { String answer = (String) callOpt(getMainClass(), "answer", s, history); if (answer == null) answer = (String) callOpt(getMainClass(), "answer", s); return emptyToNull(answer); } static char unquoteCharacter(String s) { assertTrue(s.startsWith("'") && s.length() > 1); return unquote("\"" + s.substring(1, s.endsWith("'") ? s.length()-1 : s.length()) + "\"").charAt(0); } static boolean equalsIgnoreCase(String a, String b) { return a == null ? b == null : a.equalsIgnoreCase(b); } static DialogIO talkToOpt(String host, int port) { try { return talkTo(host, port); } catch (Throwable e) { return null; } } static File loadBinarySnippet(String snippetID) { try { long id = parseSnippetID(snippetID); File f = DiskSnippetCache_getLibrary(id); if (f == null) { byte[] data = loadDataSnippetImpl(snippetID); DiskSnippetCache_putLibrary(id, data); f = DiskSnippetCache_getLibrary(id); } return f; } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static String quickSubstring(String s, int i, int j) { if (i == j) return ""; return s.substring(i, j); } static Set synchroTreeSet() { return Collections.synchronizedSet(new TreeSet()); } static boolean swic(String a, String b) { return startsWithIgnoreCase(a, b); } static Object mainBot; static Object getMainBot() { return mainBot; } static void assertTrue(Object o) { assertEquals(true, o); } static boolean assertTrue(String msg, boolean b) { if (!b) throw fail(msg); return b; } static boolean assertTrue(boolean b) { if (!b) throw fail("oops"); return b; } static String baseClassName(String className) { return substring(className, className.lastIndexOf('.')); } static String baseClassName(Object o) { return baseClassName(getClassName(o)); } static String forward(String bot, String msg, Object... args) { return format("please forward to bot *: *", bot, format(msg, args)); } static Class getClass(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { return null; } } static Class getClass(Object o) { return o instanceof Class ? (Class) o : o.getClass(); } static Class getClass(Object realm, String name) { try { try { return getClass(realm).getClassLoader().loadClass(classNameToVM(name)); } catch (ClassNotFoundException e) { return null; } } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static Class mc() { return getMainClass(); } static File getCodeProgramDir() { return getCodeProgramDir(getProgramID()); } static File getCodeProgramDir(String snippetID) { return new File(userHome(), "JavaX-Code/" + formatSnippetID(snippetID)); } static File getCodeProgramDir(long snippetID) { return getCodeProgramDir(formatSnippetID(snippetID)); } static String classNameToVM(String name) { return name.replace(".", "$"); } static String format(String pat, Object... args) { return format3(pat, args); } static String emptyToNull(String s) { return eq(s, "") ? null : s; } static TimedCache adbForward_list = new TimedCache(10); static void adbForward() { if (!isOnPATH("adb")) print("adb not on path"); else { backtick_verbose = true; String list = adbForward_list.get(new Object() { Object get() { return backtick("adb forward --list"); }}); if (!contains(list, "4995")) backtick("adb forward tcp:4995 tcp:4999"); } } static boolean booleanValue(Object o) { return eq(true, o); } static String getClassName(Object o) { return o == null ? "null" : o.getClass().getName(); } static String substring(String s, int x) { return safeSubstring(s, x); } static String substring(String s, int x, int y) { return safeSubstring(s, x, y); } static Method findMethod(Object o, String method, Object... args) { try { if (o == null) return null; if (o instanceof Class) { Method m = findMethod_static((Class) o, method, args, false); if (m == null) return null; m.setAccessible(true); return m; } else { Method m = findMethod_instance(o, method, args, false); if (m == null) return null; m.setAccessible(true); return m; } } catch (Exception e) { throw new RuntimeException(e); } } static Method findMethod_static(Class c, String method, Object[] args, boolean debug) { Class _c = c; while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (!m.getName().equals(method)) { if (debug) System.out.println("Method name mismatch: " + method); continue; } if ((m.getModifiers() & Modifier.STATIC) == 0 || !findMethod_checkArgs(m, args, debug)) continue; return m; } c = c.getSuperclass(); } return null; } static Method findMethod_instance(Object o, String method, Object[] args, boolean debug) { Class c = o.getClass(); while (c != null) { for (Method m : c.getDeclaredMethods()) { if (debug) System.out.println("Checking method " + m.getName() + " with " + m.getParameterTypes().length + " parameters");; if (m.getName().equals(method) && findMethod_checkArgs(m, args, debug)) return m; } c = c.getSuperclass(); } return null; } static boolean findMethod_checkArgs(Method m, Object[] args, boolean debug) { Class[] types = m.getParameterTypes(); if (types.length != args.length) { if (debug) System.out.println("Bad parameter length: " + args.length + " vs " + types.length); return false; } for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) { if (debug) System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]); return false; } return true; } static List synchroList() { return Collections.synchronizedList(new ArrayList()); } static List synchroList(List l) { return Collections.synchronizedList(l); } static List dropPunctuation_keep = litlist("*", "<", ">"); static List dropPunctuation(List tok) { tok = new ArrayList(tok); for (int i = 1; i < tok.size(); i += 2) { String t = tok.get(i); if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation_keep.contains(t)) { tok.set(i-1, tok.get(i-1) + tok.get(i+1)); tok.remove(i); tok.remove(i); i -= 2; } } return tok; } static String dropPunctuation(String s) { return join(dropPunctuation(nlTok(s))); } static String dropSuffix(String suffix, String s) { return s.endsWith(suffix) ? s.substring(0, l(s)-l(suffix)) : s; } static int parseHexByte(String s) { return Integer.parseInt(s, 16); } static long round(double d) { return Math.round(d); } // start multi-port if none exists in current VM. static void startMultiPort() { List mp = getMultiPorts(); if (mp != null && mp.isEmpty()) callMain(hotwire("#1001672")); } static String gateway() { return first(detectGateways()); } static boolean contains(Collection c, Object o) { return c != null && c.contains(o); } static boolean contains(Object[] x, Object o) { if (x != null) for (Object a : x) if (eq(a, o)) return true; return false; } static boolean contains(String s, char c) { return s != null && s.indexOf(c) >= 0; } static boolean contains(String s, String b) { return s != null && s.indexOf(b) >= 0; } static boolean startsWithIgnoreCase(String a, String b) { return a != null && a.regionMatches(true, 0, b, 0, b.length()); } static TimedCache> detectGateways_cache = new TimedCache(5); static synchronized List detectGateways() { try { if (detectGateways_cache.has()) return detectGateways_cache.getNoClean(); boolean win = isWindows(); String s = backtick(win ? "ipconfig" : "ip route show"); TreeSet ips = new TreeSet(); for (String line : toLines(s)) if (indexOfIgnoreCase(line, win ? "Gateway" : "via") >= 0) ips.addAll(regexpAll("\\d+\\.\\d+\\.\\d+\\.\\d+", line)); return detectGateways_cache.set(new ArrayList(ips)); } catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }} static List nlTok(String s) { return javaTokPlusPeriod(s); } // hopefully covers all cases :) static String safeSubstring(String s, int x, int y) { if (s == null) return null; if (x < 0) x = 0; if (x > s.length()) return ""; if (y < x) y = x; if (y > s.length()) y = s.length(); return s.substring(x, y); } static String safeSubstring(String s, int x) { return safeSubstring(s, x, l(s)); } static A assertEquals(Object x, A y) { return assertEquals(null, x, y); } static A assertEquals(String msg, Object x, A y) { if (!(x == null ? y == null : x.equals(y))) throw fail((msg != null ? msg + ": " : "") + structure(x) + " != " + structure(y)); return y; } static boolean isOnPATH(String cmd) { String path = System.getenv("PATH"); List dirs = splitAt(path, File.pathSeparator); String c = isWindows() ? cmd + ".exe" : cmd; for (String dir : dirs) if (new File(dir, c).isFile()) return true; return false; } static List splitAt(String s, String splitter) { List parts = new ArrayList(); int i = 0; if (s != null) while (i < l(s)) { int j = indexOf(s, splitter, i); if (j < 0) j = l(s); parts.add(substring(s, i, j)); i = j+l(splitter); } return parts; } // works on lists and strings and null static int indexOfIgnoreCase(Object a, Object b) { if (a == null) return -1; if (a instanceof String) { Matcher m = Pattern.compile((String) b, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher((String) a); if (m.find()) return m.start(); else return -1; } if (a instanceof List) { for (int i = 0; i < ((List) a).size(); i++) { Object o = ((List) a).get(i); if (o != null && ((String) o).equalsIgnoreCase((String) b)) return i; } return -1; } throw fail("Unknown type: " + a); } static List regexpAll(String pattern, String text) { List matches = new ArrayList(); Matcher matcher = Pattern.compile(pattern).matcher(text); while (matcher.find()) matches.add(matcher.group()); return matches; } static int indexOf(List l, A a, int startIndex) { if (l == null) return -1; for (int i = startIndex; i < l(l); i++) if (eq(l.get(i), a)) return i; return -1; } static int indexOf(List l, A a) { if (l == null) return -1; return l.indexOf(a); } static int indexOf(String a, String b) { return a == null || b == null ? -1 : a.indexOf(b); } static int indexOf(String a, String b, int i) { return a == null || b == null ? -1 : a.indexOf(b, i); } static int indexOf(String a, int i, String b) { return a == null || b == null ? -1 : a.indexOf(b, i); } static int indexOf(A[] x, A a) { if (x == null) return -1; for (int i = 0; i < l(x); i++) if (eq(x[i], a)) return i; return -1; } static class JavaXClassLoader extends URLClassLoader { JavaXClassLoader(List files) { super(new URL[0]); for (File f : files) addURL(f.toURI().toURL()); } } static class DynamicObject { String className; // just the name, without the "main$" Map fieldValues = new TreeMap(); DynamicObject() {} // className = just the name, without the "main$" DynamicObject(String className) { this.className = className;} void put(String field, Object value) { fieldValues.put(field, value); } Object get(String field) { return fieldValues.get(field); } } static class TimedCache { long timeout; A value; long set; // stats int stores, fails, hits; TimedCache(double timeoutSeconds) { timeout = toMS(timeoutSeconds); } synchronized A set(A a) { ++stores; value = a; set = now(); return a; } synchronized boolean has() { clean(); if (set != 0) { ++hits; return true; } ++fails; return false; } synchronized A get() { clean(); if (set != 0) ++hits; else ++fails; return value; } synchronized A get(Object makerFunction) { if (has()) return getNoClean(); A a = (A) ( callF(makerFunction)); return set(a); } synchronized A getNoClean() { return value; } // clear if timed out synchronized void clean() { if (now() > set+timeout) clear(); } // clear now synchronized void clear() { set = 0; value = null; } synchronized String stats() { return "Stores: " + stores + ", hits: " + hits + ", fails: " + fails; } } static class Var { A v; Var() {} Var(A v) { this.v = v;} synchronized void set(A a) { v = a; } synchronized A get() { return v; } } static void swingLater(int delay, final Runnable r) { javax.swing.Timer timer = new javax.swing.Timer(delay, new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) { r.run(); }}); timer.setRepeats(false); timer.start(); } static void swingLater(Runnable r) { SwingUtilities.invokeLater(r); } static long toMS(double seconds) { return (long) (seconds*1000); } static boolean match(String pat, String s) { return match3(pat, s); } static boolean match(String pat, String s, Matches matches) { return match3(pat, s, matches); } }