1 class String_overflow 2 { getChars()3 static void getChars() 4 { 5 String source = "abcdefg"; 6 char[] dest = new char [3]; 7 8 try 9 { 10 source.getChars (0, 5, // Source 11 dest, (1<<31) - 1); 12 Fail ("getChars", "Should not have succeeded"); 13 } 14 catch (Throwable e) 15 { 16 ExpectArrayIndex ("getChars", e); 17 } 18 } 19 20 /* How do I stop a compiler warning causing a test to fail? 21 static void getBytes() 22 { 23 String source = "abcdefg"; 24 byte[] dest = new byte[3]; 25 26 try 27 { 28 source.getBytes (0, 5, dest, (1<<31) - 1); 29 Fail ("getBytes", "Should not have succeeded"); 30 } 31 catch (Throwable e) 32 { 33 ExpectArrayIndex ("getBytes", e); 34 } 35 } 36 */ 37 regionMatches()38 static void regionMatches() 39 { 40 if ("abcdefg".regionMatches (4, "abcdefg", 4, -1)) 41 { 42 Fail ("regionMatches", "Should not return true"); 43 } 44 45 try 46 { 47 if ("abcdefg".regionMatches (4, "abcdefg", 4, (1<<31)-1)) 48 { 49 Fail ("regionMatches (2nd)", "Should not return true"); 50 } 51 } 52 catch (Throwable e) 53 { 54 Fail ("regionMatches (2nd)", e); 55 } 56 } 57 regionMatchesCase()58 static void regionMatchesCase() 59 { 60 if ("abcdefg".regionMatches (true, 4, "abcdefg", 4, -1)) 61 { 62 Fail ("regionMatchesCase", "Should not return true"); 63 } 64 65 try 66 { 67 if ("abcdefg".regionMatches (true, 4, "abcdefg", 4, (1<<31)-1)) 68 { 69 Fail ("regionMatchesCase (2nd)", "Should not return true"); 70 } 71 } 72 catch (Throwable e) 73 { 74 Fail ("regionMatchesCase (2nd)", e); 75 } 76 } 77 startsWith()78 static void startsWith() 79 { 80 // We make the arg pretty big to try and cause a segfault. 81 String s = new String ("abcdef"); 82 StringBuffer b = new StringBuffer (1000000); 83 b.setLength (1000000); 84 String arg = new String (b); 85 86 try 87 { 88 s.startsWith (arg, (1<<31) - 1000000); 89 } 90 catch (Throwable e) 91 { 92 Fail ("startsWith", e); 93 } 94 } 95 valueOf()96 static void valueOf() 97 { 98 char[] array = new char[] {'a', 'b', 'c', 'd', 'e'}; 99 try 100 { 101 String.valueOf (array, 4, (1<<31)-1); 102 Fail ("valueOf", "should not succeed"); 103 } 104 catch (Throwable e) 105 { 106 ExpectArrayIndex ("valueOf", e); 107 } 108 } 109 main(String[] args)110 public static void main (String[] args) throws Throwable 111 { 112 getChars(); 113 // getBytes(); 114 regionMatches(); 115 regionMatchesCase(); 116 startsWith(); 117 valueOf(); 118 119 if (tests_failed == 0) 120 System.out.println ("ok"); 121 } 122 ExpectArrayIndex(String test, Throwable e)123 static void ExpectArrayIndex (String test, Throwable e) 124 { 125 if (e instanceof ArrayIndexOutOfBoundsException) 126 return; 127 128 Fail (test, e); 129 } 130 Fail(String test, Object problem)131 static void Fail (String test, Object problem) 132 { 133 ++tests_failed; 134 System.err.print (test); 135 System.err.print ('\t'); 136 System.err.println (problem); 137 } 138 139 static int tests_failed; 140 } 141