| 55 | } |
| 56 | |
| 57 | public static String gcc( String obj, String c_conv, String cfile, boolean stdin, String... args ) throws IOException { |
| 58 | |
| 59 | // Compile the C program. Compiling code and constants in the low |
| 60 | // 2Gig. Pointers are 64b BUT since always in the low 2G all the |
| 61 | // high bits are zero - and Simple code can be emitted treating |
| 62 | // pointers as 4bytes. |
| 63 | var params = new Ary<>(String.class); |
| 64 | params.add("gcc"); |
| 65 | if( cfile!=null ) params.add(cfile); // Associated C driver, usually has a `main` |
| 66 | params.addAll(new String[] { |
| 67 | obj, |
| 68 | "-lm", // Picks up 'sqrt' for newtonFloat tests to compare |
| 69 | "-g", |
| 70 | "-o", |
| 71 | args[0], |
| 72 | }); |
| 73 | // Calling convention for C calls, if any |
| 74 | if( cfile!=null ) { |
| 75 | params.add("-D"); |
| 76 | params.add("CALL_CONV="+c_conv); |
| 77 | } |
| 78 | |
| 79 | // Run GCC to link (optionally compile C driver code) |
| 80 | Process gcc = new ProcessBuilder(params.asAry()).redirectErrorStream(true).start(); |
| 81 | int exit; |
| 82 | try { |
| 83 | boolean normal = gcc.waitFor(2, TimeUnit.SECONDS); |
| 84 | exit = normal ? gcc.exitValue() : -1; // no exit??? |
| 85 | } catch( InterruptedException e ) { |
| 86 | throw new IOException("interrupted"); |
| 87 | } |
| 88 | String result = new String(gcc.getInputStream().readAllBytes()); |
| 89 | if( exit!=0 ) { |
| 90 | System.err.println("gcc error code: "+exit); |
| 91 | System.err.println(result); |
| 92 | } |
| 93 | assertEquals( 0, exit ); |
| 94 | //assertTrue(result.isEmpty()); // No data in error stream |
| 95 | |
| 96 | // Execute results |
| 97 | ProcessBuilder smp = new ProcessBuilder(args); |
| 98 | if( stdin ) smp.redirectInput(ProcessBuilder.Redirect.INHERIT); |
| 99 | Process p = smp.start(); |
| 100 | try { exit = (byte)p.waitFor(); } catch( InterruptedException e ) { throw new IOException("interrupted"); } |
| 101 | result = new String(p.getInputStream().readAllBytes()); |
| 102 | if( exit!=0 ) |
| 103 | System.err.println("exec exit code: "+exit); |
| 104 | return result; |
| 105 | } |
| 106 | } |