instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBit() throws Exception { assertArrayEquals(new byte[]{1}, BeginBin().Bit(1).End().toByteArray()); }
#vulnerable code @Test public void testBit() throws Exception { assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBitArrayAsInts() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(1, 3, 0, 2, 4, 1, 3, 7).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(1, 3, 0, 7).End().toByteArray()); }
#vulnerable code @Test public void testBitArrayAsInts() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExceptionForOperatioOverEndedProcess() throws Exception { final JBBPOut out = BeginBin(); out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).End(); try{ out.Align(); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Align(3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit(true); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit(true,false); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit((byte)34); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit((byte)34,(byte)12); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit(34,12); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bits(JBBPNumberOfBits.BITS_3, 12); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bool(true); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bool(true,false); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Byte((byte)1,(byte)2,(byte)3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Byte(1); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Byte(1,2,3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Flush(); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Int(1); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Int(1,2); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Long(1L); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Long(1L,2L); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Short(1); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Short(1,2,3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Short((short)1,(short)2,(short)3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.End(); fail("Must throw ISE"); }catch(IllegalStateException ex){ } }
#vulnerable code @Test public void testExceptionForOperatioOverEndedProcess() throws Exception { final JBBPOut out = binStart(); out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); try{ out.Align(); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Align(3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit(true); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit(true,false); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit((byte)34); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit((byte)34,(byte)12); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bit(34,12); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bits(JBBPNumberOfBits.BITS_3, 12); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bool(true); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Bool(true,false); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Byte((byte)1,(byte)2,(byte)3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Byte(1); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Byte(1,2,3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Flush(); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Int(1); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Int(1,2); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Long(1L); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Long(1L,2L); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Short(1); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Short(1,2,3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.Short((short)1,(short)2,(short)3); fail("Must throw ISE"); }catch(IllegalStateException ex){ } try{ out.end(); fail("Must throw ISE"); }catch(IllegalStateException ex){ } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBitArrayAsBytes() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).End().toByteArray()); }
#vulnerable code @Test public void testBitArrayAsBytes() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAlign() throws Exception { assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align().Byte(0xFF).End().toByteArray()); }
#vulnerable code @Test public void testAlign() throws Exception { assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).End().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testIntArray() throws Exception { assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, BeginBin().Int(0x01020304, 0x05060708).End().toByteArray()); }
#vulnerable code @Test public void testIntArray() throws Exception { assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetLineSeparator() throws Exception { assertEquals("hello", new JBBPTextWriter(writer, JBBPByteOrder.BIG_ENDIAN, "hello", 11, "", "", "","", "").getLineSeparator()); }
#vulnerable code @Test public void testGetLineSeparator() throws Exception { assertEquals("hello", new JBBPTextWriter(writer, JBBPByteOrder.BIG_ENDIAN, "hello", 11, "", "", "", "").getLineSeparator()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBits_Int() throws Exception { assertArrayEquals(new byte[]{0xD}, BeginBin().Bits(JBBPNumberOfBits.BITS_4, 0xFD).End().toByteArray()); }
#vulnerable code @Test public void testBits_Int() throws Exception { assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testShortArray_AsIntegers_LittleEndian() throws Exception { assertArrayEquals(new byte []{2,1,4,3}, BeginBin().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).End().toByteArray()); }
#vulnerable code @Test public void testShortArray_AsIntegers_LittleEndian() throws Exception { assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBitArrayAsBooleans() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, BeginBin().Bit(true, true, false, false, false, true, true, true).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, BeginBin().Bit(true, true, false, true).End().toByteArray()); }
#vulnerable code @Test public void testBitArrayAsBooleans() throws Exception { assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testLongArray() throws Exception { assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, BeginBin().Long(0x0102030405060708L,0x1112131415161718L).End().toByteArray()); }
#vulnerable code @Test public void testLongArray() throws Exception { assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAlignWithArgument() throws Exception { assertEquals(0, JBBPOut.BeginBin().Align(2).End().toByteArray().length); assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(1).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0xFF}, JBBPOut.BeginBin().Align(3).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(1).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(2).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Bit(1).Align(4).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2).Align(4).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2, 3).Align(5).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2, 3, 4).Align(5).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, JBBPOut.BeginBin().Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, JBBPOut.BeginBin().Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, JBBPOut.BeginBin().Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, JBBPOut.BeginBin().Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, JBBPOut.BeginBin().Int(0x01020304).Align(5).Byte(0xF1).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, JBBPOut.BeginBin().Bit(1).Align(5).Byte(0xF1).End().toByteArray()); }
#vulnerable code @Test public void testAlignWithArgument() throws Exception { assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).End().toByteArray().length); assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).End().toByteArray()); assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).End().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBeginBin() throws Exception { assertArrayEquals(new byte[]{1}, BeginBin().Byte(1).End().toByteArray()); assertArrayEquals(new byte[]{0x02, 0x01}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).End().toByteArray()); assertArrayEquals(new byte[]{0x40, (byte) 0x80}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN, JBBPBitOrder.MSB0).Short(0x0102).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(JBBPBitOrder.MSB0).Byte(1).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(1).Byte(0x80).End().toByteArray()); final ByteArrayOutputStream buffer1 = new ByteArrayOutputStream(); assertSame(buffer1, BeginBin(buffer1).End()); final ByteArrayOutputStream buffer2 = new ByteArrayOutputStream(); BeginBin(buffer2,JBBPByteOrder.LITTLE_ENDIAN, JBBPBitOrder.MSB0).Short(1234).End(); assertArrayEquals(new byte[]{(byte)0x4b, (byte)0x20}, buffer2.toByteArray()); }
#vulnerable code @Test public void testBeginBin() throws Exception { assertArrayEquals(new byte[]{1}, BeginBin().Byte(1).End().toByteArray()); assertArrayEquals(new byte[]{0x02, 0x01}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).End().toByteArray()); assertArrayEquals(new byte[]{0x40, (byte) 0x80}, BeginBin(JBBPByteOrder.LITTLE_ENDIAN, JBBPBitOrder.MSB0).Short(0x0102).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(JBBPBitOrder.MSB0).Byte(1).End().toByteArray()); assertArrayEquals(new byte[]{(byte) 0x80}, BeginBin(1).Byte(0x80).End().toByteArray()); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); assertSame(buffer, BeginBin(buffer).End()); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBits_ByteArray() throws Exception { assertArrayEquals(new byte[]{(byte) 0xED}, BeginBin().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).End().toByteArray()); }
#vulnerable code @Test public void testBits_ByteArray() throws Exception { assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException { return _readArray(items, bitNumber); }
#vulnerable code public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException { int pos = 0; if (items < 0) { byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; // till end while (true) { final int next = readBits(bitNumber); if (next < 0) { break; } if (buffer.length == pos) { final byte[] newbuffer = new byte[buffer.length << 1]; System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); buffer = newbuffer; } buffer[pos++] = (byte) next; } if (buffer.length == pos) { return buffer; } final byte[] result = new byte[pos]; System.arraycopy(buffer, 0, result, 0, pos); return result; } else { // number final byte[] buffer = new byte[items]; for (int i = 0; i < items; i++) { final int next = readBits(bitNumber); if (next < 0) { throw new EOFException("Have read only " + i + " bit portions instead of " + items); } buffer[i] = (byte) next; } return buffer; } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testInt_BigEndian() throws Exception { assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, BeginBin().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).End().toByteArray()); }
#vulnerable code @Test public void testInt_BigEndian() throws Exception { assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testParse_StructArray_IgnoredForZeroLength() throws Exception { final JBBPFieldStruct parsed = JBBPParser.prepare("byte len; sss [len] { byte a; byte b; byte c;} ushort;").parse(new byte[]{0x0, 0x01, (byte) 0x02}); assertEquals(0,parsed.findFieldForType(JBBPFieldArrayStruct.class).size()); assertEquals(0x0102, parsed.findFieldForType(JBBPFieldUShort.class).getAsInt()); }
#vulnerable code @Test public void testParse_StructArray_IgnoredForZeroLength() throws Exception { final JBBPFieldStruct parsed = JBBPParser.prepare("byte len; sss [len] { byte a; byte b; byte c;} ushort;").parse(new byte[]{0x0, 0x01, (byte) 0x02}); assertNull(parsed.findFieldForType(JBBPFieldArrayStruct.class)); assertEquals(0x0102, parsed.findFieldForType(JBBPFieldUShort.class).getAsInt()); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testShortArray_AsIntegers() throws Exception { assertArrayEquals(new byte []{1,2,3,4}, BeginBin().Short(0x0102,0x0304).End().toByteArray()); }
#vulnerable code @Test public void testShortArray_AsIntegers() throws Exception { assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean apply(Server server, Map<String, String> metadata) { // 1.对Rest调用传来的Header的路由Version做策略。注意这个Version不是灰度发布的Version boolean enabled = super.apply(server, metadata); if (!enabled) { return false; } // 2.对Rest调用传来的Header参数(例如Token)做策略 return applyFromHeader(server, metadata); }
#vulnerable code @Override public boolean apply(Server server, Map<String, String> metadata) { GatewayStrategyContext context = GatewayStrategyContext.getCurrentContext(); String token = context.getExchange().getRequest().getHeaders().getFirst("token"); // String value = context.getExchange().getRequest().getQueryParams().getFirst("value"); // 执行完后,请手工清除上下文对象,否则可能会造成内存泄露 GatewayStrategyContext.clearCurrentContext(); String serviceId = server.getMetaInfo().getAppName().toLowerCase(); LOG.info("Gateway端负载均衡用户定制触发:serviceId={}, host={}, metadata={}, context={}", serviceId, server.toString(), metadata, context); String filterToken = "abc"; if (StringUtils.isNotEmpty(token) && token.contains(filterToken)) { LOG.info("过滤条件:当Token含有'{}'的时候,不能被Ribbon负载均衡到", filterToken); return false; } return true; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void debugHeader() { if (!traceDebugEnabled) { return; } System.out.println("---------------- Trace Information ---------------"); String traceId = getTraceId(); String spanId = getSpanId(); System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); System.out.println(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT)); String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); if (StringUtils.isNotEmpty(routeVersion)) { System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion); } String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); if (StringUtils.isNotEmpty(routeRegion)) { System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion); } String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); if (StringUtils.isNotEmpty(routeAddress)) { System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress); } String routeEnvironment = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ENVIRONMENT); if (StringUtils.isNotEmpty(routeEnvironment)) { System.out.println(DiscoveryConstant.N_D_ENVIRONMENT + "=" + routeEnvironment); } String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT); if (StringUtils.isNotEmpty(routeVersionWeight)) { System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight); } String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT); if (StringUtils.isNotEmpty(routeRegionWeight)) { System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight); } Map<String, String> customizationMap = getCustomizationMap(); if (MapUtils.isNotEmpty(customizationMap)) { for (Map.Entry<String, String> entry : customizationMap.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } System.out.println("--------------------------------------------------"); }
#vulnerable code public void debugHeader() { if (!traceDebugEnabled) { return; } System.out.println("---------------- Trace Information ---------------"); String traceId = getTraceId(); String spanId = getSpanId(); System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); System.out.println(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ENVIRONMENT)); String routeVersion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION); if (StringUtils.isNotEmpty(routeVersion)) { System.out.println(DiscoveryConstant.N_D_VERSION + "=" + routeVersion); } String routeRegion = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION); if (StringUtils.isNotEmpty(routeRegion)) { System.out.println(DiscoveryConstant.N_D_REGION + "=" + routeRegion); } String routeAddress = strategyContextHolder.getHeader(DiscoveryConstant.N_D_ADDRESS); if (StringUtils.isNotEmpty(routeAddress)) { System.out.println(DiscoveryConstant.N_D_ADDRESS + "=" + routeAddress); } String routeVersionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_VERSION_WEIGHT); if (StringUtils.isNotEmpty(routeVersionWeight)) { System.out.println(DiscoveryConstant.N_D_VERSION_WEIGHT + "=" + routeVersionWeight); } String routeRegionWeight = strategyContextHolder.getHeader(DiscoveryConstant.N_D_REGION_WEIGHT); if (StringUtils.isNotEmpty(routeRegionWeight)) { System.out.println(DiscoveryConstant.N_D_REGION_WEIGHT + "=" + routeRegionWeight); } Map<String, String> customizationMap = getCustomizationMap(); if (MapUtils.isNotEmpty(customizationMap)) { for (Map.Entry<String, String> entry : customizationMap.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } System.out.println("--------------------------------------------------"); } #location 42 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String createSpanId() { try { return StrategySkywalkingTracerResolver.getSpanId(); } catch (Exception e) { return null; } }
#vulnerable code private String createSpanId() { if (System.getProperties().get("skywalking.agent.service_name") == null) { return null; } try { Object traceContext = StrategySkywalkingTracerResolver.invokeStaticMethod("org.apache.skywalking.apm.agent.core.context.ContextManager", "get"); if (traceContext != null) { if (traceContext.getClass().getName().equals("org.apache.skywalking.apm.agent.core.context.TracingContext")) { Field fieldSegment = StrategySkywalkingTracerResolver.findField(traceContext.getClass(), "segment"); Object segment = StrategySkywalkingTracerResolver.getField(fieldSegment, traceContext); Field fieldSegmentId = StrategySkywalkingTracerResolver.findField(segment.getClass(), "traceSegmentId"); String segmentId = StrategySkywalkingTracerResolver.getField(fieldSegmentId, segment).toString(); return segmentId; } else { return null; } } } catch (Exception e) { } return null; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("rawtypes") private void parseStrategyCondition(Element element, List<StrategyConditionEntity> strategyConditionEntityList) { for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { Object childElementObject = elementIterator.next(); if (childElementObject instanceof Element) { Element childElement = (Element) childElementObject; if (StringUtils.equals(childElement.getName(), ConfigConstant.CONDITION_ELEMENT_NAME)) { StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity(); Attribute idAttribute = childElement.attribute(ConfigConstant.ID_ATTRIBUTE_NAME); if (idAttribute == null) { throw new DiscoveryException("Attribute[" + ConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); } String id = idAttribute.getData().toString().trim(); strategyConditionEntity.setId(id); Attribute headerAttribute = childElement.attribute(ConfigConstant.HEADER_ATTRIBUTE_NAME); if (headerAttribute == null) { throw new DiscoveryException("Attribute[" + ConfigConstant.HEADER_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); } String header = headerAttribute.getData().toString().trim(); strategyConditionEntity.setConditionHeader(header); Attribute versionIdAttribute = childElement.attribute(ConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (versionIdAttribute != null) { String versionId = versionIdAttribute.getData().toString().trim(); strategyConditionEntity.setVersionId(versionId); } Attribute regionIdAttribute = childElement.attribute(ConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (regionIdAttribute != null) { String regionId = regionIdAttribute.getData().toString().trim(); strategyConditionEntity.setRegionId(regionId); } Attribute addressIdAttribute = childElement.attribute(ConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (addressIdAttribute != null) { String addressId = addressIdAttribute.getData().toString().trim(); strategyConditionEntity.setAddressId(addressId); } Attribute versionWeightIdAttribute = childElement.attribute(ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (versionWeightIdAttribute != null) { String versionWeightId = versionWeightIdAttribute.getData().toString().trim(); strategyConditionEntity.setVersionWeightId(versionWeightId); } Attribute regionWeightIdAttribute = childElement.attribute(ConfigConstant.REGION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (regionWeightIdAttribute != null) { String regionWeightId = regionWeightIdAttribute.getData().toString().trim(); strategyConditionEntity.setRegionWeightId(regionWeightId); } strategyConditionEntityList.add(strategyConditionEntity); } } } }
#vulnerable code @SuppressWarnings("rawtypes") private void parseStrategyCondition(Element element, List<StrategyConditionEntity> strategyConditionEntityList) { for (Iterator elementIterator = element.elementIterator(); elementIterator.hasNext();) { Object childElementObject = elementIterator.next(); if (childElementObject instanceof Element) { Element childElement = (Element) childElementObject; if (StringUtils.equals(childElement.getName(), ConfigConstant.CONDITION_ELEMENT_NAME)) { StrategyConditionEntity strategyConditionEntity = new StrategyConditionEntity(); Attribute idAttribute = childElement.attribute(ConfigConstant.ID_ATTRIBUTE_NAME); if (idAttribute == null) { throw new DiscoveryException("Attribute[" + ConfigConstant.ID_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); } String id = idAttribute.getData().toString().trim(); strategyConditionEntity.setId(id); Attribute headerAttribute = childElement.attribute(ConfigConstant.HEADER_ATTRIBUTE_NAME); if (headerAttribute == null) { throw new DiscoveryException("Attribute[" + ConfigConstant.HEADER_ATTRIBUTE_NAME + "] in element[" + childElement.getName() + "] is missing"); } String header = headerAttribute.getData().toString().trim(); strategyConditionEntity.setConditionHeader(header); List<String> headerList = StringUtil.splitToList(header, DiscoveryConstant.SEPARATE); for (String value : headerList) { String[] valueArray = StringUtils.split(value, DiscoveryConstant.EQUALS); String headerName = valueArray[0].trim(); String headerValue = valueArray[1].trim(); strategyConditionEntity.getConditionHeaderMap().put(headerName, headerValue); } Attribute versionIdAttribute = childElement.attribute(ConfigConstant.VERSION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (versionIdAttribute != null) { String versionId = versionIdAttribute.getData().toString().trim(); strategyConditionEntity.setVersionId(versionId); } Attribute regionIdAttribute = childElement.attribute(ConfigConstant.REGION_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (regionIdAttribute != null) { String regionId = regionIdAttribute.getData().toString().trim(); strategyConditionEntity.setRegionId(regionId); } Attribute addressIdAttribute = childElement.attribute(ConfigConstant.ADDRESS_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (addressIdAttribute != null) { String addressId = addressIdAttribute.getData().toString().trim(); strategyConditionEntity.setAddressId(addressId); } Attribute versionWeightIdAttribute = childElement.attribute(ConfigConstant.VERSION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (versionWeightIdAttribute != null) { String versionWeightId = versionWeightIdAttribute.getData().toString().trim(); strategyConditionEntity.setVersionWeightId(versionWeightId); } Attribute regionWeightIdAttribute = childElement.attribute(ConfigConstant.REGION_WEIGHT_ELEMENT_NAME + DiscoveryConstant.DASH + ConfigConstant.ID_ATTRIBUTE_NAME); if (regionWeightIdAttribute != null) { String regionWeightId = regionWeightIdAttribute.getData().toString().trim(); strategyConditionEntity.setRegionWeightId(regionWeightId); } strategyConditionEntityList.add(strategyConditionEntity); } } } } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean applyFromHeader(Server server, Map<String, String> metadata) { String mobile = gatewayStrategyContextHolder.getHeader("mobile"); String version = metadata.get(DiscoveryConstant.VERSION); String serviceId = pluginAdapter.getServerServiceId(server); LOG.info("Gateway端负载均衡用户定制触发:mobile={}, serviceId={}, metadata={}", mobile, serviceId, metadata); if (StringUtils.isNotEmpty(mobile)) { // 手机号以移动138开头,路由到1.0版本的服务上 if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) { return true; // 手机号以联通133开头,路由到2.0版本的服务上 } else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) { return true; } else { // 其它情况,直接拒绝请求 return false; } } return true; }
#vulnerable code private boolean applyFromHeader(Server server, Map<String, String> metadata) { String token = gatewayStrategyContextHolder.getHeader("token"); String serviceId = pluginAdapter.getServerServiceId(server); LOG.info("Gateway端负载均衡用户定制触发:token={}, serviceId={}, metadata={}", token, serviceId, metadata); String filterToken = "abc"; if (StringUtils.isNotEmpty(token) && token.contains(filterToken)) { LOG.info("过滤条件:当Token含有'{}'的时候,不能被Ribbon负载均衡到", filterToken); return false; } return true; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public int compare(@Nullable Object left, @Nullable Object right) throws SpelEvaluationException { if (left == null) { return right == null ? 0 : -1; } else if (right == null) { return 1; } try { BigDecimal leftValue = new BigDecimal(left.toString()); BigDecimal rightValue = new BigDecimal(right.toString()); return super.compare(leftValue, rightValue); } catch (Exception e) { } return super.compare(left, right); }
#vulnerable code @Override public int compare(@Nullable Object left, @Nullable Object right) throws SpelEvaluationException { if (left == null) { return 0; } try { BigDecimal leftValue = new BigDecimal(left.toString()); BigDecimal rightValue = new BigDecimal(right.toString()); return super.compare(leftValue, rightValue); } catch (Exception e) { } return super.compare(left, right); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void debugTraceHeader() { if (!traceDebugEnabled) { return; } System.out.println("---------------- Trace Information ---------------"); String traceId = getTraceId(); String spanId = getSpanId(); System.out.println(DiscoveryConstant.TRACE_ID + "=" + (StringUtils.isNotEmpty(traceId) ? traceId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.SPAN_ID + "=" + (StringUtils.isNotEmpty(spanId) ? spanId : StringUtils.EMPTY)); System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); Map<String, String> customizationMap = getCustomizationMap(); if (MapUtils.isNotEmpty(customizationMap)) { for (Map.Entry<String, String> entry : customizationMap.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } System.out.println("--------------------------------------------------"); }
#vulnerable code public void debugTraceHeader() { if (!traceDebugEnabled) { return; } System.out.println("---------------- Trace Information ---------------"); Map<String, String> debugTraceMap = getDebugTraceMap(); if (MapUtils.isNotEmpty(debugTraceMap)) { for (Map.Entry<String, String> entry : debugTraceMap.entrySet()) { System.out.println(entry.getKey() + "=" + entry.getValue()); } } System.out.println(DiscoveryConstant.N_D_SERVICE_GROUP + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP)); System.out.println(DiscoveryConstant.N_D_SERVICE_TYPE + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_TYPE)); System.out.println(DiscoveryConstant.N_D_SERVICE_ID + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ID)); System.out.println(DiscoveryConstant.N_D_SERVICE_ADDRESS + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_ADDRESS)); System.out.println(DiscoveryConstant.N_D_SERVICE_VERSION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_VERSION)); System.out.println(DiscoveryConstant.N_D_SERVICE_REGION + "=" + strategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_REGION)); System.out.println("--------------------------------------------------"); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBasicWrite() throws IOException, ParserConfigurationException, SAXException { Network<String, Number> g = TestGraphs.createTestGraph(true); GraphMLWriter<String, Number> gmlw = new GraphMLWriter<String, Number>(); Function<Number, String> edge_weight = new Function<Number, String>() { public String apply(Number n) { return String.valueOf(n.intValue()); } }; Function<String, String> vertex_name = Function.identity(); //TransformerUtils.nopTransformer(); gmlw.addEdgeData("weight", "integer value for the edge", Integer.toString(-1), edge_weight); gmlw.addVertexData("name", "identifier for the vertex", null, vertex_name); gmlw.setEdgeIDs(edge_weight); gmlw.setVertexIDs(vertex_name); gmlw.save(g, new FileWriter("src/test/resources/testbasicwrite.graphml")); // TODO: now read it back in and compare the graph connectivity // and other metadata with what's in TestGraphs.pairs[], etc. GraphMLReader<MutableNetwork<String, Object>, String, Object> gmlr = new GraphMLReader<MutableNetwork<String, Object>, String, Object>(); MutableNetwork<String, Object> g2 = NetworkBuilder.directed().allowsSelfLoops(true).build(); gmlr.load("src/test/resources/testbasicwrite.graphml", g2); Map<String, GraphMLMetadata<Object>> edge_metadata = gmlr.getEdgeMetadata(); Function<Object, String> edge_weight2 = edge_metadata.get("weight").transformer; validateTopology(g, g2, edge_weight, edge_weight2); File f = new File("src/test/resources/testbasicwrite.graphml"); f.delete(); }
#vulnerable code public void testBasicWrite() throws IOException, ParserConfigurationException, SAXException { Network<String, Number> g = TestGraphs.createTestGraph(true); GraphMLWriter<String, Number> gmlw = new GraphMLWriter<String, Number>(); Function<Number, String> edge_weight = new Function<Number, String>() { public String apply(Number n) { return String.valueOf(n.intValue()); } }; Function<String, String> vertex_name = Functions.identity(); //TransformerUtils.nopTransformer(); gmlw.addEdgeData("weight", "integer value for the edge", Integer.toString(-1), edge_weight); gmlw.addVertexData("name", "identifier for the vertex", null, vertex_name); gmlw.setEdgeIDs(edge_weight); gmlw.setVertexIDs(vertex_name); gmlw.save(g, new FileWriter("src/test/resources/testbasicwrite.graphml")); // TODO: now read it back in and compare the graph connectivity // and other metadata with what's in TestGraphs.pairs[], etc. GraphMLReader<MutableNetwork<String, Object>, String, Object> gmlr = new GraphMLReader<MutableNetwork<String, Object>, String, Object>(); MutableNetwork<String, Object> g2 = NetworkBuilder.directed().allowsSelfLoops(true).build(); gmlr.load("src/test/resources/testbasicwrite.graphml", g2); Map<String, GraphMLMetadata<Object>> edge_metadata = gmlr.getEdgeMetadata(); Function<Object, String> edge_weight2 = edge_metadata.get("weight").transformer; validateTopology(g, g2, edge_weight, edge_weight2); File f = new File("src/test/resources/testbasicwrite.graphml"); f.delete(); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void testEchoStringWithEncoding(String encoding) { String sent = randomUnicodeString(100); Buffer buffSent = new Buffer(sent, encoding); testEcho(sock -> sock.write(sent, encoding), buff -> buffersEqual(buffSent, buff), buffSent.length()); }
#vulnerable code String findFileOnClasspath(String fileName) { URL url = getClass().getClassLoader().getResource(fileName); if (url == null) { throw new IllegalArgumentException("Cannot find file " + fileName + " on classpath"); } Path path = ClasspathPathResolver.urlToPath(url).toAbsolutePath(); return path.toString(); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void rtmStart() throws Exception { // TODO: "prefs" support SlackConfig config = new SlackConfig(); config.setLibraryMaintainerMode(false); config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener()); Slack slack = Slack.getInstance(config); String channelName = "test" + System.currentTimeMillis(); TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken); Conversation channel = channelGenerator.createNewPublicChannel(channelName); try { String channelId = channel.getId(); // need to invite the bot user to the created channel before starting an RTM session inviteBotUser(channelId); Thread.sleep(3000); try (RTMClient rtm = slack.rtmStart(classicAppBotToken)) { User user = rtm.getConnectedBotUser(); assertThat(user.getId(), is(notNullValue())); assertThat(user.getTeamId(), is(notNullValue())); assertThat(user.getName(), is(notNullValue())); assertThat(user.getProfile(), is(notNullValue())); assertThat(user.getProfile().getBotId(), is(notNullValue())); verifyRTMClientBehavior(channelId, rtm); } } finally { channelGenerator.archiveChannel(channel); } }
#vulnerable code @Test public void rtmStart() throws Exception { // TODO: "prefs" support SlackConfig config = new SlackConfig(); config.setLibraryMaintainerMode(false); config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener()); Slack slack = Slack.getInstance(config); String channelName = "test" + System.currentTimeMillis(); TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken); Conversation channel = channelGenerator.createNewPublicChannel(channelName); try { String channelId = channel.getId(); // need to invite the bot user to the created channel before starting an RTM session inviteBotUser(channelId); Thread.sleep(3000); try (RTMClient rtm = slack.rtmStart(botToken)) { User user = rtm.getConnectedBotUser(); assertThat(user.getId(), is(notNullValue())); assertThat(user.getTeamId(), is(notNullValue())); assertThat(user.getName(), is(notNullValue())); assertThat(user.getProfile(), is(notNullValue())); assertThat(user.getProfile().getBotId(), is(notNullValue())); verifyRTMClientBehavior(channelId, rtm); } } finally { channelGenerator.archiveChannel(channel); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void initializer_called() { App app = new App(AppConfig.builder().signingSecret("secret").build()); final AtomicBoolean called = new AtomicBoolean(false); assertThat(called.get(), is(false)); app.initializer("foo", (theApp) -> { called.set(true); }); app.initialize(); assertThat(called.get(), is(true)); }
#vulnerable code @Test public void initializer_called() { App app = new App(); final AtomicBoolean called = new AtomicBoolean(false); assertThat(called.get(), is(false)); app.initializer("foo", (theApp) -> { called.set(true); }); app.initialize(); assertThat(called.get(), is(true)); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void status() { App app = new App(AppConfig.builder().signingSecret("secret").build()); assertThat(app.status(), is(App.Status.Stopped)); app.start(); assertThat(app.status(), is(App.Status.Running)); app.stop(); assertThat(app.status(), is(App.Status.Stopped)); app.start(); assertThat(app.status(), is(App.Status.Running)); app.stop(); assertThat(app.status(), is(App.Status.Stopped)); app.start(); app.start(); assertThat(app.status(), is(App.Status.Running)); }
#vulnerable code @Test public void status() { App app = new App(); assertThat(app.status(), is(App.Status.Stopped)); app.start(); assertThat(app.status(), is(App.Status.Running)); app.stop(); assertThat(app.status(), is(App.Status.Stopped)); app.start(); assertThat(app.status(), is(App.Status.Running)); app.stop(); assertThat(app.status(), is(App.Status.Stopped)); app.start(); app.start(); assertThat(app.status(), is(App.Status.Running)); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void builder_config() { App app = new App(AppConfig.builder().signingSecret("secret").build()); assertNotNull(app.config()); app = app.toBuilder().build(); assertNotNull(app.config()); app = app.toOAuthCallbackApp(); assertNotNull(app.config()); app = app.toOAuthStartApp(); assertNotNull(app.config()); }
#vulnerable code @Test public void builder_config() { App app = new App(); assertNotNull(app.config()); app = app.toBuilder().build(); assertNotNull(app.config()); app = app.toOAuthCallbackApp(); assertNotNull(app.config()); app = app.toOAuthStartApp(); assertNotNull(app.config()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected Request<?> toSlackRequest(ApiGatewayRequest awsReq) { if (log.isDebugEnabled()) { log.debug("AWS API Gateway Request: {}", awsReq); } RequestContext context = awsReq.getRequestContext(); SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder() .requestUri(awsReq.getPath()) .queryString(toStringToStringListMap(awsReq.getQueryStringParameters())) .headers(new RequestHeaders(toStringToStringListMap(awsReq.getHeaders()))) .requestBody(awsReq.getBody()) .remoteAddress(context != null && context.getIdentity() != null ? context.getIdentity().getSourceIp() : null) .build(); return requestParser.parse(rawRequest); }
#vulnerable code protected Request<?> toSlackRequest(ApiGatewayRequest awsReq) { if (log.isDebugEnabled()) { log.debug("AWS API Gateway Request: {}", awsReq); } SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder() .requestUri(awsReq.getPath()) .queryString(toStringToStringListMap(awsReq.getQueryStringParameters())) .headers(new RequestHeaders(toStringToStringListMap(awsReq.getHeaders()))) .requestBody(awsReq.getBody()) .remoteAddress(awsReq.getRequestContext().getIdentity() != null ? awsReq.getRequestContext().getIdentity().getSourceIp() : null) .build(); return requestParser.parse(rawRequest); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Installer findInstaller(String enterpriseId, String teamId, String userId) { AmazonS3 s3 = this.createS3Client(); String fullKey = getInstallerKey(enterpriseId, teamId, userId); if (isHistoricalDataEnabled()) { fullKey = fullKey + "-latest"; } if (getObjectMetadata(s3, fullKey) == null && enterpriseId != null) { String nonGridKey = getInstallerKey(null, teamId, userId); if (isHistoricalDataEnabled()) { nonGridKey = nonGridKey + "-latest"; } S3Object nonGridObject = getObject(s3, nonGridKey); if (nonGridObject != null) { try { Installer installer = toInstaller(nonGridObject); installer.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now saveInstallerAndBot(installer); return installer; } catch (Exception e) { log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}", enterpriseId, teamId, userId); } } } S3Object s3Object = getObject(s3, fullKey); try { return toInstaller(s3Object); } catch (Exception e) { log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}", enterpriseId, teamId, userId); return null; } }
#vulnerable code @Override public Installer findInstaller(String enterpriseId, String teamId, String userId) { AmazonS3 s3 = this.createS3Client(); String fullKey = getInstallerKey(enterpriseId, teamId, userId); if (isHistoricalDataEnabled()) { fullKey = fullKey + "-latest"; } if (s3.getObjectMetadata(bucketName, fullKey) == null && enterpriseId != null) { String nonGridKey = getInstallerKey(null, teamId, userId); if (isHistoricalDataEnabled()) { nonGridKey = nonGridKey + "-latest"; } S3Object nonGridObject = s3.getObject(bucketName, nonGridKey); if (nonGridObject != null) { try { Installer installer = toInstaller(nonGridObject); installer.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now saveInstallerAndBot(installer); return installer; } catch (Exception e) { log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}", enterpriseId, teamId, userId); } } } S3Object s3Object = s3.getObject(bucketName, fullKey); try { return toInstaller(s3Object); } catch (Exception e) { log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}", enterpriseId, teamId, userId); return null; } } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { test(); }
#vulnerable code public static void main(String[] args) throws Exception { DebugProtocol protocol = new DebugProtocol(new EventListener() { @Override public void onPageLoad() { //To change body of implemented methods use File | Settings | File Templates. } @Override public void domHasChanged(Event event) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void frameDied(JSONObject message) { //To change body of implemented methods use File | Settings | File Templates. } }, "com.apple.mobilesafari"); System.out.println(protocol.sendCommand(DOM.getDocument()).toString(2)); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expectedExceptions = UnexpectedAlertOpen.class) public void cannotInteractWithAppWhenAlertOpen() throws Exception { RemoteUIADriver driver = null; try { driver = getDriver(); RemoteUIATarget target = driver.getLocalTarget(); RemoteUIAApplication app = target.getFrontMostApp(); RemoteUIAWindow win = app.getMainWindow(); getAlert(win); Criteria c = new AndCriteria(new TypeCriteria(UIAStaticText.class), new NameCriteria("Show Simple")); UIAElement el = win.findElements(c).get(1); // opens an alert. el.tap(); // should throw.The alert prevent interacting with the background. el.tap(); } finally { if (driver != null) { driver.quit(); } } }
#vulnerable code @Test(expectedExceptions = UnexpectedAlertOpen.class) public void cannotInteractWithAppWhenAlertOpen() throws Exception { RemoteUIADriver driver = null; try { driver = getDriver(); RemoteUIATarget target = driver.getLocalTarget(); RemoteUIAApplication app = target.getFrontMostApp(); RemoteUIAWindow win = app.getMainWindow(); getAlert(win); UIAElement el = win.findElements(new NameCriteria("Show Simple")).get(2); // opens an alert. el.tap(); // should throw.The alert prevent interacting with the background. el.tap(); } finally { if (driver != null) { driver.quit(); } } } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Response handle() throws Exception { waitForPageToLoad(); int implicitWait = (Integer) getConf("implicit_wait", 0); long deadline = System.currentTimeMillis() + implicitWait; List<RemoteWebElement> elements = null; do { try { elements = findElements(); if (elements.size() != 0) { break; } } catch (NoSuchElementException e) { //ignore. } catch (RemoteExceptionException e2) { // ignore. // if the page is reloading, the previous nodeId won't be there anymore, resulting in a // RemoteExceptionException: Could not find node with given id.Keep looking. } } while (System.currentTimeMillis() < deadline); JSONArray array = new JSONArray(); List<JSONObject> list = new ArrayList<JSONObject>(); for (RemoteWebElement el : elements) { list.add(new JSONObject().put("ELEMENT", "" + el.getNodeId().getId())); } Response resp = new Response(); resp.setSessionId(getSession().getSessionId()); resp.setStatus(0); resp.setValue(list); return resp; }
#vulnerable code @Override public Response handle() throws Exception { JSONObject payload = getRequest().getPayload(); String type = payload.getString("using"); String value = payload.getString("value"); RemoteWebElement element = null; if (getRequest().hasVariable(":reference")) { int id = Integer.parseInt(getRequest().getVariableValue(":reference")); element = new RemoteWebElement(new NodeId(id), getSession()); } else { element = getSession().getWebInspector().getDocument(); } List<RemoteWebElement> res; if ("link text".equals(type)) { res = element.findElementsByLinkText(value, false); } else if ("partial link text".equals(type)) { res = element.findElementsByLinkText(value, true); } else if ("xpath".equals(type)) { res = element.findElementsByXpath(value); } else { String cssSelector = ToCSSSelectorConvertor.convertToCSSSelector(type, value); res = element.findElementsByCSSSelector(cssSelector); } JSONArray array = new JSONArray(); List<JSONObject> list = new ArrayList<JSONObject>(); for (RemoteWebElement el : res) { list.add(new JSONObject().put("ELEMENT", "" + el.getNodeId().getId())); } Response resp = new Response(); resp.setSessionId(getSession().getSessionId()); resp.setStatus(0); resp.setValue(list); return resp; } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onPageLoad() { System.err.println("new page loaded"); pageLoaded = true; reset(); try { Thread.sleep(5000); System.out.println( "on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument()) .optJSONObject("root").optString("documentURL")); } catch (Exception e) { e.printStackTrace(); } }
#vulnerable code @Override public void onPageLoad() { System.err.println("new page loaded"); pageLoaded = true; reset(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onPageLoad() { pageLoaded = true; reset(); }
#vulnerable code @Override public void onPageLoad() { System.err.println("new page loaded"); pageLoaded = true; reset(); try { Thread.sleep(5000); System.out.println( "on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument()) .optJSONObject("root").optString("documentURL")); } catch (Exception e) { e.printStackTrace(); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setValueNative(String value) throws Exception { /*WebElement el = getNativeElement(); WorkingMode origin = session.getMode(); try { session.setMode(WorkingMode.Native); el.click(); RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard(); if ("\n".equals(value)) { keyboard.findElement(new NameCriteria("Return")).tap(); } else { keyboard.sendKeys(value); } Criteria iphone = new NameCriteria("Done"); Criteria ipad = new NameCriteria("Hide keyboard"); UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone)); but.tap(); // session.getNativeDriver().pinchClose(300, 400, 50, 100, 1); } finally { session.setMode(origin); }*/ WorkingMode origin = session.getMode(); session.setMode(WorkingMode.Native); ((JavascriptExecutor) nativeDriver).executeScript(getNativeElementClickOnItAndTypeUsingKeyboardScript(value)); session.setMode(origin); }
#vulnerable code public void setValueNative(String value) throws Exception { UIAElement el = getNativeElement(); WorkingMode origin = session.getMode(); try { session.setMode(WorkingMode.Native); UIARect rect = el.getRect(); int x = rect.getX() + rect.getWidth() - 1; int y = rect.getY() + rect.getHeight() / 2; // TODO freynaud : tap() should take a param like middle, topLeft, // bottomRight to save 1 call. session.getNativeDriver().tap(x, y); RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard(); if ("\n".equals(value)) { keyboard.findElement(new NameCriteria("Return")).tap(); } else { keyboard.sendKeys(value); } Criteria iphone = new NameCriteria("Done"); Criteria ipad = new NameCriteria("Hide keyboard"); UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone)); but.tap(); // session.getNativeDriver().pinchClose(300, 400, 50, 100, 1); } finally { session.setMode(origin); } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onPageLoad() { pageLoaded = true; reset(); }
#vulnerable code @Override public void onPageLoad() { System.err.println("new page loaded"); pageLoaded = true; reset(); try { Thread.sleep(5000); System.out.println( "on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument()) .optJSONObject("root").optString("documentURL")); } catch (Exception e) { e.printStackTrace(); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void persist(File screenshot, JSONObject tree, File dest) throws FileNotFoundException, IOException, JSONException { IOUtils.copy(new StringReader(tree.toString(2)), new FileOutputStream(dest), "UTF-8"); }
#vulnerable code public static void persist(File screenshot, JSONObject tree, File dest) throws FileNotFoundException, IOException, JSONException { System.out.println(screenshot.getAbsolutePath()); FileWriter write = new FileWriter(dest); IOUtils.copy(new StringReader(tree.toString(2)), new FileOutputStream(dest), "UTF-8"); System.out.println(dest.getAbsolutePath()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void setValueNative(String value) throws Exception { /*WebElement el = getNativeElement(); WorkingMode origin = session.getMode(); try { session.setMode(WorkingMode.Native); el.click(); RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard(); if ("\n".equals(value)) { keyboard.findElement(new NameCriteria("Return")).tap(); } else { keyboard.sendKeys(value); } Criteria iphone = new NameCriteria("Done"); Criteria ipad = new NameCriteria("Hide keyboard"); UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone)); but.tap(); // session.getNativeDriver().pinchClose(300, 400, 50, 100, 1); } finally { session.setMode(origin); }*/ WorkingMode origin = session.getMode(); session.setMode(WorkingMode.Native); ((JavascriptExecutor) nativeDriver).executeScript(getNativeElementClickOnItAndTypeUsingKeyboardScript(value)); session.setMode(origin); }
#vulnerable code public void setValueNative(String value) throws Exception { UIAElement el = getNativeElement(); WorkingMode origin = session.getMode(); try { session.setMode(WorkingMode.Native); UIARect rect = el.getRect(); int x = rect.getX() + rect.getWidth() - 1; int y = rect.getY() + rect.getHeight() / 2; // TODO freynaud : tap() should take a param like middle, topLeft, // bottomRight to save 1 call. session.getNativeDriver().tap(x, y); RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard(); if ("\n".equals(value)) { keyboard.findElement(new NameCriteria("Return")).tap(); } else { keyboard.sendKeys(value); } Criteria iphone = new NameCriteria("Done"); Criteria ipad = new NameCriteria("Hide keyboard"); UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone)); but.tap(); // session.getNativeDriver().pinchClose(300, 400, 50, 100, 1); } finally { session.setMode(origin); } } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean getDataFlag(int propertyId, int id) { return ((this.getDataPropertyByte(propertyId).data & 0xff) & (1 << id)) > 0; }
#vulnerable code public boolean getDataFlag(int propertyId, int id) { return ((this.getDataPropertyByte(propertyId) == null ? 0 : this.getDataPropertyByte(propertyId).data & 0xff) & (1 << id)) > 0; } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSpecialStyles() throws Exception { File f = new File("src/test/resources/special_types.xlsx"); Map<Integer, List<Cell>> contents = new HashMap<>(); try(Workbook wb = StreamingReader.builder().open(f)) { for(Row row : wb.getSheetAt(0)) { contents.put(row.getRowNum(), new ArrayList<Cell>()); for(Cell c : row) { if(c.getColumnIndex() > 0) { contents.get(row.getRowNum()).add(c); } } } } SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); assertThat(contents.size(), equalTo(2)); assertThat(contents.get(0).size(), equalTo(4)); assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14")); assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014"))); assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15")); assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015"))); assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015")); assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015"))); assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05")); assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015"))); assertThat(contents.get(1).size(), equalTo(4)); assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12")); assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312)); assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042")); assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0)); assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12")); assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145)); assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)")); assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0)); }
#vulnerable code @Test public void testSpecialStyles() throws Exception { File f = new File("src/test/resources/special_types.xlsx"); Map<Integer, List<Cell>> contents = new HashMap<>(); try(StreamingReader reader = StreamingReader.builder().read(f)) { for(Row row : reader) { contents.put(row.getRowNum(), new ArrayList<Cell>()); for(Cell c : row) { if(c.getColumnIndex() > 0) { contents.get(row.getRowNum()).add(c); } } } } SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); assertThat(contents.size(), equalTo(2)); assertThat(contents.get(0).size(), equalTo(4)); assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14")); assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014"))); assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15")); assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015"))); assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015")); assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015"))); assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05")); assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015"))); assertThat(contents.get(1).size(), equalTo(4)); assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12")); assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312)); assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042")); assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0)); assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12")); assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145)); assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)")); assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0)); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSpecialStyles() throws Exception { File f = new File("src/test/resources/special_types.xlsx"); Map<Integer, List<Cell>> contents = new HashMap<>(); try(Workbook wb = StreamingReader.builder().open(f)) { for(Row row : wb.getSheetAt(0)) { contents.put(row.getRowNum(), new ArrayList<Cell>()); for(Cell c : row) { if(c.getColumnIndex() > 0) { contents.get(row.getRowNum()).add(c); } } } } SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); assertThat(contents.size(), equalTo(2)); assertThat(contents.get(0).size(), equalTo(4)); assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14")); assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014"))); assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15")); assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015"))); assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015")); assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015"))); assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05")); assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015"))); assertThat(contents.get(1).size(), equalTo(4)); assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12")); assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312)); assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042")); assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0)); assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12")); assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145)); assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)")); assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0)); }
#vulnerable code @Test public void testSpecialStyles() throws Exception { File f = new File("src/test/resources/special_types.xlsx"); Map<Integer, List<Cell>> contents = new HashMap<>(); try(StreamingReader reader = StreamingReader.builder().read(f)) { for(Row row : reader) { contents.put(row.getRowNum(), new ArrayList<Cell>()); for(Cell c : row) { if(c.getColumnIndex() > 0) { contents.get(row.getRowNum()).add(c); } } } } SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); assertThat(contents.size(), equalTo(2)); assertThat(contents.get(0).size(), equalTo(4)); assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14")); assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014"))); assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15")); assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015"))); assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015")); assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015"))); assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05")); assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015"))); assertThat(contents.get(1).size(), equalTo(4)); assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12")); assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312)); assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042")); assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0)); assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12")); assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145)); assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)")); assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0)); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void install() throws InstallationException { // use static lock object for a synchronized block synchronized (LOCK) { if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){ nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT; } if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){ npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT; } if (!nodeIsAlreadyInstalled()) { logger.info("Installing node version {}", nodeVersion); if (!nodeVersion.startsWith("v")) { logger.warn("Node version does not start with naming convention 'v'."); } if (config.getPlatform().isWindows()) { installNodeForWindows(); } else { installNodeDefault(); } } if (!npmIsAlreadyInstalled()) { installNpm(); } } }
#vulnerable code public void install() throws InstallationException { if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){ nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT; } if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){ npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT; } synchronized (lock) { if (!nodeIsAlreadyInstalled()) { logger.info("Installing node version {}", nodeVersion); if (!nodeVersion.startsWith("v")) { logger.warn("Node version does not start with naming convention 'v'."); } if (config.getPlatform().isWindows()) { installNodeForWindows(); } else { installNodeDefault(); } } if (!npmIsAlreadyInstalled()) { installNpm(); } } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static List<String> buildArguments(ProxyConfig proxyConfig, String npmRegistryURL) { List<String> arguments = new ArrayList<String>(); if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){ arguments.add ("--registry=" + npmRegistryURL); } if(!proxyConfig.isEmpty()){ Proxy proxy = null; if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){ proxy = proxyConfig.getProxyForUrl(npmRegistryURL); } if(proxy == null){ proxy = proxyConfig.getSecureProxy(); } if(proxy == null){ proxy = proxyConfig.getInsecureProxy(); } arguments.add("--https-proxy=" + proxy.getUri().toString()); arguments.add("--proxy=" + proxy.getUri().toString()); final String nonProxyHosts = proxy.getNonProxyHosts(); if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) { final String[] nonProxyHostList = nonProxyHosts.split("\\|"); for (String nonProxyHost: nonProxyHostList) { arguments.add("--noproxy=" + nonProxyHost.replace("*", "")); } } } return arguments; }
#vulnerable code static List<String> buildArguments(ProxyConfig proxyConfig, String npmRegistryURL) { List<String> arguments = new ArrayList<String>(); if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){ arguments.add ("--registry=" + npmRegistryURL); } if(!proxyConfig.isEmpty()){ Proxy proxy = null; if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){ proxy = proxyConfig.getProxyForUrl(npmRegistryURL); } if(proxy == null){ proxy = proxyConfig.getSecureProxy(); } if(proxy == null){ proxy = proxyConfig.getInsecureProxy(); } arguments.add("--https-proxy=" + proxy.getUri().toString()); arguments.add("--proxy=" + proxy.getUri().toString()); final String nonProxyHosts = proxy.getNonProxyHosts(); if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) { arguments.add("--noproxy=" + nonProxyHosts.replace('|',',')); } } return arguments; } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void install() throws InstallationException { // use static lock object for a synchronized block synchronized (LOCK) { if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){ nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT; } if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){ npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT; } if (!nodeIsAlreadyInstalled()) { logger.info("Installing node version {}", nodeVersion); if (!nodeVersion.startsWith("v")) { logger.warn("Node version does not start with naming convention 'v'."); } if (config.getPlatform().isWindows()) { installNodeForWindows(); } else { installNodeDefault(); } } if (!npmIsAlreadyInstalled()) { installNpm(); } } }
#vulnerable code public void install() throws InstallationException { if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){ nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT; } if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){ npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT; } synchronized (lock) { if (!nodeIsAlreadyInstalled()) { logger.info("Installing node version {}", nodeVersion); if (!nodeVersion.startsWith("v")) { logger.warn("Node version does not start with naming convention 'v'."); } if (config.getPlatform().isWindows()) { installNodeForWindows(); } else { installNodeDefault(); } } if (!npmIsAlreadyInstalled()) { installNpm(); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void reload() { if (backingFile != null) { FileInputStream fis = null; try { fis = new FileInputStream(backingFile); final InsecureStore clone = fromXml(fis); if (clone != null) { this.Tokens.clear(); this.Tokens.putAll(clone.Tokens); this.Credentials.clear(); this.Credentials.putAll(clone.Credentials); } } catch (FileNotFoundException e) { Trace.writeLine("backingFile '" + backingFile.getAbsolutePath() + "' did not exist."); } finally { IOUtils.closeQuietly(fis); } } }
#vulnerable code void save() { if (backingFile != null) { // TODO: consider creating a backup of the file, if it exists, before overwriting it FileOutputStream fos = null; try { fos = new FileOutputStream(backingFile); final PrintStream printStream = new PrintStream(fos); toXml(printStream); } catch (final FileNotFoundException e) { throw new Error("Error during save()", e); } finally { IOUtils.closeQuietly(fos); } } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static InsecureStore clone(InsecureStore inputStore) { ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { baos = new ByteArrayOutputStream(); inputStore.toXml(baos); final String xmlString = baos.toString(); bais = new ByteArrayInputStream(xmlString.getBytes()); final InsecureStore result = InsecureStore.fromXml(bais); return result; } finally { IOUtils.closeQuietly(baos); IOUtils.closeQuietly(bais); } }
#vulnerable code static InsecureStore clone(InsecureStore inputStore) { ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { baos = new ByteArrayOutputStream(); final PrintStream ps = new PrintStream(baos); inputStore.toXml(ps); ps.flush(); final String xmlString = baos.toString(); bais = new ByteArrayInputStream(xmlString.getBytes()); final InsecureStore result = InsecureStore.fromXml(bais); return result; } finally { IOUtils.closeQuietly(baos); IOUtils.closeQuietly(bais); } } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public DataFrame<R, String> read(Consumer<DbSourceOptions<R>> configurator) throws DataFrameException { final DbSourceOptions<R> options = initOptions(new DbSourceOptions<>(), configurator); try (Connection conn = options.getConnection()) { conn.setAutoCommit(options.isAutoCommit()); conn.setReadOnly(options.isReadOnly()); final int fetchSize = options.getFetchSize().orElse(1000); final SQL sql = SQL.of(options.getSql(), options.getParameters().orElse(new Object[0])); return sql.executeQuery(conn, fetchSize, rs -> read(rs, options)); } catch (Exception ex) { throw new DataFrameException("Failed to create DataFrame from database request: " + options, ex); } }
#vulnerable code @Override public DataFrame<R, String> read(Consumer<DbSourceOptions<R>> configurator) throws DataFrameException { final DbSourceOptions<R> options = initOptions(new DbSourceOptions<>(), configurator); try (Connection conn = options.getConnection()) { final SQL sql = SQL.of(options.getSql(), options.getParameters().orElse(new Object[0])); return sql.executeQuery(conn, rs -> read(rs, options)); } catch (Exception ex) { throw new DataFrameException("Failed to create DataFrame from database request: " + options, ex); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testParse() throws ParseException, IOException, Exception { for (String inputString : getInputStrings()) { JSONObject parsed = parser.parse(inputString.getBytes()); assertNotNull(parsed); System.out.println(parsed); JSONParser parser = new JSONParser(); Map<?, ?> json=null; try { json = (Map<?, ?>) parser.parse(parsed.toJSONString()); assertEquals(true, validateJsonData(super.getSchemaJsonString(), json.toString())); } catch (ParseException e) { e.printStackTrace(); } } }
#vulnerable code public void testParse() throws ParseException, IOException, Exception { // JSONObject parsed = iseParser.parse(getRawMessage().getBytes()); // assertNotNull(parsed); URL log_url = getClass().getClassLoader().getResource("IseSample.log"); BufferedReader br = new BufferedReader(new FileReader(log_url.getFile())); String line = ""; while ((line = br.readLine()) != null) { System.out.println(line); JSONObject parsed = iseParser.parse(line.getBytes()); System.out.println(parsed); assertEquals(true, super.validateJsonData(super.getSchemaJsonString(), parsed.toString())); } br.close(); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testParse() throws IOException, Exception { for (String inputString : getInputStrings()) { JSONObject parsed = parser.parse(inputString.getBytes()); assertNotNull(parsed); System.out.println(parsed); JSONParser parser = new JSONParser(); Map<?, ?> json=null; try { json = (Map<?, ?>) parser.parse(parsed.toJSONString()); assertEquals(true, validateJsonData(super.getSchemaJsonString(), json.toString())); } catch (ParseException e) { e.printStackTrace(); } } }
#vulnerable code public void testParse() throws IOException, Exception { URL log_url = getClass().getClassLoader().getResource("LancopeSample.log"); BufferedReader br; try { br = new BufferedReader(new FileReader(log_url.getFile())); String line = ""; while ((line = br.readLine()) != null) { System.out.println(line); assertNotNull(line); JSONObject parsed = lancopeParser.parse(line.getBytes()); System.out.println(parsed); assertEquals(true, validateJsonData(super.getSchemaJsonString(), parsed.toString())); } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected Object createTest() throws Exception { instances = createHierarchicalFixtures(); return instances.getLast(); }
#vulnerable code @Override protected Object createTest() throws Exception { ensureHierarchicalFixturesAreValid(); return instances.getLast(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected Statement withBefores(final FrameworkMethod method, final Object target, final Statement next) { Statement statement = next; for (int i = instances.size() - 1; i >= 0; i--) { final Object instance = instances.get(i); final TestClass tClass = TestClassPool.forClass(instance.getClass()); final List<FrameworkMethod> befores = tClass.getAnnotatedMethods(Before.class); statement = befores.isEmpty() ? statement : new RunBefores(statement, befores, instance); } return statement; }
#vulnerable code @Override protected Statement withBefores(final FrameworkMethod method, final Object target, final Statement next) { Statement statement = next; for (int i = instances.size() - 1; i >= 0; i--) { final Object instance = instances.get(i); final TestClass tClass = new TestClass(instance.getClass()); final List<FrameworkMethod> befores = tClass.getAnnotatedMethods(Before.class); statement = befores.isEmpty() ? statement : new RunBefores(statement, befores, instance); } return statement; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void registerResources(final PluginAnnotation<T> pluginAnnotation, final ClassLoader classLoader) throws IOException { final T annot = pluginAnnotation.getAnnotation(); WatchEventDTO watchEventDTO = WatchEventDTO.parse(annot); String path = watchEventDTO.getPath(); // normalize if (path == null || path.equals(".") || path.equals("/")) path = ""; if (path.endsWith("/")) path = path.substring(0, path.length() - 2); // classpath resources (already should contain extraClasspath) Enumeration<URL> en = classLoader.getResources(path); while (en.hasMoreElements()) { try { URI uri = en.nextElement().toURI(); // check that this is a local accessible file (not vfs inside JAR etc.) try { new File(uri); } catch (Exception e) { LOGGER.trace("Skipping uri {}, not a local file.", uri); continue; } LOGGER.debug("Registering resource listener on classpath URI {}", uri); registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, uri); } catch (URISyntaxException e) { LOGGER.error("Unable convert root resource path URL to URI", e); } } // add extra directories for watchResources property if (!watchEventDTO.isClassFileEvent()) { for (URL url : pluginManager.getPluginConfiguration(classLoader).getWatchResources()) { try { Path watchResourcePath = Paths.get(url.toURI()); Path pathInWatchResource = watchResourcePath.resolve(path); if (pathInWatchResource.toFile().exists()) { LOGGER.debug("Registering resource listener on watchResources URI {}", pathInWatchResource.toUri()); registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, pathInWatchResource.toUri()); } } catch (URISyntaxException e) { LOGGER.error("Unable convert watch resource path URL {} to URI", e, url); } } } }
#vulnerable code private void registerResources(final PluginAnnotation<T> pluginAnnotation, final ClassLoader classLoader) throws IOException { final T annot = pluginAnnotation.getAnnotation(); WatchEventDTO watchEventDTO = WatchEventDTO.parse(annot); String path = watchEventDTO.getPath(); // normalize if (path.equals(".") || path.equals("/")) path = ""; if (path.endsWith("/")) path = path.substring(0, path.length() - 2); // classpath resources (already should contain extraClasspath) Enumeration<URL> en = classLoader.getResources(path); while (en.hasMoreElements()) { try { URI uri = en.nextElement().toURI(); // check that this is a local accessible file (not vfs inside JAR etc.) try { new File(uri); } catch (Exception e) { LOGGER.trace("Skipping uri {}, not a local file.", uri); continue; } LOGGER.debug("Registering resource listener on classpath URI {}", uri); registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, uri); } catch (URISyntaxException e) { LOGGER.error("Unable convert root resource path URL to URI", e); } } // add extra directories for watchResources property if (!watchEventDTO.isClassFileEvent()) { for (URL url : pluginManager.getPluginConfiguration(classLoader).getWatchResources()) { try { Path watchResourcePath = Paths.get(url.toURI()); Path pathInWatchResource = watchResourcePath.resolve(path); if (pathInWatchResource.toFile().exists()) { LOGGER.debug("Registering resource listener on watchResources URI {}", pathInWatchResource.toUri()); registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, pathInWatchResource.toUri()); } } catch (URISyntaxException e) { LOGGER.error("Unable convert watch resource path URL {} to URI", e, url); } } } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void register(Object generatorStrategy, Object classGenerator, byte[] bytes) { try { generatorParams.put(getClassName(bytes), new GeneratorParams(generatorStrategy, classGenerator)); } catch (Exception e) { LOGGER.error("Error saving parameters of a creation of a Cglib proxy", e); } }
#vulnerable code public static void register(Object generatorStrategy, Object classGenerator, byte[] bytes) { try { ClassPool classPool = ProxyTransformationUtils.getClassPool(generatorStrategy.getClass().getClassLoader()); CtClass cc = classPool.makeClass(new ByteArrayInputStream(bytes), false); generatorParams.put(cc.getName(), new GeneratorParams(generatorStrategy, classGenerator)); cc.detach(); } catch (IOException | RuntimeException e) { LOGGER.error("Error saving parameters of a creation of a Cglib proxy", e); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException { LOGGER.trace("Scanning JAR file '{}'", urlFile); int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); JarFile jarFile = null; String rootEntryPath; try { if (separatorIndex != -1) { String jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); } else { rootEntryPath = ""; jarFile = new JarFile(urlFile); } if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { rootEntryPath = rootEntryPath + "/"; } for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); // class files inside entry if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) { LOGGER.trace("Visiting JAR entry {}", entryPath); visitor.visit(jarFile.getInputStream(entry)); } } } finally { if (jarFile != null) { jarFile.close(); } } }
#vulnerable code private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException { LOGGER.trace("Scanning JAR file '{}'", urlFile); int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR); JarFile jarFile; String rootEntryPath; if (separatorIndex != -1) { String jarFileUrl = urlFile.substring(0, separatorIndex); rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length()); jarFile = getJarFile(jarFileUrl); } else { rootEntryPath = ""; jarFile = new JarFile(urlFile); } if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) { rootEntryPath = rootEntryPath + "/"; } for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) { JarEntry entry = entries.nextElement(); String entryPath = entry.getName(); // class files inside entry if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) { LOGGER.trace("Visiting JAR entry {}", entryPath); visitor.visit(jarFile.getInputStream(entry)); } } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void defineBean(BeanDefinition candidate) { synchronized (getClass()) { // TODO sychronize on DefaultListableFactory.beanDefinitionMap? ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); candidate.setScope(scopeMetadata.getScopeName()); String beanName = this.beanNameGenerator.generateBeanName(candidate, registry); if (candidate instanceof AbstractBeanDefinition) { postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); } if (candidate instanceof AnnotatedBeanDefinition) { processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate); } removeIfExists(beanName); BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName); definitionHolder = applyScopedProxyMode(scopeMetadata, definitionHolder, registry); LOGGER.reload("Registering Spring bean '{}'", beanName); LOGGER.debug("Bean definition '{}'", beanName, candidate); registerBeanDefinition(definitionHolder, registry); freezeConfiguration(); } ProxyReplacer.clearAllProxies(); }
#vulnerable code public void defineBean(BeanDefinition candidate) { synchronized (getClass()) { // TODO sychronize on DefaultListableFactory.beanDefinitionMap? ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); candidate.setScope(scopeMetadata.getScopeName()); String beanName = this.beanNameGenerator.generateBeanName(candidate, registry); if (candidate instanceof AbstractBeanDefinition) { postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); } if (candidate instanceof AnnotatedBeanDefinition) { processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate); } clearCahceIfExists(beanName); DefaultListableBeanFactory bf = maybeRegistryToBeanFactory(); // use previous singleton bean, if modified class is not bean, a exception will be throw Object bean; try { bean = bf.getBean(beanName); } catch (NoSuchBeanDefinitionException e) { LOGGER.warning("{} is not managed by spring", beanName); return; } BeanWrapper bw = new BeanWrapperImpl(bf.getBean(beanName)); RootBeanDefinition rootBeanDefinition = (RootBeanDefinition)ReflectionHelper.invoke(bf, AbstractBeanFactory.class, "getMergedLocalBeanDefinition", new Class[]{String.class}, beanName); ReflectionHelper.invoke(bf, AbstractAutowireCapableBeanFactory.class, "populateBean", new Class[]{String.class, RootBeanDefinition.class, BeanWrapper.class}, beanName,rootBeanDefinition , bw); freezeConfiguration(); ProxyReplacer.clearAllProxies(); } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void savePolicyFile(String text) { try (FileOutputStream fos = new FileOutputStream(filePath)) { IOUtils.write(text, fos, Charset.forName("UTF-8")); } catch (IOException e) { e.printStackTrace(); throw new Error("Policy save error"); } }
#vulnerable code private void savePolicyFile(String text) { try { FileOutputStream fos = new FileOutputStream(filePath); fos.write(text.getBytes()); fos.close(); } catch (IOException e) { e.printStackTrace(); throw new Error("IO error occurred"); } } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPostWithMultipartFormFieldsAndFile() throws IOException { String fileName = "GrandCanyon.txt"; String fileContent = HttpPostRequestTest.VALUE; String divider = UUID.randomUUID().toString(); String header = "POST " + HttpServerTest.URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data; boundary=" + divider + "\n"; String content = "--" + divider + "\r\n" + "Content-Disposition: form-data; name=\"" + HttpPostRequestTest.FIELD + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: image/jpeg\r\n" + "\r\n" + fileContent + "\r\n" + "--" + divider + "\r\n" + "Content-Disposition: form-data; name=\"" + HttpPostRequestTest.FIELD2 + "\"\r\n" + "\r\n" + HttpPostRequestTest.VALUE2 + "\r\n" + "--" + divider + "--\r\n"; int size = content.length() + header.length(); int contentLengthHeaderValueSize = String.valueOf(size).length(); int contentLength = size + contentLengthHeaderValueSize + HttpPostRequestTest.CONTENT_LENGTH.length(); String input = header + HttpPostRequestTest.CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content; invokeServer(input); assertEquals("Parms count did not match.", 2, this.testServer.parms.size()); assertEquals("Parameters count did not match.", 2, this.testServer.parameters.size()); assertEquals("Param value did not match", HttpPostRequestTest.VALUE2, this.testServer.parms.get(HttpPostRequestTest.FIELD2)); assertEquals("Parameter value did not match", HttpPostRequestTest.VALUE2, this.testServer.parameters.get(HttpPostRequestTest.FIELD2).get(0)); BufferedReader reader = new BufferedReader(new FileReader(this.testServer.files.get(HttpPostRequestTest.FIELD))); List<String> lines = readLinesFromFile(reader); assertLinesOfText(new String[]{ fileContent }, lines); }
#vulnerable code @Test public void testPostWithMultipartFormFieldsAndFile() throws IOException { String fileName = "GrandCanyon.txt"; String fileContent = HttpPostRequestTest.VALUE; String divider = UUID.randomUUID().toString(); String header = "POST " + HttpServerTest.URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data; boundary=" + divider + "\n"; String content = "--" + divider + "\r\n" + "Content-Disposition: form-data; name=\"" + HttpPostRequestTest.FIELD + "\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: image/jpeg\r\n" + "\r\n" + fileContent + "\r\n" + "--" + divider + "\r\n" + "Content-Disposition: form-data; name=\"" + HttpPostRequestTest.FIELD2 + "\"\r\n" + "\r\n" + HttpPostRequestTest.VALUE2 + "\r\n" + "--" + divider + "--\r\n"; int size = content.length() + header.length(); int contentLengthHeaderValueSize = String.valueOf(size).length(); int contentLength = size + contentLengthHeaderValueSize + HttpPostRequestTest.CONTENT_LENGTH.length(); String input = header + HttpPostRequestTest.CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content; invokeServer(input); assertEquals("Parameter count did not match.", 2, this.testServer.parms.size()); assertEquals("Parameter value did not match", HttpPostRequestTest.VALUE2, this.testServer.parms.get(HttpPostRequestTest.FIELD2)); BufferedReader reader = new BufferedReader(new FileReader(this.testServer.files.get(HttpPostRequestTest.FIELD))); List<String> lines = readLinesFromFile(reader); assertLinesOfText(new String[]{ fileContent }, lines); } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shutdown() throws Exception { Client client = TestGraphUtil.instance.createClient(); client.getDelegate().shutdown(); }
#vulnerable code @Test public void shutdown() throws Exception { Client client = TestGraphUtil.instance.createClient(); client.delegate().shutdown(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleError(Session s, Throwable exception) { doSaveExecution(s, session -> { members.unregister(session.getId()); eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage())); } ); }
#vulnerable code public void handleError(Session s, Throwable exception) { doSaveExecution(new SessionWrapper(s), session -> { members.unregister(session.getId()); eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage())); } ); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); // when server.handle(Message.create()// .signal("create")// .build(), s1); String conversationKey = s1Matcher.getMessage().getContent(); s1Matcher.reset(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); // then assertThat(s1Matcher.getMessages().size(), is(2)); assertMatch(s1Matcher, 0, "s2", "s1", "joined", EMPTY); assertMatch(s1Matcher, 1, "s2", "s1", "offerRequest", EMPTY); assertThat(s2Matcher.getMessages().size(), is(1)); assertMatch(s2Matcher, 0, EMPTY, "s2", "joined", conversationKey); }
#vulnerable code @Test public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception { // given MessageMatcher s1Matcher = new MessageMatcher(); MessageMatcher s2Matcher = new MessageMatcher(); Session s1 = mockSession("s1", s1Matcher); Session s2 = mockSession("s2", s2Matcher); server.register(s1); server.register(s2); // when server.handle(Message.create()// .signal("create")// .build(), s1); String conversationKey = s1Matcher.getMessage().getContent(); s1Matcher.reset(); server.handle(Message.create()// .signal("join")// .content(conversationKey)// .build(), s2); // then assertThat(s1Matcher.getMessages().size(), is(2)); assertThat(s1Matcher.getMessage().getFrom(), is("s2")); assertThat(s1Matcher.getMessage().getTo(), is("s1")); assertThat(s1Matcher.getMessage().getSignal(), is("joined")); assertThat(s1Matcher.getMessage(1).getFrom(), is("s2")); assertThat(s1Matcher.getMessage(1).getTo(), is("s1")); assertThat(s1Matcher.getMessage(1).getSignal(), is("offerRequest")); assertThat(s2Matcher.getMessages().size(), is(1)); assertThat(s2Matcher.getMessage().getSignal(), is("joined")); assertThat(s2Matcher.getMessage().getContent(), is(conversationKey)); } #location 30 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void send(InternalMessage message, int retry) { if (message.getSignal() != Signal.PING) { log.debug("Outgoing: " + message.transformToExternalMessage()); } if (message.getSignal() == Signal.ERROR) { tryToSendErrorMessage(message); return; } Member destination = message.getTo(); if (destination == null || !destination.getSession().isOpen()) { log.warn("Destination member is not set or session is closed! Message will not be send: " + message.transformToExternalMessage()); return; } members.findBy(destination.getId()).ifPresent(member -> lockAndRun(message, member, retry) ); }
#vulnerable code private void send(InternalMessage message, int retry) { Message messageToSend = message.transformToExternalMessage(); if (message.getSignal() != Signal.PING) { log.info("Outgoing: " + toString()); } Session destSession = message.getTo().getSession(); if (!destSession.isOpen()) { log.warn("Session is closed! Message will not be send: "); return; } try { RemoteEndpoint.Basic basic = destSession.getBasicRemote(); synchronized (basic) { basic.sendObject(messageToSend); } } catch (Exception e) { if (retry >= 0) { log.info("Retrying... " + messageToSend); send(message, --retry); } log.error("Unable to send message: " + messageToSend + " error during sending!"); throw new RuntimeException("Unable to send message: " + messageToSend, e); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") private Object getListArg(ManagedList<XmlManagedNode> values, Class<?> setterParamType) { Collection<Object> collection = null; if (VerifyUtils.isNotEmpty(values.getTypeName())) { try { collection = (Collection<Object>) XmlApplicationContext.class .getClassLoader() .loadClass(values.getTypeName()) .newInstance(); } catch (Throwable t) { log.error("list inject error", t); } } else { collection = (setterParamType == null ? new ArrayList<>() : ConvertUtils.getCollectionObj(setterParamType)); } if (collection != null) { for (XmlManagedNode item : values) { Object listValue = getInjectArg(item, null); collection.add(listValue); } } return collection; }
#vulnerable code @SuppressWarnings("unchecked") private Object getListArg(ManagedList<XmlManagedNode> values, Class<?> setterParamType) { Collection<Object> collection = null; if (VerifyUtils.isNotEmpty(values.getTypeName())) { try { collection = (Collection<Object>) XmlApplicationContext.class .getClassLoader().loadClass(values.getTypeName()) .newInstance(); } catch (Throwable t) { log.error("list inject error", t); } } else { collection = (setterParamType == null ? new ArrayList<Object>() : ConvertUtils.getCollectionObj(setterParamType)); } for (XmlManagedNode item : values) { Object listValue = getInjectArg(item, null); collection.add(listValue); } return collection; } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void parseProperties(Properties properties) { for (Entry<Object, Object> entry : properties.entrySet()) { String name = (String) entry.getKey(); String value = (String) entry.getValue(); String[] strs = StringUtils.split(value, ','); switch (strs.length) { case 1: createLog(name, strs[0], null, false); break; case 2: if("console".equalsIgnoreCase(strs[1])) { createLog(name, strs[0], null, true); } else { createLog(name, strs[0], strs[1], false); } break; case 3: createLog(name, strs[0], strs[1], "console".equalsIgnoreCase(strs[2])); break; default: System.err.println("The log " + name + " configuration format is illegal. It will use default log configuration"); createLog(name, DEFAULT_LOG_LEVEL, null, false); break; } } }
#vulnerable code private void parseProperties(Properties properties) { for (Entry<Object, Object> entry : properties.entrySet()) { String name = (String) entry.getKey(); String value = (String) entry.getValue(); // System.out.println(name + "|" + value); String[] strs = StringUtils.split(value, ','); if (strs.length < 2) { System.err.println("the log configuration file format is illegal"); continue; } String path = strs[1]; FileLog fileLog = new FileLog(); fileLog.setName(name); fileLog.setLevel(LogLevel.fromName(strs[0])); if ("console".equalsIgnoreCase(path)) { fileLog.setFileOutput(false); fileLog.setConsoleOutput(true); } else { File file = new File(path); if(file.exists() && file.isDirectory()) { fileLog.setPath(path); fileLog.setFileOutput(true); } else { boolean success = file.mkdirs(); if(success) { fileLog.setPath(path); fileLog.setFileOutput(true); } else { System.err.println("create directory " + path + " failure"); continue; } } if (strs.length > 2) fileLog.setConsoleOutput("console".equalsIgnoreCase(strs[2])); } logMap.put(name, fileLog); System.out.println("initialize log " + fileLog.toString() + " success"); } } #location 32 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void render(RoutingContext ctx, int status, Throwable t) { HttpStatus.Code code = Optional.ofNullable(HttpStatus.getCode(status)).orElse(HttpStatus.Code.INTERNAL_SERVER_ERROR); String title = status + " " + code.getMessage(); String content; switch (code) { case NOT_FOUND: { content = "The resource " + ctx.getURI().getPath() + " is not found"; } break; case INTERNAL_SERVER_ERROR: { content = "The server internal error. <br/>" + (t != null ? t.getMessage() : ""); } break; default: { content = title + "<br/>" + (t != null ? t.getMessage() : ""); } break; } ctx.setStatus(status).put(HttpHeader.CONTENT_TYPE, "text/html") .write("<!DOCTYPE html>") .write("<html>") .write("<head>") .write("<title>") .write(title) .write("</title>") .write("</head>") .write("<body>") .write("<h1> " + title + " </h1>") .write("<p>" + content + "</p>") .write("<hr/>") .write("<footer><em>powered by Firefly " + Version.value + "</em></footer>") .write("</body>") .end("</html>"); }
#vulnerable code public void render(RoutingContext ctx, int status, Throwable t) { HttpStatus.Code code = HttpStatus.getCode(status); String title = status + " " + (code != null ? code.getMessage() : "error"); String content; switch (code) { case NOT_FOUND: { content = "The resource " + ctx.getURI().getPath() + " is not found"; } break; case INTERNAL_SERVER_ERROR: { content = "The server internal error. <br/>" + (t != null ? t.getMessage() : ""); } break; default: { content = title + "<br/>" + (t != null ? t.getMessage() : ""); } break; } ctx.setStatus(status).put(HttpHeader.CONTENT_TYPE, "text/html") .write("<!DOCTYPE html>") .write("<html>") .write("<head>") .write("<title>") .write(title) .write("</title>") .write("</head>") .write("<body>") .write("<h1> " + title + " </h1>") .write("<p>" + content + "</p>") .write("<hr/>") .write("<footer><em>powered by Firefly " + Version.value + "</em></footer>") .write("</body>") .end("</html>"); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static long copy(File src, File dest, long position, long count) throws IOException { try(FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel();) { return inChannel.transferTo(position, count, outChannel); } }
#vulnerable code public static long copy(File src, File dest, long position, long count) throws IOException { FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); try { return inChannel.transferTo(position, count, outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); if (in != null) in.close(); if (out != null) out.close(); } } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testHeaders() throws Throwable { final HTTP2Decoder decoder = new HTTP2Decoder(); final HTTP2MockSession session = new HTTP2MockSession(); final HTTP2Configuration http2Configuration = new HTTP2Configuration(); final HTTP2SessionAttachment attachment = new HTTP2SessionAttachment(http2Configuration, session, new ServerSessionListener(){ @Override public Map<Integer, Integer> onPreface(Session session) { System.out.println("on preface: " + session.isClosed()); Assert.assertThat(session.isClosed(), is(false)); return null; } @Override public Listener onNewStream(Stream stream, HeadersFrame frame) { System.out.println("on new stream: " + stream.getId()); System.out.println("on new stread headers: " + frame.getMetaData().toString()); Assert.assertThat(stream.getId(), is(5)); Assert.assertThat(frame.getMetaData().getVersion(), is(HttpVersion.HTTP_2)); Assert.assertThat(frame.getMetaData().getFields().get("User-Agent"), is("Firefly Client 1.0")); MetaData.Request request = (MetaData.Request) frame.getMetaData(); Assert.assertThat(request.getMethod(), is("GET")); Assert.assertThat(request.getURI().getPath(), is("/index")); Assert.assertThat(request.getURI().getPort(), is(8080)); Assert.assertThat(request.getURI().getHost(), is("localhost")); return new Listener(){ @Override public void onHeaders(Stream stream, HeadersFrame frame) { System.out.println("on headers: " + frame.getMetaData()); } @Override public Listener onPush(Stream stream, PushPromiseFrame frame) { return null; } @Override public void onData(Stream stream, DataFrame frame, Callback callback) { } @Override public void onReset(Stream stream, ResetFrame frame) { } @Override public void onTimeout(Stream stream, Throwable x) { }}; } @Override public void onSettings(Session session, SettingsFrame frame) { System.out.println("on settings: " + frame.toString()); Assert.assertThat(frame.getSettings().get(SettingsFrame.INITIAL_WINDOW_SIZE), is(http2Configuration.getInitialStreamSendWindow())); } @Override public void onPing(Session session, PingFrame frame) { } @Override public void onReset(Session session, ResetFrame frame) { } @Override public void onClose(Session session, GoAwayFrame frame) { } @Override public void onFailure(Session session, Throwable failure) { } @Override public void onAccept(Session session) { }}); int streamId = 5; HttpFields fields = new HttpFields(); fields.put("Accept", "text/html"); fields.put("User-Agent", "Firefly Client 1.0"); MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("localhost:8080"), "/index", HttpVersion.HTTP_2, fields); Map<Integer, Integer> settings = new HashMap<>(); settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize()); settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow()); HeadersGenerator headersGenerator = attachment.getGenerator().getControlGenerator(FrameType.HEADERS); SettingsGenerator settingsGenerator = attachment.getGenerator().getControlGenerator(FrameType.SETTINGS); List<ByteBuffer> list = new LinkedList<>(); list.add(ByteBuffer.wrap(PrefaceFrame.PREFACE_BYTES)); list.add(settingsGenerator.generateSettings(settings, false)); list.addAll(headersGenerator.generateHeaders(streamId, metaData, null, true)); for(ByteBuffer buffer : list) { decoder.decode(buffer, session); } Assert.assertThat(session.outboundData.size(), greaterThan(0)); System.out.println("out data: " + session.outboundData.size()); attachment.close(); }
#vulnerable code @Test public void testHeaders() throws Throwable { final HTTP2Decoder decoder = new HTTP2Decoder(); final HTTP2MockSession session = new HTTP2MockSession(); final HTTP2Configuration http2Configuration = new HTTP2Configuration(); final HTTP2SessionAttachment attachment = new HTTP2SessionAttachment(http2Configuration, session, new ServerSessionListener(){ @Override public Map<Integer, Integer> onPreface(Session session) { System.out.println("on preface: " + session.isClosed()); Assert.assertThat(session.isClosed(), is(false)); return null; } @Override public Listener onNewStream(Stream stream, HeadersFrame frame) { System.out.println("on new stream: " + stream.getId()); System.out.println("on new stread headers: " + frame.getMetaData().toString()); Assert.assertThat(stream.getId(), is(5)); Assert.assertThat(frame.getMetaData().getVersion(), is(HttpVersion.HTTP_2)); Assert.assertThat(frame.getMetaData().getFields().get("User-Agent"), is("Firefly Client 1.0")); MetaData.Request request = (MetaData.Request) frame.getMetaData(); Assert.assertThat(request.getMethod(), is("GET")); Assert.assertThat(request.getURI().getPath(), is("/index")); Assert.assertThat(request.getURI().getPort(), is(8080)); Assert.assertThat(request.getURI().getHost(), is("localhost")); return new Listener(){ @Override public void onHeaders(Stream stream, HeadersFrame frame) { System.out.println("on headers: " + frame.getMetaData()); } @Override public Listener onPush(Stream stream, PushPromiseFrame frame) { return null; } @Override public void onData(Stream stream, DataFrame frame, Callback callback) { } @Override public void onReset(Stream stream, ResetFrame frame) { } @Override public void onTimeout(Stream stream, Throwable x) { }}; } @Override public void onSettings(Session session, SettingsFrame frame) { System.out.println("on settings: " + frame.toString()); Assert.assertThat(frame.getSettings().get(SettingsFrame.INITIAL_WINDOW_SIZE), is(http2Configuration.getInitialStreamSendWindow())); } @Override public void onPing(Session session, PingFrame frame) { } @Override public void onReset(Session session, ResetFrame frame) { } @Override public void onClose(Session session, GoAwayFrame frame) { } @Override public void onFailure(Session session, Throwable failure) { } @Override public void onAccept(Session session) { }}); int streamId = 5; HttpFields fields = new HttpFields(); fields.put("Accept", "text/html"); fields.put("User-Agent", "Firefly Client 1.0"); MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP, new HostPortHttpField("localhost:8080"), "/index", HttpVersion.HTTP_2, fields); Map<Integer, Integer> settings = new HashMap<>(); settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize()); settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow()); HeadersGenerator headersGenerator = attachment.getGenerator().getControlGenerator(FrameType.HEADERS); SettingsGenerator settingsGenerator = attachment.getGenerator().getControlGenerator(FrameType.SETTINGS); List<ByteBuffer> list = new LinkedList<>(); list.add(ByteBuffer.wrap(PrefaceFrame.PREFACE_BYTES)); list.add(settingsGenerator.generateSettings(settings, false)); list.addAll(headersGenerator.generateHeaders(streamId, metaData, null, true)); for(ByteBuffer buffer : list) { decoder.decode(buffer, session); } Assert.assertThat(session.outboundData.size(), greaterThan(0)); System.out.println("out data: " + session.outboundData.size()); } #location 93 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code HTTP1ServerConnection(HTTP2Configuration config, Session tcpSession, SecureSession secureSession, HTTP1ServerRequestHandler requestHandler, ServerSessionListener serverSessionListener) { super(config, secureSession, tcpSession, requestHandler, null); requestHandler.connection = this; this.serverSessionListener = serverSessionListener; this.serverRequestHandler = requestHandler; }
#vulnerable code boolean directUpgradeHTTP2(MetaData.Request request) { if (HttpMethod.PRI.is(request.getMethod())) { HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(config, tcpSession, secureSession, serverSessionListener); tcpSession.attachObject(http2ServerConnection); http2ServerConnection.getParser().directUpgrade(); upgradeHTTP2Successfully = true; return true; } else { return false; } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void initializeHTTP2ClientConnection(final Session session, final HTTP2ClientContext context, final SSLSession sslSession) { HTTP2ClientConnection.initialize(config, session, context, sslSession); }
#vulnerable code private void initializeHTTP2ClientConnection(final Session session, final HTTP2ClientContext context, final SSLSession sslSession) { final HTTP2ClientConnection connection = new HTTP2ClientConnection(config, session, sslSession, context.listener); Map<Integer, Integer> settings = context.listener.onPreface(connection.getHttp2Session()); if (settings == null) { settings = Collections.emptyMap(); } PrefaceFrame prefaceFrame = new PrefaceFrame(); SettingsFrame settingsFrame = new SettingsFrame(settings, false); SessionSPI sessionSPI = connection.getSessionSPI(); int windowDelta = config.getInitialSessionRecvWindow() - FlowControlStrategy.DEFAULT_WINDOW_SIZE; Callback callback = new Callback() { @Override public void succeeded() { context.promise.succeeded(connection); } @Override public void failed(Throwable x) { try { connection.close(); } catch (IOException e) { log.error("http2 connection initialization error", e); } context.promise.failed(x); } }; if (windowDelta > 0) { sessionSPI.updateRecvWindow(windowDelta); sessionSPI.frames(null, callback, prefaceFrame, settingsFrame, new WindowUpdateFrame(0, windowDelta)); } else { sessionSPI.frames(null, callback, prefaceFrame, settingsFrame); } } #location 34 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testResponseParse2() throws Exception { ByteBuffer buffer = BufferUtils .toBuffer("HTTP/1.1 204 No-Content\015\012" + "Header: value\015\012" + "\015\012" + "HTTP/1.1 200 Correct\015\012" + "Content-Length: 10\015\012" + "Content-Type: text/plain\015\012" + "\015\012" + "0123456789\015\012"); HttpParser.ResponseHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parser.parseNext(buffer); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("204", _uriOrStatus); assertEquals("No-Content", _versionOrReason); assertTrue(_headerCompleted); assertTrue(_messageCompleted); parser.reset(); init(); parser.parseNext(buffer); parser.atEOF(); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("200", _uriOrStatus); assertEquals("Correct", _versionOrReason); assertEquals(_content.length(), 10); assertTrue(_headerCompleted); assertTrue(_messageCompleted); }
#vulnerable code @Test public void testResponseParse2() throws Exception { ByteBuffer buffer = BufferUtils .toBuffer("HTTP/1.1 204 No-Content\015\012" + "Header: value\015\012" + "\015\012" + "HTTP/1.1 200 Correct\015\012" + "Content-Length: 10\015\012" + "Content-Type: text/plain\015\012" + "\015\012" + "0123456789\015\012"); HttpParser.ResponseHandler handler = new Handler(); HttpParser parser = new HttpParser(handler); parser.parseNext(buffer); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("204", _uriOrStatus); assertEquals("No-Content", _versionOrReason); assertTrue(_headerCompleted); assertTrue(_messageCompleted); parser.reset(); init(); parser.parseNext(buffer); parser.atEOF(); assertEquals("HTTP/1.1", _methodOrVersion); assertEquals("200", _uriOrStatus); assertEquals("Correct", _versionOrReason); assertEquals(_content.length(), 10); assertTrue(_headerCompleted); assertTrue(_messageCompleted); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); }
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn((short)3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMethodType() { Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(reqRef); MethodGenericTypeBind extInfo = getterMap.get("extInfo"); ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.GETTER)); Map<String, MethodGenericTypeBind> setterMap = ReflectUtils.getGenericBeanSetterMethods(reqRef); extInfo = setterMap.get("extInfo"); parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.SETTER)); }
#vulnerable code @Test public void testMethodType() { Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>>() { }, null); MethodGenericTypeBind extInfo = getterMap.get("extInfo"); ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.GETTER)); Map<String, MethodGenericTypeBind> setterMap = ReflectUtils.getGenericBeanSetterMethods( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>>() { }, null); extInfo = setterMap.get("extInfo"); parameterizedType = (ParameterizedType) extInfo.getType(); System.out.println(parameterizedType.getTypeName()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(extInfo.getMethodType(), is(MethodType.SETTER)); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); }
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn((short)3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); } #location 110 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); try(SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false));) { clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); } }
#vulnerable code @Test public void testWindowUpdate() throws Throwable { MockSession clientSession = new MockSession(); MockSession serverSession = new MockSession(); SpdySessionAttachment clientAttachment = new SpdySessionAttachment(new Connection(clientSession, true)); SpdySessionAttachment serverAttachment = new SpdySessionAttachment(new Connection(serverSession, false)); clientSession.attachObject(clientAttachment); serverSession.attachObject(serverAttachment); SpdyDecoder clientDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { }}, new SettingsManager(null, "localhost", 7777))); SpdyDecoder serverDecoder = new SpdyDecoder(new DefaultSpdyDecodingEventListener(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { System.out.println("Server receives syn stream -> " + synStreamFrame); } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Server receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Fields headers = stream.createFields(); headers.put("response", "ok"); stream.reply(Version.V3, (byte)0, headers); stream.sendLastData("the server has received messages".getBytes()); } }}, null)); // Client creates a stream Stream clientStream = clientAttachment.getConnection().createStream(new StreamEventListener(){ @Override public void onSynStream(SynStreamFrame synStreamFrame, Stream stream, Connection connection) { } @Override public void onSynReply(SynReplyFrame synReplyFrame, Stream stream, Connection connection) { System.out.println("Client receives reply frame -> " + synReplyFrame); Assert.assertThat(synReplyFrame.getHeaders().get("response").getValue(), is("ok")); } @Override public void onRstStream(RstStreamFrame rstStreamFrame, Stream stream, Connection connection) { } @Override public void onHeaders(HeadersFrame headersFrame, Stream stream, Connection connection) { } @Override public void onData(DataFrame dataFrame, Stream stream, Connection connection) { System.out.println("Client receives data -> " + dataFrame); if(dataFrame.getFlags() == DataFrame.FLAG_FIN) { Assert.assertThat(new String(dataFrame.getData()), is("the server has received messages")); } }}); Assert.assertThat(clientStream.getId(), is(1)); Assert.assertThat(clientStream.getPriority(), is((byte)0)); Assert.assertThat(clientAttachment.getConnection().getStream(1) == clientStream, is(true)); // Client sends a SYN stream to server Fields headers = clientStream.createFields(); headers.put("test1", "testValue1"); headers.put("test2", "testValue2"); headers.add("testM1", "testm1"); headers.add("testM2", "testm2"); clientStream.syn(Version.V3, (byte)0, 0, (byte)0, headers); Assert.assertThat(clientStream.getWindowSize(), is(64 * 1024)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); // Server receives a SYN stream serverDecoder.decode(clientSession.outboundData.poll(), serverSession); // Client sends data frames int currentWindowSize = 64 * 1024; byte[] data = "hello world".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data2".getBytes(); clientStream.sendData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); data = "data3".getBytes(); clientStream.sendLastData(data); currentWindowSize -= data.length; Assert.assertThat(clientStream.getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(currentWindowSize)); Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(false)); // Server receives data ByteBuffer buf = null; while( (buf = clientSession.outboundData.poll()) != null ) { serverDecoder.decode(buf, serverSession); } // Server sends window update and replies while( (buf = serverSession.outboundData.poll()) != null ) { clientDecoder.decode(buf, clientSession); } Assert.assertThat(clientStream.isOutboundClosed(), is(true)); Assert.assertThat(clientStream.isInboundClosed(), is(true)); Assert.assertThat(clientAttachment.getConnection().getWindowSize(), is(64 * 1024)); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testInputStreamContent() { InputStream inputStream = $.class.getResourceAsStream("/poem.txt"); InputStreamContentProvider inputStreamContentProvider = new InputStreamContentProvider(inputStream); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFilePart("poetry", "poem.txt", inputStreamContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = $.buffer.toString(list); Assert.assertThat(value.length(), greaterThan(0)); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), lessThan(0L)); }
#vulnerable code @Test public void testInputStreamContent() { InputStream inputStream = $.class.getResourceAsStream("/poem.txt"); InputStreamContentProvider inputStreamContentProvider = new InputStreamContentProvider(inputStream); MultiPartContentProvider multiPartProvider = new MultiPartContentProvider(); System.out.println(multiPartProvider.getContentType()); multiPartProvider.addFilePart("poetry", "poem.txt", inputStreamContentProvider, null); multiPartProvider.close(); multiPartProvider.setListener(() -> System.out.println("on content")); List<ByteBuffer> list = new ArrayList<>(); for (ByteBuffer buf : multiPartProvider) { list.add(buf); } String value = BufferUtils.toString(list); Assert.assertThat(value.length(), greaterThan(0)); System.out.println(multiPartProvider.getLength()); Assert.assertThat(multiPartProvider.getLength(), lessThan(0L)); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetLocationOfClass() throws Exception { // Class from project dependencies Assert.assertThat(TypeUtils.getLocationOfClass(TypeUtils.class).toASCIIString(), Matchers.containsString("/classes/")); // Class from JVM core String expectedJavaBase = "/rt.jar"; if (JDK.IS_9) expectedJavaBase = "/java.base/"; Assert.assertThat(TypeUtils.getLocationOfClass(String.class).toASCIIString(), Matchers.containsString(expectedJavaBase)); }
#vulnerable code @Test public void testGetLocationOfClass() throws Exception { // Classes from maven dependencies Assert.assertThat(TypeUtils.getLocationOfClass(Assert.class).toASCIIString(), Matchers.containsString("repository")); // Class from project dependencies Assert.assertThat(TypeUtils.getLocationOfClass(TypeUtils.class).toASCIIString(), Matchers.containsString("/classes/")); // Class from JVM core String expectedJavaBase = "/rt.jar"; if (JDK.IS_9) expectedJavaBase = "/java.base/"; Assert.assertThat(TypeUtils.getLocationOfClass(String.class).toASCIIString(), Matchers.containsString(expectedJavaBase)); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Throwable{ Certificate[] certificates = getCertificates("fireflySSLkeys.jks", "fireflySSLkeys"); for(Certificate certificate : certificates) { System.out.println(certificate); } certificates = getCertificates("fireflykeys", "fireflysource"); for(Certificate certificate : certificates) { System.out.println(certificate); } }
#vulnerable code public static void main(String[] args) throws Throwable { FileInputStream in = null; ByteArrayOutputStream out = null; try { in = new FileInputStream(new File("/Users/qiupengtao", "fireflykeys")); out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; for (int i = 0; (i = in.read(buf)) != -1;) { byte[] temp = new byte[i]; System.arraycopy(buf, 0, temp, 0, i); out.write(temp); } byte[] ret = out.toByteArray(); // System.out.println(ret.length); System.out.println(Arrays.toString(ret)); } finally { in.close(); out.close(); } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields(barRef); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(carRef); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.Integer>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields(parRef); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(sarRef); MethodGenericTypeBind list = getterMap.get("list"); System.out.println(list.getType().getTypeName()); Assert.assertThat(list.getType().getTypeName(), is("java.util.List<java.util.Map<java.lang.String, test.utils.lang.TestGenericTypeReference$Foo>>")); MethodGenericTypeBind sar = getterMap.get("sar"); Assert.assertThat(sar.getType().getTypeName(), is("java.lang.Integer")); }
#vulnerable code @Test public void testNestedClass() throws Exception { Map<String, FieldGenericTypeBind> map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Bar<List<String>>>() { }, null); FieldGenericTypeBind barMaps = map.get("maps"); ParameterizedType parameterizedType = (ParameterizedType) barMaps.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); FieldGenericTypeBind bar = map.get("bar"); parameterizedType = (ParameterizedType) bar.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Car<List<String>>>() { }, null); FieldGenericTypeBind car = map.get("car"); parameterizedType = (ParameterizedType) car.getType(); System.out.println(parameterizedType.getTypeName()); System.out.println(parameterizedType.getOwnerType()); Assert.assertThat(parameterizedType.getTypeName(), is("java.util.List<java.lang.String>")); Assert.assertThat(parameterizedType.getOwnerType(), nullValue()); map = ReflectUtils.getGenericBeanFields( new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>.Par>() { }, null); FieldGenericTypeBind par = map.get("par"); Class<?> clazz = (Class<?>) par.getType(); System.out.println(clazz.getTypeName()); Assert.assertThat(clazz.getTypeName(), is("java.lang.String")); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String... args) throws IOException, ExecutionException, InterruptedException { final String project = Util.defaultProject(); GoogleCredential credential; // Use credentials from file if available try { credential = GoogleCredential .fromStream(new FileInputStream("credentials.json")) .createScoped(PubsubScopes.all()); } catch (IOException e) { credential = GoogleCredential.getApplicationDefault() .createScoped(PubsubScopes.all()); } final Pubsub pubsub = Pubsub.builder() .credential(credential) .compressionLevel(Deflater.BEST_SPEED) .enabledCipherSuites(Util.nonGcmCiphers()) .build(); LoggingConfigurator.configureDefaults("benchmark", WARN); System.setProperty("https.cipherSuites", Joiner.on(',').join(Util.nonGcmCiphers())); final String subscription = System.getenv("GOOGLE_PUBSUB_SUBSCRIPTION"); if (subscription == null) { System.err.println("Please specify a subscription using the GOOGLE_PUBSUB_SUBSCRIPTION environment variable."); System.exit(1); } System.out.println("Consuming from GOOGLE_PUBSUB_SUBSCRIPTION='" + subscription + "'"); final ProgressMeter meter = new ProgressMeter(); final ProgressMeter.Metric receives = meter.group("operations").metric("receives", "messages"); final Puller puller = Puller.builder() .pubsub(pubsub) .batchSize(1000) .concurrency(PULLER_CONCURRENCY) .project(project) .subscription(subscription) .messageHandler(new Handler(receives)) .build(); while (true) { Thread.sleep(1000); System.out.println("outstanding messages: " + puller.outstandingMessages()); System.out.println("outstanding requests: " + puller.outstandingRequests()); } }
#vulnerable code public static void main(final String... args) throws IOException, ExecutionException, InterruptedException { final String project = Util.defaultProject(); GoogleCredential credential; // Use credentials from file if available try { credential = GoogleCredential .fromStream(new FileInputStream("credentials.json")) .createScoped(PubsubScopes.all()); } catch (IOException e) { credential = GoogleCredential.getApplicationDefault() .createScoped(PubsubScopes.all()); } final Pubsub pubsub = Pubsub.builder() .credential(credential) .compressionLevel(Deflater.BEST_SPEED) .enabledCipherSuites(Util.nonGcmCiphers()) .build(); LoggingConfigurator.configureDefaults("benchmark", WARN); final String subscription = System.getenv("GOOGLE_PUBSUB_SUBSCRIPTION"); if (subscription == null) { System.err.println("Please specify a subscription using the GOOGLE_PUBSUB_SUBSCRIPTION environment variable."); System.exit(1); } System.out.println("Consuming from GOOGLE_PUBSUB_SUBSCRIPTION='" + subscription + "'"); final ProgressMeter meter = new ProgressMeter(); final ProgressMeter.Metric receives = meter.group("operations").metric("receives", "messages"); final Puller puller = Puller.builder() .pubsub(pubsub) .batchSize(1000) .concurrency(PULLER_CONCURRENCY) .project(project) .subscription(subscription) .messageHandler(new Handler(receives)) .build(); while (true) { Thread.sleep(1000); } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Mono<Payload> requestResponse(Payload payload) { RSocket service = findRSocket(payload); return service.requestResponse(payload); }
#vulnerable code @Override public Mono<Payload> requestResponse(Payload payload) { List<String> metadata = getRoutingMetadata(payload); RSocket service = findRSocket(metadata); if (service != null) { return service.requestResponse(payload); } MonoProcessor<RSocket> processor = MonoProcessor.create(); this.registry.pendingRequest(metadata, processor); return processor .log("pending-request") .flatMap(rSocket -> rSocket.requestResponse(payload)); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Flux<Payload> requestStream(Payload payload) { RSocket service = findRSocket(payload); return service.requestStream(payload); }
#vulnerable code @Override public Flux<Payload> requestStream(Payload payload) { List<String> metadata = getRoutingMetadata(payload); RSocket service = findRSocket(metadata); if (service != null) { return service.requestStream(payload); } MonoProcessor<RSocket> processor = MonoProcessor.create(); this.registry.pendingRequest(metadata, processor); return processor .log("pending-request") .flatMapMany(rSocket -> rSocket.requestStream(payload)); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Flux<Payload> requestStream(Payload payload) { GatewayExchange exchange = createExchange(REQUEST_STREAM, payload); return findRSocketOrCreatePending(exchange) .flatMapMany(rSocket -> rSocket.requestStream(payload)) // S N E F .doOnNext(s -> count(exchange, "payload")) .doOnError(t -> count(exchange, "error")) .doFinally(s -> count(exchange, Tags.empty())); }
#vulnerable code @Override public Flux<Payload> requestStream(Payload payload) { GatewayExchange exchange = GatewayExchange.fromPayload(REQUEST_STREAM, payload); Tags tags = getTags(exchange); return findRSocketOrCreatePending(exchange) .flatMapMany(rSocket -> rSocket.requestStream(payload)) // S N E F //TODO: move tagnames to enum .doOnNext(s -> count("forward.request.stream.payload", tags)) .doOnError(t -> count("forward.request.stream.error", tags)) .doFinally(s -> count("forward.request.stream", tags)); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Mono<Payload> requestResponse(Payload payload) { AtomicReference<Timer.Sample> timer = new AtomicReference<>(); GatewayExchange exchange = createExchange(REQUEST_RESPONSE, payload); return findRSocketOrCreatePending(exchange) .flatMap(rSocket -> rSocket.requestResponse(payload)) .doOnSubscribe(s -> timer.set(Timer.start(meterRegistry))) .doOnError(t -> count(exchange, "error")) .doFinally(s -> timer.get().stop(meterRegistry.timer(getMetricName(exchange), exchange.getTags()))); }
#vulnerable code @Override public Mono<Payload> requestResponse(Payload payload) { AtomicReference<Timer.Sample> timer = new AtomicReference<>(); GatewayExchange exchange = GatewayExchange.fromPayload(REQUEST_RESPONSE, payload); Tags tags = getTags(exchange); return findRSocketOrCreatePending(exchange) .flatMap(rSocket -> rSocket.requestResponse(payload)) .doOnSubscribe(s -> timer.set(Timer.start(meterRegistry))) .doOnError(t -> count("forward.request.response.error", tags)) .doFinally(s -> timer.get().stop(meterRegistry.timer("forward.request.response", tags))); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException { IngestReader ir = new IngestReader(); try { if(args.length < 2) { throw new IngestException(); } String command = args[0]; if(args.length == 2) { if(command.equals("-gx")) { XmlHelper.generateXml(args[1]); } else if(command.equals("-b")) { //In the case of bills, we also need to make sure we reindex all ammended versions Bill bill = (Bill)ir.loadObject(args[1], Bill.class); if(ir.reindexAmendedVersions((Bill)bill)) bill.setLuceneActive(false); ir.indexSenateObject(bill); } else if(command.equals("-c")) { ir.indexSenateObject(ir.loadObject(args[1], Calendar.class)); } else if(command.equals("-a")) { ir.indexSenateObject(ir.loadObject(args[1], Agenda.class)); } else if(command.equals("-t")) { ir.indexSenateObject(ir.loadObject(args[1], Transcript.class)); } else { throw new IngestException(); } } else if(args.length == 3){ if(command.equals("-i")) { WRITE_DIRECTORY = args[1]; ir.processPath(args[2]); } else if(command.equals("-it")) { //Processes, writes, and indexes a directory of transcripts WRITE_DIRECTORY = args[1]; ir.handleTranscript(new File(args[2])); } else if(command.equals("-bulk")) { ir.bulkIndexJsonDirectory(ir.getIngestType(args[1]).clazz(),args[2]); } else { throw new IngestException(); } } else if(args.length == 5) { if(command.equals("-pull")) { ir.pullSobis(args[1], args[2], args[3], args[4]); } else { throw new IngestException(); } } } catch(IngestException e) { System.err.println("appropriate usage is:\n" + "\t-i <json directory> <sobi directory> (to create index)\n" + "\t-gx <sobi directory> (to generate agenda and calendar xml from sobi)\n" + "\t-b <bill json path> (to reindex single bill)\n" + "\t-c <calendar json path> (to reindex single calendar)\n" + "\t-a <agenda json path> (to reindex single agenda)\n" + "\t-t <transcript json path> (to reindex single transcript)" + "\t-it <transcript sobi path> (to reindex dir of transcripts)\n" + "\t-pull <sobi directory> <output directory> <id> <year> (get an objects referencing sobis)" + "\t-bulk <object type> <json directory> (bulk index directory ofjson objects)"); } }
#vulnerable code public static void main(String[] args) throws IOException { IngestReader ir = new IngestReader(); try { if(args.length < 2) { throw new IngestException(); } String command = args[0]; if(args.length == 2) { if(command.equals("-gx")) { XmlHelper.generateXml(args[1]); } else if(command.equals("-b")) { //In the case of bills, we also need to make sure we reindex all ammended versions Bill bill = (Bill)ir.loadObject(args[1], Bill.class); if(ir.reindexAmendedVersions((Bill)bill)) bill.setLuceneActive(false); ir.indexSenateObject(bill); } else if(command.equals("-c")) { ir.indexSenateObject(ir.loadObject(args[1], Calendar.class)); } else if(command.equals("-a")) { ir.indexSenateObject(ir.loadObject(args[1], Agenda.class)); } else if(command.equals("-t")) { ir.indexSenateObject(ir.loadObject(args[1], Transcript.class)); } else { throw new IngestException(); } } else if(args.length == 3){ if(command.equals("-i")) { WRITE_DIRECTORY = args[1]; ir.processPath(args[2]); } else if(command.equals("-it")) { //Processes, writes, and indexes a directory of transcripts WRITE_DIRECTORY = args[1]; ir.handleTranscript(new File(args[2])); } else { throw new IngestException(); } } else if(args.length == 5) { if(command.equals("-pull")) { ir.pullSobis(args[1], args[2], args[3], args[4]); } else { throw new IngestException(); } } } catch(IngestException e) { System.err.println("appropriate usage is:\n" + "\t-i <json directory> <sobi directory> (to create index)\n" + "\t-gx <sobi directory> (to generate agenda and calendar xml from sobi)\n" + "\t-b <bill json path> (to reindex single bill)\n" + "\t-c <calendar json path> (to reindex single calendar)\n" + "\t-a <agenda json path> (to reindex single agenda)\n" + "\t-t <transcript json path> (to reindex single transcript)" + "\t-it <transcript sobi path> (to reindex dir of transcripts)\n" + "\t-pull <sobi directory> <output directory> <id> <year> (get an objects referencing sobis)"); } } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void handleAPIv1 (String format, String type, String key, int pageIdx, int pageSize, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String urlPath = "/legislation/" + type + "/" + ((key != null && !key.matches("\\s*")) ? key + "/" :""); if (type.equalsIgnoreCase("sponsor")) { String filter = req.getParameter("filter"); key = "sponsor:\"" + key + "\""; if(filter != null) { req.setAttribute("filter", filter); key += (filter != null ? " AND " + filter : ""); } type = "bills"; } else if (type.equalsIgnoreCase("committee")) { key = "committee:\"" + key + "\""; type = "bills"; } String originalType = type; String viewPath = ""; String searchString = ""; String sFormat = "json"; String sortField = "when"; boolean sortOrder = true; if(type != null) { if(type.contains("bill")) { sortField = "sortindex"; sortOrder = false; } else if(type.contains("meeting")) { sortField = "sortindex"; } } SenateResponse sr = null; key = key.trim(); if (pageSize > MAX_PAGE_SIZE) throw new ServletException ("The maximum page size is " + MAX_PAGE_SIZE); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; int end = start + pageSize; logger.info("request: key=" + key + ";type=" + type + ";format=" + format + ";paging=" + start + "/" + end); try { /* * construct query with "otype:<type>" if type present */ if (type != null) { /* * for searches * * applicable to: bills, calendars, meetings, transcripts, actions, votes */ if (type.endsWith("s")) { type = type.substring(0,type.length()-1); searchString = "otype:" + type; if (key != null && key.length() > 0) searchString += " AND " + key; } /* * for individual documents * * applicable to: bill, calendar, meeting, transcript */ else { searchString ="otype:" + type; if (key != null && key.length() > 0) { if (type.equals("bill") && key.indexOf("-") == -1) key += "-" + DEFAULT_SESSION_YEAR; key = key.replace(" ","+"); searchString += " AND oid:" + key; } } } else { searchString = key; } /* * applicable to: bills * * only return bills with "year:<currentSessionYear>" */ if(originalType.equals("bills")) { req.setAttribute("urlPath", urlPath); searchString = ApiHelper.dateReplace(searchString) + " AND year:" + SessionYear.getSessionYear() + " AND active:true"; } /* * applicable to: calendars, meetings, transcripts * * only want current session documents as defined by the time * frame between DATE_START and DATE_END */ else if(originalType.endsWith("s")) { req.setAttribute("urlPath", urlPath); searchString = ApiHelper.dateReplace(searchString) + " AND when:[" + DATE_START + " TO " + DATE_END + "]" + " AND active:true"; } /* * applicable to: individual documents * * attempting to access a document by id doesn't * doesn't require any special formatting */ else { searchString = ApiHelper.dateReplace(searchString); } req.setAttribute("sortField", sortField); req.setAttribute("sortOrder", Boolean.toString(sortOrder)); req.setAttribute("type", type); req.setAttribute("term", searchString); req.setAttribute("format", format); req.setAttribute("key", key); req.setAttribute(PAGE_IDX,pageIdx+""); req.setAttribute(PAGE_SIZE,pageSize+""); sr = searchEngine.search(searchString,sFormat,start,pageSize,sortField,sortOrder); logger.info("got search results: " + sr.getResults().size()); if (sr.getResults().size()==0) { resp.sendError(404); return; } else if (sr.getResults().size()==1 && format.matches("(html(\\-print)?|mobile|lrs\\-print)")) { Result result = sr.getResults().get(0); /* if not an exact match on the oid it's likely * the correct id, just the wrong case */ if (!result.getOid().equals(key)) { if(format.equals("html")) resp.sendRedirect("/legislation/" + result.getOtype() + "/" + result.getOid()); else resp.sendRedirect("/legislation/api/1.0/" + format + "/" + result.getOtype() + "/" + result.getOid()); return; } String jsonData = result.getData(); req.setAttribute("active", result.getActive()); jsonData = jsonData.substring(jsonData.indexOf(":")+1); jsonData = jsonData.substring(0,jsonData.lastIndexOf("}")); /* Jackson ObjectMaper will deserialize our json in to an object, * we need to know what sort of an object that is */ String className = "gov.nysenate.openleg.model.bill." + type.substring(0,1).toUpperCase() + type.substring(1); /* * for bills we populate other relevant data, such as * votes, calendars, meetings, sameas bills, older versions, etc. */ if (type.equals("bill")) { String billQueryId = key; String sessionYear = DEFAULT_SESSION_YEAR; /* default behavior to maintain previous permalinks * is if key=S1234 to transform to S1234-2009 * in line with our new bill oid format <billno>-<sessYear> */ String[] billParts = billQueryId.split("-"); billQueryId = billParts[0]; if (billParts.length > 1) sessionYear = billParts[1]; /* turns S1234A in to S1234 */ String billWildcard = billQueryId; if (!Character.isDigit(billWildcard.charAt(billWildcard.length()-1))) billWildcard = billWildcard.substring(0,billWildcard.length()-1); //get BillEvents for this //otype:action AND billno:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) String rType = "action"; String rQuery = null; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "billno:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; ArrayList<SearchResult> relatedActions = ApiHelper.getRelatedSenateObjects(rType,rQuery); Hashtable<String,SearchResult> uniqResults = new Hashtable<String,SearchResult>(); for (SearchResult rResult: relatedActions) { BillEvent rAction = (BillEvent)rResult.getObject(); uniqResults.put(rAction.getEventDate().toGMTString()+'-'+rResult.getTitle().toUpperCase(), rResult); } ArrayList<SearchResult> list = Collections.list(uniqResults.elements()); Collections.sort(list); req.setAttribute("related-" + rType, list); //get older bills (e.g. for S1234A get S1234) //otype:meeting AND oid:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) rType = "bill"; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "oid:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects (rType,rQuery)); //get Meetings //otype:meeting AND bills:"S67005-2011" rType = "meeting"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get calendars //otype:calendar AND bills:"S337A-2011" rType = "calendar"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get votes //otype:vote AND billno:"A11597-2011" rType = "vote"; rQuery = "billno:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); } else if (type.equals("calendar")) { className = "gov.nysenate.openleg.model.calendar.Calendar"; } else if (type.equals("meeting")) { className = "gov.nysenate.openleg.model.committee.Meeting"; } else if(type.equals("transcript")) { className = "gov.nysenate.openleg.model.transcript.Transcript"; } Object resultObj = null; try { resultObj = ApiHelper.getMapper().readValue(jsonData, Class.forName(className)); } catch (Exception e) { logger.warn("error binding className", e); } req.setAttribute(type, resultObj); viewPath = "/views/" + type + "-" + format + ".jsp"; } else { /* all non html/print bill views go here */ if (type.equals("bill") && (!format.equals("html"))) { viewPath = "/views/bills-" + format + ".jsp"; ArrayList<SearchResult> searchResults = ApiHelper.buildSearchResultList(sr); ArrayList<Bill> bills = new ArrayList<Bill>(); for (SearchResult result : searchResults) { bills.add((Bill)result.getObject()); } req.setAttribute("bills", bills); } /* all calendar, meeting, transcript multi views go here */ else { viewPath = "/views/" + "search" + "-" + format + ".jsp"; SearchResultSet srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); req.setAttribute("results", srs); } } } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); e.printStackTrace(); } try { logger.info("routing to search controller:" + viewPath); getServletContext().getRequestDispatcher(viewPath).forward(req, resp); } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); } }
#vulnerable code public void handleAPIv1 (String format, String type, String key, int pageIdx, int pageSize, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { String viewPath = ""; String searchString = ""; String originalType = type; String sFormat = "json"; String sortField = "when"; boolean sortOrder = true; if(type != null) { if(type.contains("bill")) { sortField = "sortindex"; sortOrder = false; } else if(type.contains("meeting")) { sortField = "sortindex"; } } SenateResponse sr = null; if (type.equalsIgnoreCase("sponsor")) { String filter = req.getParameter("filter"); key = "sponsor:\"" + key + (filter != null ? " AND " + filter : ""); type = "bills"; } else if (type.equalsIgnoreCase("committee")) { key = "committee:\"" + key + "\" AND oid:s*-" + SessionYear.getSessionYear(); type = "bills"; } key = key.trim(); if (pageSize > MAX_PAGE_SIZE) throw new ServletException ("The maximum page size is " + MAX_PAGE_SIZE); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; int end = start + pageSize; logger.info("request: key=" + key + ";type=" + type + ";format=" + format + ";paging=" + start + "/" + end); try { /* * construct query with "otype:<type>" if type present */ if (type != null) { /* * for searches * * applicable to: bills, calendars, meetings, transcripts, actions, votes */ if (type.endsWith("s")) { type = type.substring(0,type.length()-1); searchString = "otype:" + type; if (key != null && key.length() > 0) searchString += " AND " + key; } /* * for individual documents * * applicable to: bill, calendar, meeting, transcript */ else { searchString ="otype:" + type; if (key != null && key.length() > 0) { if (type.equals("bill") && key.indexOf("-") == -1) key += "-" + DEFAULT_SESSION_YEAR; key = key.replace(" ","+"); searchString += " AND oid:" + key; } } } else { searchString = key; } req.setAttribute("sortField", sortField); req.setAttribute("sortOrder", Boolean.toString(sortOrder)); req.setAttribute("type", type); req.setAttribute("term", searchString); req.setAttribute("format", format); req.setAttribute("key", key); req.setAttribute(PAGE_IDX,pageIdx+""); req.setAttribute(PAGE_SIZE,pageSize+""); /* * applicable to: bills * * only return bills with "year:<currentSessionYear>" */ if(originalType.equals("bills")) { sr = searchEngine.search(ApiHelper.dateReplace(searchString) + " AND year:" + SessionYear.getSessionYear() + " AND active:true", sFormat,start,pageSize,sortField,sortOrder); } /* * applicable to: calendars, meetings, transcripts * * only want current session documents as defined by the time * frame between DATE_START and DATE_END */ else if(originalType.endsWith("s")) { sr = searchEngine.search(ApiHelper.dateReplace(searchString) + " AND when:[" + DATE_START + " TO " + DATE_END + "]" + " AND active:true", sFormat,start,pageSize,sortField,sortOrder); } /* * applicable to: individual documents * * attempting to access a document by id doesn't * doesn't require any special formatting */ else { sr = searchEngine.search(ApiHelper.dateReplace(searchString),sFormat,start,pageSize,sortField,sortOrder); } logger.info("got search results: " + sr.getResults().size()); if (sr.getResults().size()==0) { resp.sendError(404); return; } else if (sr.getResults().size()==1 && format.matches("(html(\\-print)?|mobile|lrs\\-print)")) { Result result = sr.getResults().get(0); /* if not an exact match on the oid it's likely * the correct id, just the wrong case */ if (!result.getOid().equals(key)) { if(format.equals("html")) resp.sendRedirect("/legislation/" + result.getOtype() + "/" + result.getOid()); else resp.sendRedirect("/legislation/api/1.0/" + format + "/" + result.getOtype() + "/" + result.getOid()); return; } String jsonData = result.getData(); req.setAttribute("active", result.getActive()); jsonData = jsonData.substring(jsonData.indexOf(":")+1); jsonData = jsonData.substring(0,jsonData.lastIndexOf("}")); /* Jackson ObjectMaper will deserialize our json in to an object, * we need to know what sort of an object that is */ String className = "gov.nysenate.openleg.model.bill." + type.substring(0,1).toUpperCase() + type.substring(1); /* * for bills we populate other relevant data, such as * votes, calendars, meetings, sameas bills, older versions, etc. */ if (type.equals("bill")) { String billQueryId = key; String sessionYear = DEFAULT_SESSION_YEAR; /* default behavior to maintain previous permalinks * is if key=S1234 to transform to S1234-2009 * in line with our new bill oid format <billno>-<sessYear> */ String[] billParts = billQueryId.split("-"); billQueryId = billParts[0]; if (billParts.length > 1) sessionYear = billParts[1]; /* turns S1234A in to S1234 */ String billWildcard = billQueryId; if (!Character.isDigit(billWildcard.charAt(billWildcard.length()-1))) billWildcard = billWildcard.substring(0,billWildcard.length()-1); //get BillEvents for this //otype:action AND billno:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) String rType = "action"; String rQuery = null; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "billno:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; ArrayList<SearchResult> relatedActions = ApiHelper.getRelatedSenateObjects(rType,rQuery); Hashtable<String,SearchResult> uniqResults = new Hashtable<String,SearchResult>(); for (SearchResult rResult: relatedActions) { BillEvent rAction = (BillEvent)rResult.getObject(); uniqResults.put(rAction.getEventDate().toGMTString()+'-'+rResult.getTitle().toUpperCase(), rResult); } ArrayList<SearchResult> list = Collections.list(uniqResults.elements()); Collections.sort(list); req.setAttribute("related-" + rType, list); //get older bills (e.g. for S1234A get S1234) //otype:meeting AND oid:((S1234-2011 OR [S1234A-2011 TO S1234Z-2011) AND S1234*-2011) rType = "bill"; rQuery = billWildcard + "-" + sessionYear; logger.info(rQuery); rQuery = "oid:((" + rQuery + " OR [" + billWildcard + "A-" + sessionYear + " TO " + billWildcard + "Z-" + sessionYear + "]) AND " + billWildcard + "*-" + sessionYear + ")"; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects (rType,rQuery)); //get Meetings //otype:meeting AND bills:"S67005-2011" rType = "meeting"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get calendars //otype:calendar AND bills:"S337A-2011" rType = "calendar"; rQuery = "bills:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); //get votes //otype:vote AND billno:"A11597-2011" rType = "vote"; rQuery = "billno:\"" + key + "\""; req.setAttribute("related-" + rType, ApiHelper.getRelatedSenateObjects(rType,rQuery)); } else if (type.equals("calendar")) { className = "gov.nysenate.openleg.model.calendar.Calendar"; } else if (type.equals("meeting")) { className = "gov.nysenate.openleg.model.committee.Meeting"; } else if(type.equals("transcript")) { className = "gov.nysenate.openleg.model.transcript.Transcript"; } Object resultObj = null; try { resultObj = ApiHelper.getMapper().readValue(jsonData, Class.forName(className)); } catch (Exception e) { logger.warn("error binding className", e); } req.setAttribute(type, resultObj); viewPath = "/views/" + type + "-" + format + ".jsp"; } else { /* all non html/print bill views go here */ if (type.equals("bill") && (!format.equals("html"))) { viewPath = "/views/bills-" + format + ".jsp"; ArrayList<SearchResult> searchResults = ApiHelper.buildSearchResultList(sr); ArrayList<Bill> bills = new ArrayList<Bill>(); for (SearchResult result : searchResults) { bills.add((Bill)result.getObject()); } req.setAttribute("bills", bills); } /* all calendar, meeting, transcript multi views go here */ else { viewPath = "/views/" + "search" + "-" + format + ".jsp"; SearchResultSet srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); req.setAttribute("results", srs); } } } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); e.printStackTrace(); } try { logger.info("routing to search controller:" + viewPath); getServletContext().getRequestDispatcher(viewPath).forward(req, resp); } catch (Exception e) { logger.warn("search controller didn't work for: " + req.getRequestURI(),e); } } #location 293 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("reset")!=null) searchEngine.closeSearcher(); String search = request.getParameter("search"); String term = request.getParameter("term"); String type = request.getParameter("type"); String full = request.getParameter("full"); String memo = request.getParameter("memo"); String status = request.getParameter("status"); String sponsor = request.getParameter("sponsor"); String cosponsors = request.getParameter("cosponsors"); String sameas = request.getParameter("sameas"); String committee = request.getParameter("committee"); String location = request.getParameter("location"); String session = request.getParameter("session"); if(search != null) { request.setAttribute("search", search); term = search; } String tempTerm = null; if((tempTerm = BillCleaner.getDesiredBillNumber(term)) != null) { term = "oid:" + tempTerm; type = "bill"; System.out.println("!! " + tempTerm); } String sortField = request.getParameter("sort"); boolean sortOrder = false; if (request.getParameter("sortOrder")!=null) sortOrder = Boolean.parseBoolean(request.getParameter("sortOrder")); Date startDate = null; Date endDate = null; try { if (request.getParameter("startdate")!=null && (!request.getParameter("startdate").equals("mm/dd/yyyy"))) startDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("startdate")); } catch (java.text.ParseException e1) { logger.warn(e1); } try { if (request.getParameter("enddate")!=null && (!request.getParameter("enddate").equals("mm/dd/yyyy"))) { endDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("enddate")); Calendar cal = Calendar.getInstance(); cal.setTime(endDate); cal.set(Calendar.HOUR, 11); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); endDate = cal.getTime(); } } catch (java.text.ParseException e1) { logger.warn(e1); } String format = "html"; if (request.getParameter("format")!=null) format = request.getParameter("format"); int pageIdx = 1; int pageSize = 20; if (request.getParameter("pageIdx") != null) pageIdx = Integer.parseInt(request.getParameter("pageIdx")); if (request.getParameter("pageSize") != null) pageSize = Integer.parseInt(request.getParameter("pageSize")); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; SearchResultSet srs; StringBuilder searchText = new StringBuilder(); if (term != null) searchText.append(term); try { if (type != null && type.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("otype:"); searchText.append(type.equals("res") ? "bill AND oid:r*":type); } if(session != null && session.length() > 0) { if(searchText.length() > 0) searchText.append(" AND "); searchText.append("year:" + session); } if (full != null && full.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("(full:\""); searchText.append(full); searchText.append("\""); searchText.append(" OR "); searchText.append("osearch:\""); searchText.append(full); searchText.append("\")"); } if (memo != null && memo.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("memo:\""); searchText.append(memo); searchText.append("\""); } if (status != null && status.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("status:\""); searchText.append(status); searchText.append("\""); } if (sponsor != null && sponsor.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sponsor:\""); searchText.append(sponsor); searchText.append("\""); } if (cosponsors != null && cosponsors.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("cosponsors:\""); searchText.append(cosponsors); searchText.append("\""); } if (sameas != null && sameas.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sameas:"); searchText.append(sameas); } if (committee != null && committee.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("committee:\""); searchText.append(committee); searchText.append("\""); } if (location != null && location.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("location:\""); searchText.append(location); searchText.append("\""); } if (startDate != null && endDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); searchText.append(endDate.getTime()); searchText.append("]"); } else if (startDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); cal.set(Calendar.HOUR, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); startDate = cal.getTime(); searchText.append(startDate.getTime()); searchText.append("]"); } term = searchText.toString(); term = BillCleaner.billFormat(term); request.setAttribute("term", term); request.setAttribute("type", type); //default behavior is to return only active bills, so if a user searches //s1234 and s1234a is available then s1234a should be returned if(sortField == null && (((search != null && search.contains("otype:bill")) || (term != null && term.contains("otype:bill"))) || (type != null && type.equals("bill")))) { sortField = "sortindex"; sortOrder = false; type = "bill"; } if (sortField!=null && !sortField.equals("")) { request.setAttribute("sortField", sortField); request.setAttribute("sortOrder",Boolean.toString(sortOrder)); } else { sortField = "when"; sortOrder = true; request.setAttribute("sortField", sortField); request.setAttribute("sortOrder", Boolean.toString(sortOrder)); } request.setAttribute(OpenLegConstants.PAGE_IDX,pageIdx+""); request.setAttribute(OpenLegConstants.PAGE_SIZE,pageSize+""); srs = null; if (term.length() == 0) { response.sendError(404); return; } String searchFormat = "json"; SenateResponse sr = null; if(term != null && !term.contains("year:") && !term.contains("when:") && !term.contains("oid:")) { if(type != null && type.equals("bill")) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } else { sr = searchEngine.search(term + " AND when:[" + DATE_START + " TO " + DATE_END + "]",searchFormat,start,pageSize,sortField,sortOrder); if(sr.getResults().isEmpty()) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } } } else { System.out.println("!!! " + term); sr = searchEngine.search(term,searchFormat,start,pageSize,sortField,sortOrder); } srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); if (srs != null) { if (srs.getResults().size() == 0) { response.sendError(404); } else { request.setAttribute("results", srs); String viewPath = "/views/search-" + format + DOT_JSP; getServletContext().getRequestDispatcher(viewPath).forward(request, response); } } else { logger.error("Search Error: " + request.getRequestURI()); response.sendError(500); } } catch (Exception e) { logger.error("Search Error: " + request.getRequestURI(),e); e.printStackTrace(); response.sendError(500); } }
#vulnerable code public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("reset")!=null) searchEngine.closeSearcher(); String search = request.getParameter("search"); String term = request.getParameter("term"); String type = request.getParameter("type"); String full = request.getParameter("full"); String memo = request.getParameter("memo"); String status = request.getParameter("status"); String sponsor = request.getParameter("sponsor"); String cosponsors = request.getParameter("cosponsors"); String sameas = request.getParameter("sameas"); String committee = request.getParameter("committee"); String location = request.getParameter("location"); String session = request.getParameter("session"); if(search != null) { request.setAttribute("search", search); term = search; } String tempTerm = null; if((tempTerm = BillCleaner.getDesiredBillNumber(term)) != null) { term = "oid:" + tempTerm; type = "bill"; } String sortField = request.getParameter("sort"); boolean sortOrder = false; if (request.getParameter("sortOrder")!=null) sortOrder = Boolean.parseBoolean(request.getParameter("sortOrder")); Date startDate = null; Date endDate = null; try { if (request.getParameter("startdate")!=null && (!request.getParameter("startdate").equals("mm/dd/yyyy"))) startDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("startdate")); } catch (java.text.ParseException e1) { logger.warn(e1); } try { if (request.getParameter("enddate")!=null && (!request.getParameter("enddate").equals("mm/dd/yyyy"))) { endDate = OL_SEARCH_DATE_FORMAT.parse(request.getParameter("enddate")); Calendar cal = Calendar.getInstance(); cal.setTime(endDate); cal.set(Calendar.HOUR, 11); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); endDate = cal.getTime(); } } catch (java.text.ParseException e1) { logger.warn(e1); } String format = "html"; if (request.getParameter("format")!=null) format = request.getParameter("format"); int pageIdx = 1; int pageSize = 20; if (request.getParameter("pageIdx") != null) pageIdx = Integer.parseInt(request.getParameter("pageIdx")); if (request.getParameter("pageSize") != null) pageSize = Integer.parseInt(request.getParameter("pageSize")); //now calculate start, end idx based on pageIdx and pageSize int start = (pageIdx - 1) * pageSize; SearchResultSet srs; StringBuilder searchText = new StringBuilder(); if (term != null) searchText.append(term); try { if (type != null && type.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("otype:"); searchText.append(type.equals("res") ? "bill AND oid:r*":type); } if(session != null && session.length() > 0) { if(searchText.length() > 0) searchText.append(" AND "); searchText.append("year:" + session); } if (full != null && full.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("(full:\""); searchText.append(full); searchText.append("\""); searchText.append(" OR "); searchText.append("osearch:\""); searchText.append(full); searchText.append("\")"); } if (memo != null && memo.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("memo:\""); searchText.append(memo); searchText.append("\""); } if (status != null && status.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("status:\""); searchText.append(status); searchText.append("\""); } if (sponsor != null && sponsor.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sponsor:\""); searchText.append(sponsor); searchText.append("\""); } if (cosponsors != null && cosponsors.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("cosponsors:\""); searchText.append(cosponsors); searchText.append("\""); } if (sameas != null && sameas.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("sameas:"); searchText.append(sameas); } if (committee != null && committee.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("committee:\""); searchText.append(committee); searchText.append("\""); } if (location != null && location.length() > 0) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("location:\""); searchText.append(location); searchText.append("\""); } if (startDate != null && endDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); searchText.append(endDate.getTime()); searchText.append("]"); } else if (startDate != null) { if (searchText.length()>0) searchText.append(" AND "); searchText.append("when:["); searchText.append(startDate.getTime()); searchText.append(" TO "); Calendar cal = Calendar.getInstance(); cal.setTime(startDate); cal.set(Calendar.HOUR, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); startDate = cal.getTime(); searchText.append(startDate.getTime()); searchText.append("]"); } term = searchText.toString(); term = BillCleaner.billFormat(term); request.setAttribute("term", term); request.setAttribute("type", type); //default behavior is to return only active bills, so if a user searches //s1234 and s1234a is available then s1234a should be returned if(sortField == null && (((search != null && search.contains("otype:bill")) || (term != null && term.contains("otype:bill"))) || (type != null && type.equals("bill")))) { sortField = "sortindex"; sortOrder = false; type = "bill"; } if (sortField!=null && !sortField.equals("")) { request.setAttribute("sortField", sortField); request.setAttribute("sortOrder",Boolean.toString(sortOrder)); } else { sortField = "when"; sortOrder = true; request.setAttribute("sortField", sortField); request.setAttribute("sortOrder", Boolean.toString(sortOrder)); } request.setAttribute(OpenLegConstants.PAGE_IDX,pageIdx+""); request.setAttribute(OpenLegConstants.PAGE_SIZE,pageSize+""); srs = null; if (term.length() == 0) { response.sendError(404); return; } String searchFormat = "json"; SenateResponse sr = null; if(term != null && !term.contains("year:") && !term.contains("when:") && !term.contains("oid:")) { if(type != null && type.equals("bill")) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } else { sr = searchEngine.search(term + " AND when:[" + DATE_START + " TO " + DATE_END + "]",searchFormat,start,pageSize,sortField,sortOrder); if(sr.getResults().isEmpty()) { sr = searchEngine.search(term + " AND year:" + SessionYear.getSessionYear(),searchFormat,start,pageSize,sortField,sortOrder); } } } else { sr = searchEngine.search(term,searchFormat,start,pageSize,sortField,sortOrder); } srs = new SearchResultSet(); srs.setTotalHitCount((Integer)sr.getMetadata().get("totalresults")); srs.setResults(ApiHelper.buildSearchResultList(sr)); if (srs != null) { if (srs.getResults().size() == 0) { response.sendError(404); } else { request.setAttribute("results", srs); String viewPath = "/views/search-" + format + DOT_JSP; getServletContext().getRequestDispatcher(viewPath).forward(request, response); } } else { logger.error("Search Error: " + request.getRequestURI()); response.sendError(500); } } catch (Exception e) { logger.error("Search Error: " + request.getRequestURI(),e); e.printStackTrace(); response.sendError(500); } } #location 270 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Benchmark public int offerAndPollLoops() { final int burstSize = this.burstSize; for (int i = 0; i < burstSize; i++) { q.offer(DUMMY_MESSAGE); } Integer result = DUMMY_MESSAGE; for (int i = 0; i < burstSize; i++) { result = q.poll(); } return result; }
#vulnerable code @Benchmark public int offerAndPollLoops() { final int burstSize = this.burstSize; for (int i = 0; i < burstSize; i++) { q.offer(DUMMY_MESSAGE); } Integer result = null; for (int i = 0; i < burstSize; i++) { result = q.poll(); } return result; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); }
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); arrayIndexScale = JvmUtil.arrayIndexScale(elementType); arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, length); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, length); if (initializeElements) { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = sampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < length; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } } else { // All index is object pool array header point to allocated objects for (long l = 0; l < length; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0); } } this.objectArray = (A) directMemoryService.getObject(allocationStartAddress); switch (JvmUtil.getAddressSize()) { case JvmUtil.SIZE_32_BIT: jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); break; case JvmUtil.SIZE_64_BIT: int referenceSize = JvmUtil.getReferenceSize(); switch (referenceSize) { case JvmUtil.ADDRESSING_4_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; case JvmUtil.ADDRESSING_8_BYTE: jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); break; default: throw new AssertionError("Unsupported reference size: " + referenceSize); } break; default: throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); } } #location 59 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } sampleHeader = directMemoryService.getLong(sampleObject, 0L); objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); }
#vulnerable code protected void init(Class<T> elementType, long objectCount, NonPrimitiveFieldAllocationConfigType allocateNonPrimitiveFieldsAtOffHeapConfigType, DirectMemoryService directMemoryService) { super.init(elementType, allocateNonPrimitiveFieldsAtOffHeapConfigType, directMemoryService); if (elementType.isAnnotation()) { throw new IllegalArgumentException("Annotation class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isInterface()) { throw new IllegalArgumentException("Interface class " + "(" + elementType.getName() + ")" + " is not supported !"); } if (elementType.isAnonymousClass()) { throw new IllegalArgumentException("Anonymous class " + "(" + elementType.getName() + ")" + " is not supported !"); } this.elementType = elementType; this.objectCount = objectCount; this.usedObjectCount = 0; this.directMemoryService = directMemoryService; inUseBlockCount = objectCount; inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleObject = JvmUtil.getSampleInstance(elementType); if (sampleObject == null) { throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); } synchronized (sampleObject) { sampleHeader = directMemoryService.getLong(sampleObject, 0L); } objectSize = directMemoryService.sizeOfObject(sampleObject); offHeapSampleObjectAddress = directMemoryService.allocateMemory(objectSize); directMemoryService.copyMemory(sampleObject, 0L, null, offHeapSampleObjectAddress, objectSize); /* for (int i = 0; i < objectSize; i += JvmUtil.LONG_SIZE) { directMemoryService.putLong(offHeapSampleObjectAddress + i, directMemoryService.getLong(sampleObject, i)); } */ /* for (int i = 0; i < objectSize; i++) { directMemoryService.putByte(offHeapSampleObjectAddress + i, directMemoryService.getByte(sampleObject, i)); } */ // directMemoryService.copyMemory(directMemoryService.addressOf(sampleObject), offHeapSampleObjectAddress, objectSize); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { objectsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); }
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objectsStartAddress += (JvmUtil.getAddressSize() - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, (int) objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() { ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool = offHeapService.createOffHeapPool( new DefaultExtendableObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). elementType(SampleOffHeapClass.class). build()); List<SampleOffHeapClass> objList = new ArrayList<SampleOffHeapClass>(); for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = extendableObjectPool.get(); Assert.assertEquals(0, obj.getOrder()); obj.setOrder(i); Assert.assertEquals(i, obj.getOrder()); objList.add(obj); } for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objList.get(i); Assert.assertEquals(i, obj.getOrder()); } }
#vulnerable code @Test public void objectRetrievedSuccessfullyFromExtendableObjectOffHeapPoolWithDefaultObjectOffHeapPool() { ExtendableObjectOffHeapPool<SampleOffHeapClass> extendableObjectPool = offHeapService.createOffHeapPool( new DefaultExtendableObjectOffHeapPoolCreateParameterBuilder<SampleOffHeapClass>(). elementType(SampleOffHeapClass.class). build()); List<SampleOffHeapClass> objList = new ArrayList<SampleOffHeapClass>(); for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = extendableObjectPool.get(); obj.setOrder(i); objList.add(obj); } for (int i = 0; i < TOTAL_ELEMENT_COUNT; i++) { SampleOffHeapClass obj = objList.get(i); Assert.assertEquals(i, obj.getOrder()); } } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index > length) { throw new IllegalArgumentException("Invalid index: " + index); } processObject( jvmAwareArrayElementAddressFinder.findAddress( arrayIndexStartAddress, arrayIndexScale, index)); T obj = ((T[])(getObjectArray()))[index]; if (obj instanceof OffHeapAwareObject) { ((OffHeapAwareObject) obj).onGet(offHeapService, directMemoryService); } return obj; }
#vulnerable code @SuppressWarnings("unchecked") @Override public T getAt(int index) { checkAvailability(); if (index < 0 || index > length) { throw new IllegalArgumentException("Invalid index: " + index); } processObject( jvmAwareArrayElementAddressFinder.findAddress( arrayIndexStartAddress, arrayIndexScale, index)); T obj = ((T[])(objectArray))[index]; if (obj instanceof OffHeapAwareObject) { ((OffHeapAwareObject) obj).onGet(offHeapService, directMemoryService); } return obj; } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objectsStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objectsStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objectsStartAddress += (JvmUtil.getAddressSize() - addressMod); } objectsEndAddress = objectsStartAddress + (objectCount * objectSize); // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte( allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong( arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objectsStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objectsStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); }
#vulnerable code @SuppressWarnings("unchecked") @Override protected void init() { super.init(); this.currentIndex = 0; int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); int arrayIndexScale = JvmUtil.arrayIndexScale(elementType); long arrayIndexStartAddress = allocationStartAddress + JvmUtil.arrayBaseOffset(elementType); objStartAddress = allocationStartAddress + JvmUtil.sizeOfArray(elementType, objectCount); // Allocated objects must start aligned as address size from start address of allocated address long diffBetweenArrayAndObjectStartAddresses = objStartAddress - allocationStartAddress; long addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.getAddressSize(); if (addressMod != 0) { objStartAddress += (JvmUtil.getAddressSize() - addressMod); } // Copy sample array header to object pool array header for (int i = 0; i < arrayHeaderSize; i++) { directMemoryService.putByte(allocationStartAddress + i, directMemoryService.getByte(sampleArray, i)); } // Set length of array object pool array JvmUtil.setArrayLength(allocationStartAddress, elementType, objectCount); // All index is object pool array header point to allocated objects for (long l = 0; l < objectCount; l++) { directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); } long sourceAddress = offHeapSampleObjectAddress + 4; long copySize = objectSize - 4; // Copy sample object to allocated memory region for each object for (long l = 0; l < objectCount; l++) { long targetAddress = objStartAddress + (l * objectSize); directMemoryService.putInt(targetAddress, 0); directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); } this.objectArray = (T[]) directMemoryService.getObject(allocationStartAddress); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected long allocateStringFromOffHeap(String str) { long addressOfStr = directMemoryService.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize; // + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod1 != 0) { currentAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod2 != 0) { valueAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; }
#vulnerable code protected long allocateStringFromOffHeap(String str) { long addressOfStr = JvmUtil.addressOf(str); char[] valueArray = (char[]) directMemoryService.getObject(str, valueArrayOffsetInString); int valueArraySize = charArrayIndexStartOffset + (charArrayIndexScale * valueArray.length); int strSize = stringSize + valueArraySize + JvmUtil.getAddressSize(); // Extra memory for possible aligning long addressMod1 = currentAddress % JvmUtil.getAddressSize(); if (addressMod1 != 0) { currentAddress += (JvmUtil.getAddressSize() - addressMod1); } if (currentAddress + strSize > allocationEndAddress) { return 0; } // Copy string object content to allocated area directMemoryService.copyMemory(addressOfStr, currentAddress, strSize); long valueAddress = currentAddress + stringSize; long addressMod2 = valueAddress % JvmUtil.getAddressSize(); if (addressMod2 != 0) { valueAddress += (JvmUtil.getAddressSize() - addressMod2); } // Copy value array in allocated string to allocated char array directMemoryService.copyMemory( JvmUtil.toNativeAddress( directMemoryService.getAddress(addressOfStr + valueArrayOffsetInString)), valueAddress, valueArraySize); // Now, value array in allocated string points to allocated char array directMemoryService.putAddress( currentAddress + valueArrayOffsetInString, JvmUtil.toJvmAddress(valueAddress)); long allocatedStrAddress = currentAddress; currentAddress += strSize; return allocatedStrAddress; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; segmentCount = allocationSize / STRING_SEGMENT_SIZE; long segmentCountMod = allocationSize % STRING_SEGMENT_SIZE; if (segmentCountMod != 0) { segmentCount++; } inUseBlockCount = segmentCount / STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; long blockCountMod = segmentCount % STRING_SEGMENT_COUNT_AT_AN_IN_USE_BLOCK; if (blockCountMod != 0) { inUseBlockCount++; fullValueOfLastBlock = (byte)(Math.pow(2, blockCountMod) - 1); } else { fullValueOfLastBlock = BLOCK_IS_FULL_VALUE; } inUseBlockAddress = directMemoryService.allocateMemory(inUseBlockCount); sampleHeader = directMemoryService.getInt(new String(), 0L); init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } }
#vulnerable code @SuppressWarnings("deprecation") protected void init(int estimatedStringCount, int estimatedStringLength) { try { this.estimatedStringCount = estimatedStringCount; this.estimatedStringLength = estimatedStringLength; charArrayIndexScale = JvmUtil.arrayIndexScale(char.class); charArrayIndexStartOffset = JvmUtil.arrayBaseOffset(char.class); valueArrayOffsetInString = JvmUtil.getUnsafe().fieldOffset(String.class.getDeclaredField("value")); stringSize = (int) JvmUtil.sizeOf(String.class); int estimatedStringSize = (int) (stringSize + JvmUtil.sizeOfArray(char.class, estimatedStringLength)); allocationSize = (estimatedStringSize * estimatedStringCount) + JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning allocationStartAddress = directMemoryService.allocateMemory(allocationSize); allocationEndAddress = allocationStartAddress + allocationSize; // Allocated objects must start aligned as address size from start address of allocated address stringsStartAddress = allocationStartAddress; long addressMod = stringsStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; if (addressMod != 0) { stringsStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); } currentAddress = stringsStartAddress; sampleStr = new String(); sampleStrAddress = JvmUtil.addressOf(sampleStr); sampleCharArray = new char[0]; init(); makeAvaiable(); } catch (Throwable t) { logger.error("Error occured while initializing \"StringOffHeapPool\"", t); throw new IllegalStateException(t); } } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION