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 public void flush() throws IOException { ByteBuffer buffer = this.bufferQueue.peek(); while ( buffer != null ) { sockchannel.write( buffer ); if( buffer.remaining() > 0 ) { continue; } else { // subtract this amount of data from the total queued (synchronized over this object) bufferQueueTotalAmount.addAndGet(-buffer.limit()); this.bufferQueue.poll(); // Buffer finished. Remove it. buffer = this.bufferQueue.peek(); } } }
#vulnerable code public void flush() throws IOException { ByteBuffer buffer = this.bufferQueue.peek(); while ( buffer != null ) { sockchannel.write( buffer ); if( buffer.remaining() > 0 ) { continue; } else { synchronized ( bufferQueueTotalAmount ) { // subtract this amount of data from the total queued (synchronized over this object) bufferQueueTotalAmount -= buffer.limit(); } this.bufferQueue.poll(); // Buffer finished. Remove it. buffer = this.bufferQueue.peek(); } } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; SocketChannelIOHelper.batch( conn, channel ); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.eot( e ); } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; }
#vulnerable code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, client ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; conn.flush(); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && conn.read( buff ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isWritable() ) { conn.flush(); } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error conn.flush(); } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); return; } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false ); return; } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { client.close(); } catch ( IOException e ) { onError( e ); } client = null; } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( selectorthread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); selectorthread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } try { while ( !selectorthread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( !key.isValid() ) { continue; } if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); asyncQueueRead( conn ); // conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client /*if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); }*/ } /*synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the selectorthread that // adds the buffered data to the WebSocket, because the // Selector is not selectorthread-safe, and can only be accessed // by this selectorthread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } }*/ } catch ( IOException ex ) { if( key != null ) key.cancel(); handleIOException( conn, ex ); } } } catch ( RuntimeException e ) { // should hopefully never occur onError( null, e ); try { selector.close(); } catch ( IOException e1 ) { onError( null, e1 ); } decoders.shutdown(); } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } } #location 52 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; SocketChannelIOHelper.batch( conn, channel ); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.eot( e ); } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; }
#vulnerable code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, client ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; conn.flush(); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && conn.read( buff ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isWritable() ) { conn.flush(); } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error conn.flush(); } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); return; } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false ); return; } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { client.close(); } catch ( IOException e ) { onError( e ); } client = null; } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( selectorthread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); selectorthread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } try { while ( !selectorthread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( !key.isValid() ) { continue; } if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); asyncQueueRead( conn ); // conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client /*if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); }*/ } /*synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the selectorthread that // adds the buffered data to the WebSocket, because the // Selector is not selectorthread-safe, and can only be accessed // by this selectorthread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } }*/ } catch ( IOException ex ) { if( key != null ) key.cancel(); handleIOException( conn, ex ); } } } catch ( RuntimeException e ) { // should hopefully never occur onError( null, e ); try { selector.close(); } catch ( IOException e1 ) { onError( null, e1 ); } decoders.shutdown(); } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } } #location 34 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void start() { if( selectorthread != null ) throw new IllegalStateException( "Already started" ); new Thread( this ).start(); }
#vulnerable code public void start() { if( thread != null ) throw new IllegalStateException( "Already started" ); new Thread( this ).start(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( selectorthread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); selectorthread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } try { while ( !selectorthread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( !key.isValid() ) { continue; } if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); asyncQueueRead( conn ); // conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client /*if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); }*/ } /*synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the selectorthread that // adds the buffered data to the WebSocket, because the // Selector is not selectorthread-safe, and can only be accessed // by this selectorthread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } }*/ } catch ( IOException ex ) { if( key != null ) key.cancel(); handleIOException( conn, ex ); } } } catch ( RuntimeException e ) { // should hopefully never occur onError( null, e ); try { selector.close(); } catch ( IOException e1 ) { onError( null, e1 ); } decoders.shutdown(); } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void decode( ByteBuffer socketBuffer ) throws IOException { if( !socketBuffer.hasRemaining() || connectionClosed ) return; if( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" ); if( handshakeComplete ) { decodeFrames( socketBuffer ); } else { if( decodeHandshake( socketBuffer ) ) { decodeFrames( socketBuffer ); } } assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() ); }
#vulnerable code public void decode( ByteBuffer socketBuffer ) throws IOException { if( !socketBuffer.hasRemaining() ) return; if( DEBUG ) System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" ); if( handshakeComplete ) { decodeFrames( socketBuffer ); } else { if( decodeHandshake( socketBuffer ) ) { decodeFrames( socketBuffer ); } } assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() ); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; SocketChannelIOHelper.batch( conn, channel ); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.eot( e ); } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; }
#vulnerable code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, client ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; conn.flush(); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && conn.read( buff ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isWritable() ) { conn.flush(); } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error conn.flush(); } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); return; } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false ); return; } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { client.close(); } catch ( IOException e ) { onError( e ); } client = null; } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); assert ( !channel.isOpen() ); try { if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null selector.close(); } catch ( IOException e ) { onError( e ); } }
#vulnerable code public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); try { if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; thread = null; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } catch ( Throwable e ) { System.out.println( e ); e.printStackTrace(); } } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( selectorthread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); selectorthread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } try { while ( !selectorthread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( !key.isValid() ) { continue; } if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); asyncQueueRead( conn ); // conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client /*if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); }*/ } /*synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the selectorthread that // adds the buffered data to the WebSocket, because the // Selector is not selectorthread-safe, and can only be accessed // by this selectorthread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } }*/ } catch ( IOException ex ) { if( key != null ) key.cancel(); handleIOException( conn, ex ); } } } catch ( RuntimeException e ) { // should hopefully never occur onError( null, e ); try { selector.close(); } catch ( IOException e1 ) { onError( null, e1 ); } decoders.shutdown(); } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void stop() throws IOException { synchronized ( connections ) { for( WebSocket ws : connections ) { ws.close( CloseFrame.NORMAL ); } } selectorthread.interrupt(); this.server.close(); }
#vulnerable code public void stop() throws IOException { synchronized ( connections ) { for( WebSocket ws : connections ) { ws.close( CloseFrame.NORMAL ); } } thread.interrupt(); this.server.close(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); assert ( !channel.isOpen() ); try { if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null selector.close(); } catch ( IOException e ) { onError( e ); } }
#vulnerable code public void run() { if( thread == null ) thread = Thread.currentThread(); interruptableRun(); try { if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; thread = null; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void stop() throws IOException , InterruptedException { stop( 0 ); }
#vulnerable code public void stop() throws IOException , InterruptedException { synchronized ( connections ) { for( WebSocket ws : connections ) { ws.close( CloseFrame.NORMAL ); } } selectorthread.interrupt(); selectorthread.join(); for( WebSocketWorker w : decoders ) { w.interrupt(); } this.server.close(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() { if( selectorthread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); selectorthread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } try { while ( !selectorthread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( !key.isValid() ) { continue; } if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); asyncQueueRead( conn ); // conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client /*if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); }*/ } /*synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the selectorthread that // adds the buffered data to the WebSocket, because the // Selector is not selectorthread-safe, and can only be accessed // by this selectorthread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } }*/ } catch ( IOException ex ) { if( key != null ) key.cancel(); handleIOException( conn, ex ); } } } catch ( RuntimeException e ) { // should hopefully never occur onError( null, e ); try { selector.close(); } catch ( IOException e1 ) { onError( null, e1 ); } decoders.shutdown(); } }
#vulnerable code public void run() { if( thread != null ) throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." ); thread = Thread.currentThread(); try { server = ServerSocketChannel.open(); server.configureBlocking( false ); server.socket().bind( address ); // InetAddress.getLocalHost() selector = Selector.open(); server.register( selector, server.validOps() ); } catch ( IOException ex ) { onWebsocketError( null, ex ); return; } while ( !thread.isInterrupted() ) { SelectionKey key = null; WebSocket conn = null; try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); // Remove the current key i.remove(); // if isAcceptable == true // then a client required a connection if( key.isAcceptable() ) { SocketChannel client = server.accept(); client.configureBlocking( false ); WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client ); client.register( selector, SelectionKey.OP_READ, c ); } // if isReadable == true // then the server is ready to read if( key.isReadable() ) { conn = (WebSocket) key.attachment(); conn.handleRead(); } // if isWritable == true // then we need to send the rest of the data to the client if( key.isValid() && key.isWritable() ) { conn = (WebSocket) key.attachment(); conn.flush(); key.channel().register( selector, SelectionKey.OP_READ, conn ); } } synchronized ( connections ) { Iterator<WebSocket> it = this.connections.iterator(); while ( it.hasNext() ) { // We have to do this check here, and not in the thread that // adds the buffered data to the WebSocket, because the // Selector is not thread-safe, and can only be accessed // by this thread. conn = it.next(); if( conn.hasBufferedData() ) { conn.flush(); // key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn ); } } } } catch ( IOException ex ) { if( key != null ) key.cancel(); onWebsocketError( conn, ex );// conn may be null here if( conn != null ) { conn.close( CloseFrame.ABNROMAL_CLOSE ); } } } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public final void onWriteDemand( WebSocket conn ) { try { conn.flush(); } catch ( IOException e ) { handleIOException( conn, e ); } /*synchronized ( write_demands ) { if( !write_demands.contains( conn ) ) { write_demands.add( conn ); flusher.submit( new WebsocketWriteTask( conn ) ); } }*/ }
#vulnerable code @Override public final void onWriteDemand( WebSocket conn ) { selector.wakeup(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void stop() throws IOException { for( WebSocket ws : connections ) { ws.close( CloseFrame.NORMAL ); } thread.interrupt(); this.server.close(); }
#vulnerable code public void stop() throws IOException { synchronized ( connections ) { for( WebSocket ws : connections ) { ws.close( CloseFrame.NORMAL ); } } thread.interrupt(); this.server.close(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; SocketChannelIOHelper.batch( conn, channel ); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.eot( e ); } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { channel.close(); } catch ( IOException e ) { onError( e ); } channel = null; }
#vulnerable code protected final void interruptableRun() { try { tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) ); } catch ( ClosedByInterruptException e ) { onWebsocketError( null, e ); return; } catch ( IOException e ) {// onWebsocketError( conn, e ); return; } catch ( SecurityException e ) { onWebsocketError( conn, e ); return; } catch ( UnresolvedAddressException e ) { onWebsocketError( conn, e ); return; } conn = (WebSocketImpl) wf.createWebSocket( this, draft, client ); ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF ); try/*IO*/{ while ( !conn.isClosed() ) { if( Thread.interrupted() ) { conn.close( CloseFrame.NORMAL ); } SelectionKey key = null; conn.flush(); selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> i = keys.iterator(); while ( i.hasNext() ) { key = i.next(); i.remove(); if( key.isReadable() && conn.read( buff ) ) { conn.decode( buff ); } if( !key.isValid() ) { continue; } if( key.isWritable() ) { conn.flush(); } if( key.isConnectable() ) { try { finishConnect(); } catch ( InterruptedException e ) { conn.close( CloseFrame.NEVERCONNECTED );// report error to only break; } catch ( InvalidHandshakeException e ) { conn.close( e ); // http error conn.flush(); } } } } } catch ( IOException e ) { onError( e ); conn.close( CloseFrame.ABNORMAL_CLOSE ); return; } catch ( RuntimeException e ) { // this catch case covers internal errors only and indicates a bug in this websocket implementation onError( e ); conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false ); return; } try { selector.close(); } catch ( IOException e ) { onError( e ); } closelock.lock(); selector = null; closelock.unlock(); try { client.close(); } catch ( IOException e ) { onError( e ); } client = null; } #location 74 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public TaskTestContext assertOutputSize(int size) { requireMultipleOutputs(); String[] files = fileOutput.list(); assertEquals("An unexpected number of output files has been created: " + StringUtils.join(files, ","), size, files.length); return this; }
#vulnerable code public TaskTestContext assertOutputSize(int size) { requireMultipleOutputs(); assertEquals("An unexpected number of output files has been created", size, fileOutput.listFiles().length); return this; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void mergeNull() { PDDocument destination = new PDDocument(); AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination); assertNotNull(document.getDocumentCatalog().getAcroForm()); victim.mergeForm(null, annotationsLookup); assertTrue(victim.getForm().getFields().isEmpty()); assertNull(destination.getDocumentCatalog().getAcroForm()); }
#vulnerable code @Test public void mergeNull() { PDDocument destination = new PDDocument(); AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination); assertNotNull(document.getDocumentCatalog().getAcroForm()); victim.mergeForm(null, annotationsLookup); assertFalse(victim.hasForm()); assertNull(destination.getDocumentCatalog().getAcroForm()); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasics() throws TaskException, IOException { withSource("pdf/unoptimized.pdf"); victim.execute(parameters); assertThat(sizeOfResult(), is(lessThan(104L))); }
#vulnerable code @Test public void testBasics() throws TaskException, IOException { parameters.setOutput(new DirectoryTaskOutput(outputFolder)); victim.execute(parameters); long sizeInKb = outputFolder.listFiles()[0].length() / 1000; assertThat(sizeInKb, is(lessThan(104L))); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void extract(PDDocument document, File output) throws TaskException { if (document == null) { throw new TaskException("Unable to extract text from a null document."); } if (output == null || !output.isFile() || !output.canWrite()) { throw new TaskException(String.format("Cannot write extracted text to a the given output file '%s'.", output)); } try { outputWriter = Files.newBufferedWriter(output.toPath(), Charset.forName(encoding)); textStripper.writeText(document, outputWriter); } catch (IOException e) { throw new TaskExecutionException("An error occurred extracting text from a pdf source.", e); } }
#vulnerable code public void extract(PDDocument document, File output) throws TaskException { if (document == null) { throw new TaskException("Unable to extract text from a null document."); } if (output == null || !output.isFile() || !output.canWrite()) { throw new TaskException(String.format("Cannot write extracted text to a the given output file '%s'.", output)); } try { outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), encoding)); textStripper.writeText(document, outputWriter); } catch (IOException e) { throw new TaskExecutionException("An error occurred extracting text from a pdf source.", e); } } #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 canDisplayGeorgian() { assertNotNull(findFontFor("ქართული ენა")); }
#vulnerable code @Test public void canDisplayGeorgian() { PDFont font = FontUtils.findFontFor(new PDDocument(), "ქართული ენა"); assertNotNull("No font available for Georgian", font); assertThat(font.getName(), is("NotoSansGeorgian")); } #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 resolveTextAndFontsWhenTextRepeats() throws TaskIOException { write("123α456α789"); }
#vulnerable code @Test public void resolveTextAndFontsWhenTextRepeats() throws TaskIOException { PageTextWriter writer = new PageTextWriter(new PDDocument()); List<PageTextWriter.TextWithFont> textAndFonts = writer.resolveFonts("123α456α789", helvetica); assertThat(textAndFonts.get(0).getFont().getName(), is("Helvetica")); assertThat(textAndFonts.get(0).getText(), is("123")); assertThat(textAndFonts.get(1).getFont().getName(), is(not("Helvetica"))); assertThat(textAndFonts.get(1).getText(), is("α")); assertThat(textAndFonts.get(2).getFont().getName(), is("Helvetica")); assertThat(textAndFonts.get(2).getText(), is("456")); assertThat(textAndFonts.get(3).getFont().getName(), is(not("Helvetica"))); assertThat(textAndFonts.get(3).getText(), is("α")); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(JpegToPdfParameters parameters) throws TaskException { final MutableInt currentStep = new MutableInt(0); ImagesToPdfDocumentConverter converter = new ImagesToPdfDocumentConverter() { @Override public void beforeImage(Source<?> source) throws TaskException { executionContext().assertTaskNotCancelled(); currentStep.increment(); } @Override public void afterImage(PDImageXObject image) { notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(currentStep.getValue()).outOf(totalSteps); } @Override public void failedImage(Source<?> source, TaskIOException e) throws TaskException{ executionContext().assertTaskIsLenient(e); notifyEvent(executionContext().notifiableTaskMetadata()).taskWarning( String.format("Image %s was skipped, could not be processed", source.getName()), e); } }; documentHandler = converter.convert(parameters.getSourceList()); File tmpFile = createTemporaryBuffer(parameters.getOutput()); LOG.debug("Created output on temporary buffer {}", tmpFile); documentHandler.setVersionOnPDDocument(parameters.getVersion()); documentHandler.setCompress(parameters.isCompress()); documentHandler.savePDDocument(tmpFile); String outName = nameGenerator(parameters.getOutputPrefix()).generate(nameRequest()); outputWriter.addOutput(file(tmpFile).name(outName)); nullSafeCloseQuietly(documentHandler); parameters.getOutput().accept(outputWriter); LOG.debug("Input images written to {}", parameters.getOutput()); }
#vulnerable code @Override public void execute(JpegToPdfParameters parameters) throws TaskException { int currentStep = 0; documentHandler = new PDDocumentHandler(); documentHandler.setCreatorOnPDDocument(); PageImageWriter imageWriter = new PageImageWriter(documentHandler.getUnderlyingPDDocument()); for (Source<?> source : parameters.getSourceList()) { executionContext().assertTaskNotCancelled(); currentStep++; try { PDImageXObject image = PageImageWriter.toPDXImageObject(source); PDRectangle mediaBox = PDRectangle.A4; if (image.getWidth() > image.getHeight() && image.getWidth() > mediaBox.getWidth()) { mediaBox = new PDRectangle(mediaBox.getHeight(), mediaBox.getWidth()); } PDPage page = documentHandler.addBlankPage(mediaBox); // full page (scaled down only) int width = image.getWidth(); int height = image.getHeight(); if (width > mediaBox.getWidth()) { int targetWidth = (int) mediaBox.getWidth(); LOG.debug("Scaling image down to fit by width {} vs {}", width, targetWidth); float ratio = (float) width / targetWidth; width = targetWidth; height = Math.round(height / ratio); } if (height > mediaBox.getHeight()) { int targetHeight = (int) mediaBox.getHeight(); LOG.debug("Scaling image down to fit by height {} vs {}", height, targetHeight); float ratio = (float) height / targetHeight; height = targetHeight; width = Math.round(width / ratio); } // centered on page int x = ((int) mediaBox.getWidth() - width) / 2; int y = ((int) mediaBox.getHeight() - height) / 2; imageWriter.append(page, image, new Point(x, y), width, height, null, 0); notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(currentStep).outOf(totalSteps); } catch (TaskIOException e) { executionContext().assertTaskIsLenient(e); notifyEvent(executionContext().notifiableTaskMetadata()).taskWarning( String.format("Image %s was skipped, could not be processed", source.getName()), e); } } File tmpFile = createTemporaryBuffer(parameters.getOutput()); LOG.debug("Created output on temporary buffer {}", tmpFile); documentHandler.setVersionOnPDDocument(parameters.getVersion()); documentHandler.setCompress(parameters.isCompress()); documentHandler.savePDDocument(tmpFile); String outName = nameGenerator(parameters.getOutputPrefix()).generate(nameRequest()); outputWriter.addOutput(file(tmpFile).name(outName)); nullSafeCloseQuietly(documentHandler); parameters.getOutput().accept(outputWriter); LOG.debug("Input images written to {}", parameters.getOutput()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void resolvedSpaceSeparately() throws TaskIOException { write("ab cd"); }
#vulnerable code @Test public void resolvedSpaceSeparately() throws TaskIOException { PageTextWriter writer = new PageTextWriter(new PDDocument()); List<PageTextWriter.TextWithFont> textAndFonts = writer.resolveFonts("ab cd", helvetica); assertThat(textAndFonts.get(0).getFont().getName(), is("Helvetica")); assertThat(textAndFonts.get(0).getText(), is("ab")); assertThat(textAndFonts.get(1).getFont().getName(), is("Helvetica")); assertThat(textAndFonts.get(1).getText(), is(" ")); assertThat(textAndFonts.get(2).getFont().getName(), is("Helvetica")); assertThat(textAndFonts.get(2).getText(), is("cd")); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException { try (ZipOutputStream zipOut = new ZipOutputStream(out)) { for (Entry<String, File> entry : files.entrySet()) { if (isBlank(entry.getKey())) { throw new IOException(String.format( "Unable to copy %s to the output stream, no output name specified.", entry.getValue())); } try (FileInputStream input = new FileInputStream(entry.getValue())) { zipOut.putNextEntry(new ZipEntry(entry.getKey())); LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey()); IOUtils.copy(input, zipOut); } finally { delete(entry.getValue()); } } } }
#vulnerable code static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException { ZipOutputStream zipOut = new ZipOutputStream(out); for (Entry<String, File> entry : files.entrySet()) { FileInputStream input = null; if (isBlank(entry.getKey())) { throw new IOException(String.format("Unable to copy %s to the output stream, no output name specified.", entry.getValue())); } try { input = new FileInputStream(entry.getValue()); zipOut.putNextEntry(new ZipEntry(entry.getKey())); LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey()); IOUtils.copy(input, zipOut); } finally { IOUtils.closeQuietly(input); delete(entry.getValue()); } } IOUtils.closeQuietly(zipOut); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public TaskTestContext assertEmptyMultipleOutput() { assertNotNull(fileOutput); assertTrue("Expected an output directory", fileOutput.isDirectory()); assertEquals("Found output files while expecting none", 0, fileOutput.listFiles((d, n) -> !n.endsWith(".tmp")).length); return this; }
#vulnerable code public TaskTestContext assertEmptyMultipleOutput() { assertNotNull(fileOutput); assertTrue("Expected an output directory", fileOutput.isDirectory()); assertEquals("Found output files while expecting none", 0, fileOutput.listFiles().length); return this; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFindFontFor() { assertNotNull(findFontFor("ทดสอบ")); // thai assertNotNull(findFontFor("αυτό είναι ένα τεστ")); // greek assertNotNull(findFontFor("വീട്")); // malayalam assertNotNull(findFontFor("मानक")); // hindi assertNotNull(findFontFor("జ")); // telugu assertNotNull(findFontFor("উ")); // bengali assertNotNull(findFontFor("עברית")); // hebrew assertNotNull(findFontFor("简化字")); // simplified chinese assertNotNull(findFontFor("한국어/조선말")); // korean assertNotNull(findFontFor("日本語")); // japanese assertNotNull(findFontFor("latin ąćęłńóśźż")); // latin }
#vulnerable code @Test public void testFindFontFor() { assertEquals("NotoSansThai", findFontFor(new PDDocument(), "ทดสอบ").getName()); assertEquals("NotoSans", findFontFor(new PDDocument(), "αυτό είναι ένα τεστ").getName()); assertNull(findFontFor(new PDDocument(), "വീട്")); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void before(AlternateMixParameters parameters, TaskExecutionContext executionContext) throws TaskException { super.before(parameters, executionContext); mixer = new PdfAlternateMixer(); outputWriter = OutputWriters.newSingleOutputWriter(parameters.getExistingOutputPolicy(), executionContext); }
#vulnerable code @Override public void before(AlternateMixParameters parameters, TaskExecutionContext executionContext) throws TaskException { super.before(parameters, executionContext); mixer = new PdfAlternateMixer(parameters.getFirstInput(), parameters.getSecondInput()); outputWriter = OutputWriters.newSingleOutputWriter(parameters.getExistingOutputPolicy(), executionContext); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static ArchiveOutputStream createArchiveOutputStream(CommonsArchiver archiver, File archive) throws IOException, ArchiveException { return createArchiveOutputStream(archiver.getArchiveFormat(), archive); }
#vulnerable code static ArchiveOutputStream createArchiveOutputStream(CommonsArchiver archiver, File archive) throws IOException, ArchiveException { return createArchiveOutputStream(archiver.getFileType(), new FileOutputStream(archive)); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static FileModeMapper create(ArchiveEntry entry) { if (IS_POSIX) { return new PosixPermissionMapper(entry); } // TODO: implement basic windows permission mapping (e.g. with File.setX or attrib) return new FallbackFileModeMapper(entry); }
#vulnerable code public static FileModeMapper create(ArchiveEntry entry) { if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { // FIXME: this is really horrid, but with java 6 i need the system call to 'chmod' // TODO: implement basic windows permission mapping (e.g. with File.setX or attrib) return new FallbackFileModeMapper(entry); } // please don't use me on OS/2 return new UnixPermissionMapper(entry); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination) throws IOException, CompressorException { return createCompressorOutputStream(compressor.getCompressionType(), destination); }
#vulnerable code static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination) throws IOException, CompressorException { return createCompressorOutputStream(compressor.getFileType(), new FileOutputStream(destination)); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void initialize() { InputStream in = PinyinDic.class.getResourceAsStream(dicLocation); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); try { String line = null; long startPoint = System.currentTimeMillis(); while (null != (line = reader.readLine())) { if (StringUtils.isNotBlank(line)) { dicSet.add(line); } } long endPoint = System.currentTimeMillis(); Logger.logger.info(String.format("Load pinyin from pinyin.dic, sizeof dic=[%s], takes %s ms, size=%s", MemoryUsage.humanSizeOf(dicSet), (endPoint - startPoint), dicSet.size()), this); } catch (Exception ex) { Logger.logger.error("read pinyin dic error.", ex); throw new RuntimeException("read pinyin dic error.", ex); } finally { try { if (reader != null) { reader.close(); } } catch (Exception ex) { //ignore ex } } }
#vulnerable code private void initialize() { InputStream in = PinyinDic.class.getResourceAsStream(dicLocation); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); try { String line = null; long startPoint = System.currentTimeMillis(); while (null != (line = reader.readLine())) { if (StringUtils.isNotBlank(line)) { dicSet.add(line); } } long endPoint = System.currentTimeMillis(); Logger.logger.info(String.format("Load pinyin from pinyin.dic, sizeof dic=[%s], takes %s ms, size=%s", MemoryUsage.humanSizeOf(dicSet), (endPoint - startPoint), dicSet.size()), this); } catch (Exception ex) { Logger.logger.error("read pinyin dic error.", ex); throw new RuntimeException("read pinyin dic error.", ex); } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFindCardsId() { Card c1 = cardService.createCard("card1", col1.getId(), new Date(), user); Card c2 = cardService.createCard("card2", col1.getId(), new Date(), user); Card c3 = cardService.createCard("card3", col1.getId(), new Date(), user); Map<String, Integer> res = cardRepository.findCardsIds(Arrays.asList("TESTBRD-" + c1.getSequence(), "TESTBRD-" + c2.getSequence(), "TESTBRD-" + c3.getSequence())); Assert.assertEquals(res.get("TESTBRD-" + c1.getSequence()).intValue(), c1.getId()); Assert.assertEquals(res.get("TESTBRD-" + c2.getSequence()).intValue(), c2.getId()); Assert.assertEquals(res.get("TESTBRD-" + c3.getSequence()).intValue(), c3.getId()); }
#vulnerable code @Test public void testFindCardsId() { Card c1 = cardService.createCard("card1", col1.getId(), new Date(), user); Card c2 = cardService.createCard("card2", col1.getId(), new Date(), user); Card c3 = cardService.createCard("card3", col1.getId(), new Date(), user); Map<String, Integer> res = cardRepository.findCardsIds(Arrays.asList("TEST-BRD-" + c1.getSequence(), "TEST-BRD-" + c2.getSequence(), "TEST-BRD-" + c3.getSequence())); Assert.assertEquals(res.get("TEST-BRD-" + c1.getSequence()).intValue(), c1.getId()); Assert.assertEquals(res.get("TEST-BRD-" + c2.getSequence()).intValue(), c2.getId()); Assert.assertEquals(res.get("TEST-BRD-" + c3.getSequence()).intValue(), c3.getId()); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. } }
#vulnerable code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; if (Lizzie.leelaz.isKataGo) { history.getData().scoreMean = stats.maxScoreMean; } // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void clear() { initialize(); }
#vulnerable code public void clear() { while (previousMove()); history.clear(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void ponder() { isPondering = true; startPonderTime = System.currentTimeMillis(); if (Lizzie.board.isAvoding && Lizzie.board.isKeepingAvoid && !isKataGo) analyzeAvoid( "avoid b " + Lizzie.board.avoidCoords + " " + Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations") + " avoid w " + Lizzie.board.avoidCoords + " " + Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations")); else sendCommand( (this.isKataGo ? "kata-analyze " : "lz-analyze ") + Lizzie.config .config .getJSONObject("leelaz") .getInt("analyze-update-interval-centisec") + (this.isKataGo && Lizzie.config.showKataGoEstimate ? " ownership true" : "")); // until it responds to this, incoming // ponder results are obsolete }
#vulnerable code public void ponder() { isPondering = true; startPonderTime = System.currentTimeMillis(); if (Lizzie.board.isAvoding && Lizzie.board.isKeepingAvoid && !isKataGo) analyzeAvoid( "avoid", Lizzie.board.getHistory().isBlacksTurn() ? "w" : "b", Lizzie.board.avoidCoords, +Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations")); else sendCommand( (this.isKataGo ? "kata-analyze " : "lz-analyze ") + Lizzie.config .config .getJSONObject("leelaz") .getInt("analyze-update-interval-centisec") + (this.isKataGo && Lizzie.config.showKataGoEstimate ? " ownership true" : "")); // until it responds to this, incoming // ponder results are obsolete } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void sendCommand(String command) { command = cmdNumber + " " + command; cmdNumber++; if (printCommunication) { System.out.printf("> %s\n", command); } if (command.startsWith("fixed_handicap")) isSettingHandicap = true; try { outputStream.write((command + "\n").getBytes()); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } }
#vulnerable code public void sendCommand(String command) { if (printCommunication) { System.out.printf("> %s\n", command); } if (command.startsWith("fixed_handicap")) isSettingHandicap = true; if (command.startsWith("genmove")) isThinking = true; try { outputStream.write((command + "\n").getBytes()); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static boolean parse(String value) { // Drop anything outside "(;...)" final Pattern SGF_PATTERN = Pattern.compile("(?s).*?(\\(\\s*;{0,1}.*\\))(?s).*?"); Matcher sgfMatcher = SGF_PATTERN.matcher(value); if (sgfMatcher.matches()) { value = sgfMatcher.group(1); } else { return false; } // Determine the SZ property Pattern szPattern = Pattern.compile("(?s).*?SZ\\[([\\d:]+)\\](?s).*"); Matcher szMatcher = szPattern.matcher(value); int boardWidth = 19; int boardHeight = 19; if (szMatcher.matches()) { String sizeStr = szMatcher.group(1); Pattern sizePattern = Pattern.compile("([\\d]+):([\\d]+)"); Matcher sizeMatcher = sizePattern.matcher(sizeStr); if (sizeMatcher.matches()) { Lizzie.board.reopen( Integer.parseInt(sizeMatcher.group(1)), Integer.parseInt(sizeMatcher.group(2))); } else { int boardSize = Integer.parseInt(sizeStr); Lizzie.board.reopen(boardSize, boardSize); } } else { Lizzie.board.reopen(boardWidth, boardHeight); } parseValue(value, null, false); return true; }
#vulnerable code private static boolean parse(String value) { // Drop anything outside "(;...)" final Pattern SGF_PATTERN = Pattern.compile("(?s).*?(\\(\\s*;.*\\)).*?"); Matcher sgfMatcher = SGF_PATTERN.matcher(value); if (sgfMatcher.matches()) { value = sgfMatcher.group(1); } else { return false; } // Determine the SZ property Pattern szPattern = Pattern.compile("(?s).*?SZ\\[([\\d:]+)\\](?s).*"); Matcher szMatcher = szPattern.matcher(value); if (szMatcher.matches()) { String sizeStr = szMatcher.group(1); Pattern sizePattern = Pattern.compile("([\\d]+):([\\d]+)"); Matcher sizeMatcher = sizePattern.matcher(sizeStr); if (sizeMatcher.matches()) { Lizzie.board.reopen( Integer.parseInt(sizeMatcher.group(1)), Integer.parseInt(sizeMatcher.group(2))); } else { int boardSize = Integer.parseInt(sizeStr); Lizzie.board.reopen(boardSize, boardSize); } } else { Lizzie.board.reopen(19, 19); } int subTreeDepth = 0; // Save the variation step count Map<Integer, Integer> subTreeStepMap = new HashMap<Integer, Integer>(); // Comment of the game head String headComment = ""; // Game properties Map<String, String> gameProperties = new HashMap<String, String>(); Map<String, String> pendingProps = new HashMap<String, String>(); boolean inTag = false, isMultiGo = false, escaping = false, moveStart = false, addPassForMove = true; boolean inProp = false; String tag = ""; StringBuilder tagBuilder = new StringBuilder(); StringBuilder tagContentBuilder = new StringBuilder(); // MultiGo 's branch: (Main Branch (Main Branch) (Branch) ) // Other 's branch: (Main Branch (Branch) Main Branch) if (value.matches("(?s).*\\)\\s*\\)")) { isMultiGo = true; } String blackPlayer = "", whitePlayer = ""; // Support unicode characters (UTF-8) for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (escaping) { // Any char following "\" is inserted verbatim // (ref) "3.2. Text" in https://www.red-bean.com/sgf/sgf4.html tagContentBuilder.append(c == 'n' ? "\n" : c); escaping = false; continue; } switch (c) { case '(': if (!inTag) { subTreeDepth += 1; // Initialize the step count subTreeStepMap.put(subTreeDepth, 0); addPassForMove = true; pendingProps = new HashMap<String, String>(); } else { if (i > 0) { // Allow the comment tag includes '(' tagContentBuilder.append(c); } } break; case ')': if (!inTag) { if (isMultiGo) { // Restore to the variation node int varStep = subTreeStepMap.get(subTreeDepth); for (int s = 0; s < varStep; s++) { Lizzie.board.previousMove(); } } subTreeDepth -= 1; } else { // Allow the comment tag includes '(' tagContentBuilder.append(c); } break; case '[': if (!inProp) { inProp = true; if (subTreeDepth > 1 && !isMultiGo) { break; } inTag = true; String tagTemp = tagBuilder.toString(); if (!tagTemp.isEmpty()) { // Ignore small letters in tags for the long format Smart-Go file. // (ex) "PlayerBlack" ==> "PB" // It is the default format of mgt, an old SGF tool. // (Mgt is still supported in Debian and Ubuntu.) tag = tagTemp.replaceAll("[a-z]", ""); } tagContentBuilder = new StringBuilder(); } else { tagContentBuilder.append(c); } break; case ']': if (subTreeDepth > 1 && !isMultiGo) { break; } inTag = false; inProp = false; tagBuilder = new StringBuilder(); String tagContent = tagContentBuilder.toString(); // We got tag, we can parse this tag now. if (tag.equals("B") || tag.equals("W")) { moveStart = true; addPassForMove = true; int[] move = convertSgfPosToCoord(tagContent); // Save the step count subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1); Stone color = tag.equals("B") ? Stone.BLACK : Stone.WHITE; boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1); if (move == null) { Lizzie.board.pass(color, newBranch, false); } else { Lizzie.board.place(move[0], move[1], color, newBranch); } if (newBranch) { processPendingPros(Lizzie.board.getHistory(), pendingProps); } } else if (tag.equals("C")) { // Support comment if (!moveStart) { headComment = tagContent; } else { Lizzie.board.comment(tagContent); } } else if (tag.equals("LZ") && Lizzie.config.holdBestMovesToSgf) { // Content contains data for Lizzie to read String[] lines = tagContent.split("\n"); String[] line1 = lines[0].split(" "); String line2 = ""; if (lines.length > 1) { line2 = lines[1]; } String versionNumber = line1[0]; Lizzie.board.getData().winrate = 100 - Double.parseDouble(line1[1]); int numPlayouts = Integer.parseInt( line1[2] .replaceAll("k", "000") .replaceAll("m", "000000") .replaceAll("[^0-9]", "")); Lizzie.board.getData().setPlayouts(numPlayouts); if (numPlayouts > 0 && !line2.isEmpty()) { Lizzie.board.getData().bestMoves = Lizzie.leelaz.parseInfo(line2); } } else if (tag.equals("AB") || tag.equals("AW")) { int[] move = convertSgfPosToCoord(tagContent); Stone color = tag.equals("AB") ? Stone.BLACK : Stone.WHITE; if (moveStart) { // add to node properties Lizzie.board.addNodeProperty(tag, tagContent); if (addPassForMove) { // Save the step count subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1); boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1); Lizzie.board.pass(color, newBranch, true); if (newBranch) { processPendingPros(Lizzie.board.getHistory(), pendingProps); } addPassForMove = false; } Lizzie.board.addNodeProperty(tag, tagContent); if (move != null) { Lizzie.board.addStone(move[0], move[1], color); } } else { if (move == null) { Lizzie.board.pass(color); } else { Lizzie.board.place(move[0], move[1], color); } Lizzie.board.flatten(); } } else if (tag.equals("PB")) { blackPlayer = tagContent; } else if (tag.equals("PW")) { whitePlayer = tagContent; } else if (tag.equals("KM")) { try { if (tagContent.trim().isEmpty()) { tagContent = "0.0"; } Lizzie.board.setKomi(Double.parseDouble(tagContent)); } catch (NumberFormatException e) { e.printStackTrace(); } } else { if (moveStart) { // Other SGF node properties if ("AE".equals(tag)) { // remove a stone if (addPassForMove) { // Save the step count subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1); Stone color = Lizzie.board.getHistory().getLastMoveColor() == Stone.WHITE ? Stone.BLACK : Stone.WHITE; boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1); Lizzie.board.pass(color, newBranch, true); if (newBranch) { processPendingPros(Lizzie.board.getHistory(), pendingProps); } addPassForMove = false; } Lizzie.board.addNodeProperty(tag, tagContent); int[] move = convertSgfPosToCoord(tagContent); if (move != null) { Lizzie.board.removeStone( move[0], move[1], tag.equals("AB") ? Stone.BLACK : Stone.WHITE); } } else { boolean firstProp = (subTreeStepMap.get(subTreeDepth) == 0); if (firstProp) { addProperty(pendingProps, tag, tagContent); } else { Lizzie.board.addNodeProperty(tag, tagContent); } } } else { addProperty(gameProperties, tag, tagContent); } } break; case ';': break; default: if (subTreeDepth > 1 && !isMultiGo) { break; } if (inTag) { if (c == '\\') { escaping = true; continue; } tagContentBuilder.append(c); } else { if (c != '\n' && c != '\r' && c != '\t' && c != ' ') { tagBuilder.append(c); } } } } Lizzie.frame.setPlayers(whitePlayer, blackPlayer); // Rewind to game start while (Lizzie.board.previousMove()) ; // Set AW/AB Comment if (!headComment.isEmpty()) { Lizzie.board.comment(headComment); Lizzie.frame.refresh(); } if (gameProperties.size() > 0) { Lizzie.board.addNodeProperties(gameProperties); } return true; } #location 128 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. } }
#vulnerable code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. if (!Lizzie.config.holdWinrateToMove) { history.getData().setPlayouts(stats.totalPlayouts); } } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void reopen(int size) { size = (size >= 2) ? size : 19; if (size != boardSize) { boardSize = size; Zobrist.init(); clear(); Lizzie.leelaz.sendCommand("boardsize " + boardSize); forceRefresh = true; } }
#vulnerable code public void reopen(int size) { size = (size == 13 || size == 9) ? size : 19; if (size != boardSize) { boardSize = size; initialize(); forceRefresh = true; } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. } }
#vulnerable code public void updateWinrate() { Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats(); if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) { history.getData().winrate = stats.maxWinrate; // we won't set playouts here. but setting winrate is ok... it shows the user that we are // computing. i think its fine. if (!Lizzie.config.holdWinrateToMove) { history.getData().setPlayouts(stats.totalPlayouts); } } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetPropertyType() throws Exception { assertThat(TypeUtil.getPropertyType(A.class, "b.i", "1").equals(Integer.class), equalTo(true)); assertThat(TypeUtil.getPropertyType(A.class, "s", "2").equals(String.class), equalTo(true)); TypeUtil.getPropertyType(A.class, "b.j", "3"); }
#vulnerable code @Test public void testGetPropertyType() throws Exception { assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true)); assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true)); } #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 executeDDL(Object test, String[] sqls) { try { executeSql(CONNECTION_TABLE.get(test), sqls); } catch (SQLException e) { throw new RuntimeException(e); } }
#vulnerable code public static void executeDDL(Object test, String[] sqls) { Connection connection = CONNECTION_TABLE.get(test); try { Statement statement = connection.createStatement(); for (int i = 0; i < sqls.length; i++) { statement.execute(sqls[i]); } connection.commit(); statement.close(); } catch (SQLException e) { throw new RuntimeException(e); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected Properties getProperties() { if (propertyFile!=null) { Properties properties = new Properties(); // TODO: should we "inherit" from the ant projects properties ? FileInputStream is = null; try { is = new FileInputStream(propertyFile); properties.load(is); return properties; } catch (FileNotFoundException e) { throw new BuildException(propertyFile + " not found.",e); } catch (IOException e) { throw new BuildException("Problem while loading " + propertyFile,e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } else { return null; } }
#vulnerable code protected Properties getProperties() { if (propertyFile!=null) { Properties properties = new Properties(); // TODO: should we "inherit" from the ant projects properties ? try { properties.load(new FileInputStream(propertyFile) ); return properties; } catch (FileNotFoundException e) { throw new BuildException(propertyFile + " not found.",e); } catch (IOException e) { throw new BuildException("Problem while loading " + propertyFile,e); } } else { return null; } } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void refreshTreeData() { Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values(); for (ZkCluster zkCluster : zkClusters) { InitRegistryCenterService.initTreeJson(zkCluster.getRegCenterConfList(), zkCluster.getZkAddr()); } }
#vulnerable code private void refreshTreeData() { Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values(); for (ZkCluster zkCluster : zkClusters) { InitRegistryCenterService.initTreeJson(REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr()), zkCluster.getZkAddr()); } } #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 zip(List<File> runtimeLibFiles, File saturnContainerDir, File zipFile) throws IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); /* for(File file : saturnContainerDir.listFiles()) { zip(file, "saturn", zos); }*/ for(File file : runtimeLibFiles) { zip(file, "app"+fileSeparator+"lib", zos); } zos.close(); }
#vulnerable code public static void zip(List<File> runtimeLibFiles, File saturnContainerDir, File zipFile) throws IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile)); for(File file : saturnContainerDir.listFiles()) { zip(file, "saturn", zos); } for(File file : runtimeLibFiles) { zip(file, "app"+fileSeparator+"lib", zos); } zos.close(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String[] getItemsPaths(String executorName, String jobName) { String jobNamePath = String.format(EXECUTINGJOBPATH, executorName, jobName); File jobNameFile = new File(jobNamePath); if (!jobNameFile.exists() || jobNameFile.isFile()) { return new String[0]; } File[] files = jobNameFile.listFiles(); if(files == null || files.length == 0){ return new String[]{}; } String[] filePaths = new String[files.length]; int i=0; for(File file:files){ filePaths[i++] = file.getAbsolutePath(); } return filePaths; }
#vulnerable code public static String[] getItemsPaths(String executorName, String jobName) { String jobNamePath = String.format(EXECUTINGJOBPATH, executorName, jobName); File jobNameFile = new File(jobNamePath); if (!jobNameFile.exists() || jobNameFile.isFile()) { return new String[0]; } File[] files = jobNameFile.listFiles(); if(files.length == 0){ return new String[]{}; } String[] filePaths = new String[files.length]; int i=0; for(File file:files){ filePaths[i++] = file.getAbsolutePath(); } return filePaths; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void init() { if (zkConfig.isUseNestedZookeeper()) { NestedZookeeperServers.getInstance().startServerIfNotStarted(zkConfig.getNestedPort(), zkConfig.getNestedDataDir()); } log.info("msg=Saturn job: zookeeper registry center init, server lists is: {}.", zkConfig.getServerLists()); Builder builder = CuratorFrameworkFactory.builder() .connectString(zkConfig.getServerLists()) .sessionTimeoutMs(SESSION_TIMEOUT) .connectionTimeoutMs(CONNECTION_TIMEOUT) .retryPolicy(new ExponentialBackoffRetry(zkConfig.getBaseSleepTimeMilliseconds(), zkConfig.getMaxRetries(), zkConfig.getMaxSleepTimeMilliseconds())) .namespace(zkConfig.getNamespace()); if (0 != zkConfig.getSessionTimeoutMilliseconds()) { builder.sessionTimeoutMs(zkConfig.getSessionTimeoutMilliseconds()); sessionTimeout = zkConfig.getSessionTimeoutMilliseconds(); } if (0 != zkConfig.getConnectionTimeoutMilliseconds()) { builder.connectionTimeoutMs(zkConfig.getConnectionTimeoutMilliseconds()); } if (!Strings.isNullOrEmpty(zkConfig.getDigest())) { builder.authorization("digest", zkConfig.getDigest().getBytes(Charset.forName("UTF-8"))) .aclProvider(new ACLProvider() { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(final String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } }); } client = builder.build(); client.start(); try { client.getZookeeperClient().blockUntilConnectedOrTimedOut(); if (!client.getZookeeperClient().isConnected()) { throw new Exception("the zk client is not connected"); } client.checkExists().forPath(SLASH_CONSTNAT + zkConfig.getNamespace()); // check namespace node by using client, for UnknownHostException of connection string. //CHECKSTYLE:OFF } catch (final Exception ex) { throw new RuntimeException("zk connect fail, zkList is " + zkConfig.getServerLists(),ex); } // start monitor. if (zkConfig.getMonitorPort() > 0) { monitorService = new MonitorService(this, zkConfig.getMonitorPort()); monitorService.listen(); log.info("msg=zk monitor port starts at {}. usage: telnet {jobServerIP} {} and execute dump {jobName}", zkConfig.getMonitorPort(), zkConfig.getMonitorPort()); } }
#vulnerable code @Override public void init() { if (zkConfig.isUseNestedZookeeper()) { NestedZookeeperServers.getInstance().startServerIfNotStarted(zkConfig.getNestedPort(), zkConfig.getNestedDataDir()); } log.info("msg=Saturn job: zookeeper registry center init, server lists is: {}.", zkConfig.getServerLists()); Builder builder = CuratorFrameworkFactory.builder() .connectString(zkConfig.getServerLists()) .sessionTimeoutMs(SESSION_TIMEOUT) .connectionTimeoutMs(CONNECTION_TIMEOUT) .retryPolicy(new ExponentialBackoffRetry(zkConfig.getBaseSleepTimeMilliseconds(), zkConfig.getMaxRetries(), zkConfig.getMaxSleepTimeMilliseconds())) .namespace(zkConfig.getNamespace()); if (0 != zkConfig.getSessionTimeoutMilliseconds()) { builder.sessionTimeoutMs(zkConfig.getSessionTimeoutMilliseconds()); sessionTimeout = zkConfig.getSessionTimeoutMilliseconds(); } if (0 != zkConfig.getConnectionTimeoutMilliseconds()) { builder.connectionTimeoutMs(zkConfig.getConnectionTimeoutMilliseconds()); } if (!Strings.isNullOrEmpty(zkConfig.getDigest())) { builder.authorization("digest", zkConfig.getDigest().getBytes(Charset.forName("UTF-8"))) .aclProvider(new ACLProvider() { @Override public List<ACL> getDefaultAcl() { return ZooDefs.Ids.CREATOR_ALL_ACL; } @Override public List<ACL> getAclForPath(final String path) { return ZooDefs.Ids.CREATOR_ALL_ACL; } }); } client = builder.build(); client.start(); try { client.getZookeeperClient().blockUntilConnectedOrTimedOut(); if (!client.getZookeeperClient().isConnected()) { throw new Exception("the zk client is not connected"); } client.checkExists().forPath(SLASH_CONSTNAT + zkConfig.getNamespace()); // check namespace node by using client, for UnknownHostException of connection string. //CHECKSTYLE:OFF } catch (final Exception ex) { throw new RuntimeException("zk connect fail, zkList is " + zkConfig.getServerLists(),ex); } // start monitor. if (zkConfig.getMonitorPort() > 0) { MonitorService monitorService = new MonitorService(this, zkConfig.getMonitorPort()); monitorService.listen(); log.info("msg=zk monitor port starts at {}. usage: telnet {jobServerIP} {} and execute dump {jobName}", zkConfig.getMonitorPort(), zkConfig.getMonitorPort()); } } #location 51 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public <T> Cursor<T> queryForCursor(Query query, final Class<T> clazz) { return new DelegatingCursor<T>(queryParsers.getForClass(query.getClass()).constructSolrQuery(query)) { @Override protected org.springframework.data.solr.core.query.result.DelegatingCursor.PartialResult<T> doLoad( SolrQuery nativeQuery) { QueryResponse response = executeSolrQuery(nativeQuery, getSolrRequestMethod(getDefaultRequestMethod())); if (response == null) { return new PartialResult<T>("", Collections.<T> emptyList()); } return new PartialResult<T>(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz)); } }.open(); }
#vulnerable code public <T> Cursor<T> queryForCursor(Query query, final Class<T> clazz) { return new DelegatingCursor<T>(queryParsers.getForClass(query.getClass()).constructSolrQuery(query)) { @Override protected org.springframework.data.solr.core.query.result.DelegatingCursor.PartialResult<T> doLoad( SolrQuery nativeQuery) { QueryResponse response = executeSolrQuery(nativeQuery); if (response == null) { return new PartialResult<T>("", Collections.<T> emptyList()); } return new PartialResult<T>(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz)); } }.open(); } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T> T createFor(final Class<T> protocol, final Actor actor, final Mailbox mailbox) { final T maybeCachedProxy = actor.lifeCycle.environment.lookUpProxy(protocol); if (maybeCachedProxy != null) { return maybeCachedProxy; } final String proxyClassname = fullyQualifiedClassnameFor(protocol, "__Proxy"); T newProxy; try { newProxy = tryCreate(protocol, actor, mailbox, proxyClassname); } catch (Exception e) { synchronized (protocol) { newProxy = tryGenerateCreate(protocol, actor, mailbox, proxyClassname); } } actor.lifeCycle.environment.cacheProxy(newProxy); return newProxy; }
#vulnerable code public static <T> T createFor(final Class<T> protocol, final Actor actor, final Mailbox mailbox) { final T maybeCachedProxy = actor.lifeCycle.environment.lookUpProxy(protocol); if (maybeCachedProxy != null) { return maybeCachedProxy; } final String proxyClassname = fullyQualifiedClassnameFor(protocol, "__Proxy"); final T maybeProxy = tryProxyFor(proxyClassname, actor, mailbox); if (maybeProxy != null) { actor.lifeCycle.environment.cacheProxy(maybeProxy); return maybeProxy; } synchronized (protocol) { T newProxy; try { newProxy = tryCreate(protocol, actor, mailbox, proxyClassname); } catch (Exception e) { newProxy = tryGenerateCreate(protocol, actor, mailbox, proxyClassname); } actor.lifeCycle.environment.cacheProxy(newProxy); return newProxy; } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void deliver() { if (actor.lifeCycle.isResuming()) { if (isStowed()) { internalDeliver(this); } else { internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this)); } actor.lifeCycle.nextResuming(); } else if (actor.isDispersing()) { internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this)); } else { internalDeliver(this); } }
#vulnerable code @Override public void deliver() { if (actor.__internal__IsResumed()) { if (isStowed()) { internalDeliver(this); } else { internalDeliver(actor.__internal__Environment().suspended.swapWith(this)); } actor.__internal__NextResuming(); } else if (actor.isDispersing()) { internalDeliver(actor.__internal__Environment().stowage.swapWith(this)); } else { internalDeliver(this); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testProxy() throws Exception { int frontendPort = Utils.findOpenPort(); int backendPort = Utils.findOpenPort(); Context ctx = ZMQ.context(1); assert (ctx != null); Main mt = new Main(ctx, frontendPort, backendPort); mt.start(); new Dealer(ctx, "AA", backendPort).start(); new Dealer(ctx, "BB", backendPort).start(); Thread.sleep(1000); Thread c1 = new Client(ctx, "X", frontendPort); c1.start(); Thread c2 = new Client(ctx, "Y", frontendPort); c2.start(); c1.join(); c2.join(); ctx.term(); }
#vulnerable code @Test public void testProxy() throws Exception { Context ctx = ZMQ.context(1); assert (ctx != null); Main mt = new Main(ctx); mt.start(); new Dealer(ctx, "AA").start(); new Dealer(ctx, "BB").start(); Thread.sleep(1000); Thread c1 = new Client(ctx, "X"); c1.start(); Thread c2 = new Client(ctx, "Y"); c2.start(); c1.join(); c2.join(); ctx.term(); } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected boolean xsend(Msg msg_) { // If this is the first part of the message it's the ID of the // peer to send the message to. if (!more_out) { assert (current_out == null); // If we have malformed message (prefix with no subsequent message) // then just silently ignore it. // TODO: The connections should be killed instead. if (msg_.has_more()) { more_out = true; // Find the pipe associated with the identity stored in the prefix. // If there's no such pipe just silently ignore the message, unless // mandatory is set. Blob identity = Blob.createBlob(msg_.data(), true); Outpipe op = outpipes.get(identity); if (op != null) { current_out = op.pipe; if (!current_out.check_write ()) { op.active = false; current_out = null; if (mandatory) { more_out = false; errno.set(ZError.EAGAIN); return false; } } } else if (mandatory) { more_out = false; errno.set(ZError.EHOSTUNREACH); return false; } } return true; } // Check whether this is the last part of the message. more_out = msg_.has_more(); // Push the message into the pipe. If there's no out pipe, just drop it. if (current_out != null) { boolean ok = current_out.write (msg_); if (!ok) current_out = null; else if (!more_out) { current_out.flush (); current_out = null; } } return true; }
#vulnerable code @Override protected boolean xsend(Msg msg_) { // If this is the first part of the message it's the ID of the // peer to send the message to. if (!more_out) { assert (current_out == null); // If we have malformed message (prefix with no subsequent message) // then just silently ignore it. // TODO: The connections should be killed instead. if (msg_.has_more()) { more_out = true; // Find the pipe associated with the identity stored in the prefix. // If there's no such pipe just silently ignore the message, unless // mandatory is set. Blob identity = new Blob(msg_.data()); Outpipe op = outpipes.get(identity); if (op != null) { current_out = op.pipe; if (!current_out.check_write ()) { op.active = false; current_out = null; if (mandatory) { more_out = false; errno.set(ZError.EAGAIN); return false; } } } else if (mandatory) { more_out = false; errno.set(ZError.EHOSTUNREACH); return false; } } return true; } // Check whether this is the last part of the message. more_out = msg_.has_more(); // Push the message into the pipe. If there's no out pipe, just drop it. if (current_out != null) { boolean ok = current_out.write (msg_); if (!ok) current_out = null; else if (!more_out) { current_out.flush (); current_out = null; } } return true; } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public int start () { int rc = 0; timers.addAll(newTimers); newTimers.clear(); // Recalculate all timers now for (STimer timer: timers) { timer.when = timer.delay + System.currentTimeMillis(); } Selector selector; try { selector = Selector.open(); } catch (IOException e) { System.err.println (e.getMessage()); return -1; } // Main reactor loop while (!Thread.currentThread().isInterrupted()) { if (dirty) { // If s_rebuild_pollset() fails, break out of the loop and // return its error rebuild (); } long wait = ticklessTimer(); rc = zmq.ZMQ.zmq_poll (selector, pollset, wait); if (rc == -1) { if (verbose) System.out.println("I: zloop: interrupted"); rc = 0; break; // Context has been shut down } // Handle any timers that have now expired Iterator<STimer> it = timers.iterator(); while (it.hasNext()) { STimer timer = it.next(); if (System.currentTimeMillis() >= timer.when && timer.when != -1) { if (verbose) System.out.println ("I: zloop: call timer handler"); rc = timer.handler.handle(this, null, timer.arg); if (rc == -1) break; // Timer handler signalled break if (timer.times != 0 && --timer.times == 0) { it.remove(); } else timer.when = timer.delay + System.currentTimeMillis(); } } if (rc == -1) break; // Some timer signalled break from the reactor loop // Handle any pollers that are ready for (int item_nbr = 0; item_nbr < poll_size; item_nbr++) { SPoller poller = pollact [item_nbr]; assert (pollset [item_nbr].getSocket() == poller.item.getSocket()); if (pollset [item_nbr].isError()) { if (verbose) System.out.printf ("I: zloop: can't poll %s socket (%s, %s)", poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD", poller.item.getSocket(), poller.item.getChannel()); // Give handler one chance to handle error, then kill // poller because it'll disrupt the reactor otherwise. if (poller.errors++ > 0) { pollerEnd (poller.item); } } else poller.errors = 0; // A non-error happened if (pollset [item_nbr].readyOps() > 0) { if (verbose) System.out.printf ("I: zloop: call %s socket handler (%s, %s)\n", poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD", poller.item.getSocket(), poller.item.getChannel()); rc = poller.handler.handle (this, poller.item, poller.arg); if (rc == -1) break; // Poller handler signalled break } } // Now handle any timer zombies // This is going to be slow if we have many zombies for (Object arg: zombies) { it = timers.iterator(); while (it.hasNext()) { STimer timer = it.next(); if (timer.arg == arg) { it.remove(); } } } // Now handle any new timers added inside the loop timers.addAll(newTimers); newTimers.clear(); if (rc == -1) break; } try { selector.close(); } catch (IOException e) { } return rc; }
#vulnerable code public int start () { int rc = 0; timers.addAll(newTimers); newTimers.clear(); // Recalculate all timers now for (STimer timer: timers) { timer.when = timer.delay + System.currentTimeMillis(); } Selector selector; try { selector = Selector.open(); } catch (IOException e) { System.err.println (e.getMessage()); return -1; } // Main reactor loop while (!Thread.currentThread().isInterrupted()) { if (dirty) { // If s_rebuild_pollset() fails, break out of the loop and // return its error rebuild (); } long wait = ticklessTimer(); rc = zmq.ZMQ.zmq_poll (selector, pollset, wait); if (rc == -1) { if (verbose) System.out.printf ("I: zloop: interrupted\n", rc); rc = 0; break; // Context has been shut down } // Handle any timers that have now expired Iterator<STimer> it = timers.iterator(); while (it.hasNext()) { STimer timer = it.next(); if (System.currentTimeMillis() >= timer.when && timer.when != -1) { if (verbose) System.out.println ("I: zloop: call timer handler"); rc = timer.handler.handle(this, null, timer.arg); if (rc == -1) break; // Timer handler signalled break if (timer.times != 0 && --timer.times == 0) { it.remove(); } else timer.when = timer.delay + System.currentTimeMillis(); } } if (rc == -1) break; // Some timer signalled break from the reactor loop // Handle any pollers that are ready for (int item_nbr = 0; item_nbr < poll_size; item_nbr++) { SPoller poller = pollact [item_nbr]; assert (pollset [item_nbr].getSocket() == poller.item.getSocket()); if (pollset [item_nbr].isError()) { if (verbose) System.out.printf ("I: zloop: can't poll %s socket (%s, %s)", poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD", poller.item.getSocket(), poller.item.getChannel()); // Give handler one chance to handle error, then kill // poller because it'll disrupt the reactor otherwise. if (poller.errors++ > 0) { pollerEnd (poller.item); } } else poller.errors = 0; // A non-error happened if (pollset [item_nbr].readyOps() > 0) { if (verbose) System.out.printf ("I: zloop: call %s socket handler (%s, %s)\n", poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD", poller.item.getSocket(), poller.item.getChannel()); rc = poller.handler.handle (this, poller.item, poller.arg); if (rc == -1) break; // Poller handler signalled break } } // Now handle any timer zombies // This is going to be slow if we have many zombies for (Object arg: zombies) { it = timers.iterator(); while (it.hasNext()) { STimer timer = it.next(); if (timer.arg == arg) { it.remove(); } } } // Now handle any new timers added inside the loop timers.addAll(newTimers); newTimers.clear(); if (rc == -1) break; } try { selector.close(); } catch (IOException e) { } return rc; } #location 32 #vulnerability type CHECKERS_PRINTF_ARGS
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Command recv (long timeout_) { Command cmd_ = null; // Try to get the command straight away. if (active) { cmd_ = cpipe.read (); if (cmd_ != null) { return cmd_; } // If there are no more commands available, switch into passive state. active = false; signaler.recv (); } // Wait for signal from the command sender. boolean rc = signaler.wait_event (timeout_); if (!rc) return null; // We've got the signal. Now we can switch into active state. active = true; // Get a command. cmd_ = cpipe.read (); assert (cmd_ != null); return cmd_; }
#vulnerable code public Command recv (long timeout_) { Command cmd_ = null; // Try to get the command straight away. if (active) { cmd_ = cpipe.read (); if (cmd_ != null) { return cmd_; } // If there are no more commands available, switch into passive state. active = false; signaler.recv (); } // Wait for signal from the command sender. boolean rc = signaler.wait_event (timeout_); if (!rc) return null; assert (rc); // We've got the signal. Now we can switch into active state. active = true; // Get a command. cmd_ = cpipe.read (); assert (cmd_ != null); return cmd_; } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main (String[] args) throws Exception { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } receiver.close (); subscriber.close (); context.term (); }
#vulnerable code public static void main (String[] args) throws Exception { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } subscriber.close (); context.term (); } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean identify_peer(Pipe pipe_) { Blob identity; Msg msg = pipe_.read(); if (msg == null) return false; if (msg.size () == 0) { // Fall back on the auto-generation ByteBuffer buf = ByteBuffer.allocate(5); buf.put((byte) 0); buf.putInt (next_peer_id++); identity = Blob.createBlob(buf.array(), false); } else { identity = Blob.createBlob(msg.data (), true); // Ignore peers with duplicate ID. if (outpipes.containsKey(identity)) return false; } pipe_.set_identity (identity); // Add the record into output pipes lookup table Outpipe outpipe = new Outpipe(pipe_, true); outpipes.put (identity, outpipe); return true; }
#vulnerable code private boolean identify_peer(Pipe pipe_) { Blob identity; Msg msg = pipe_.read(); if (msg == null) return false; if (msg.size () == 0) { // Fall back on the auto-generation ByteBuffer buf = ByteBuffer.allocate(5); buf.put((byte)0); buf.putInt (next_peer_id++); buf.flip(); identity = new Blob(buf); } else { identity = new Blob(msg.data ()); // Ignore peers with duplicate ID. if (outpipes.containsKey(identity)) return false; } pipe_.set_identity (identity); // Add the record into output pipes lookup table Outpipe outpipe = new Outpipe(pipe_, true); outpipes.put (identity, outpipe); return true; } #location 18 #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 { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } receiver.close (); subscriber.close (); context.term (); }
#vulnerable code public static void main (String[] args) throws Exception { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } subscriber.close (); context.term (); } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void destroySocket(Socket s) { if (s == null) { return; } s.setLinger(linger); s.close(); try { mutex.lock(); this.sockets.remove(s); } finally { mutex.unlock(); } }
#vulnerable code public void destroySocket(Socket s) { if (s == null) { return; } if (sockets.remove(s)) { s.setLinger(linger); s.close(); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout = 1000) public void testSocketDoubleClose() { Context ctx = ZMQ.context(1); Socket socket = ctx.socket(ZMQ.PUSH); socket.close(); socket.close(); ctx.term(); }
#vulnerable code @Test(timeout = 1000) public void testSocketDoubleClose() { Context ctx = ZMQ.context(1); Socket socket = ctx.socket(ZMQ.PUSH); socket.close(); socket.close(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testIssue476() throws InterruptedException, IOException, ExecutionException { final int front = Utils.findOpenPort(); final int back = Utils.findOpenPort(); final int max = 20; ExecutorService service = Executors.newFixedThreadPool(3); try (final ZContext ctx = new ZContext()) { service.submit(() -> { Thread.currentThread().setName("Proxy"); Socket xpub = ctx.createSocket(SocketType.XPUB); xpub.bind("tcp://*:" + back); Socket xsub = ctx.createSocket(SocketType.XSUB); xsub.bind("tcp://*:" + front); Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.bind("inproc://ctrl-proxy"); ZMQ.proxy(xpub, xsub, null, ctrl); }); final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx); ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.connect("inproc://ctrl-proxy"); ctrl.send(ZMQ.PROXY_TERMINATE); ctrl.close(); service.shutdown(); service.awaitTermination(2, TimeUnit.SECONDS); assertThat(error.get(), nullValue()); } }
#vulnerable code @Test public void testIssue476() throws InterruptedException, IOException, ExecutionException { final int front = Utils.findOpenPort(); final int back = Utils.findOpenPort(); final int max = 10; ExecutorService service = Executors.newFixedThreadPool(3); final ZContext ctx = new ZContext(); service.submit(new Runnable() { @Override public void run() { Thread.currentThread().setName("Proxy"); ZMQ.Socket xpub = ctx.createSocket(SocketType.XPUB); xpub.bind("tcp://*:" + back); ZMQ.Socket xsub = ctx.createSocket(SocketType.XSUB); xsub.bind("tcp://*:" + front); ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.bind("inproc://ctrl-proxy"); ZMQ.proxy(xpub, xsub, null, ctrl); } }); final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx); ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR); ctrl.connect("inproc://ctrl-proxy"); ctrl.send(ZMQ.PROXY_TERMINATE); ctrl.close(); service.shutdown(); service.awaitTermination(2, TimeUnit.SECONDS); assertThat(error.get(), nullValue()); ctx.close(); } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public byte[] receive(int flags) { final Msg msg = socketBase.recv(flags); if (msg == null) { return null; } return msg.data(); }
#vulnerable code public byte[] receive(int flags) { final Msg msg = socketBase.recv(flags); return msg.data(); } #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 Exception { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } receiver.close (); subscriber.close (); context.term (); }
#vulnerable code public static void main (String[] args) throws Exception { // Prepare our context and sockets ZMQ.Context context = ZMQ.context(1); // Connect to task ventilator ZMQ.Socket receiver = context.socket(ZMQ.PULL); receiver.connect("tcp://localhost:5557"); // Connect to weather server ZMQ.Socket subscriber = context.socket(ZMQ.SUB); subscriber.connect("tcp://localhost:5556"); subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET)); // Process messages from both sockets // We prioritize traffic from the task ventilator while (!Thread.currentThread ().isInterrupted ()) { // Process any waiting tasks byte[] task; while((task = receiver.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process task"); } // Process any waiting weather updates byte[] update; while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) { System.out.println("process weather update"); } // No activity, so sleep for 1 msec Thread.sleep(1000); } subscriber.close (); context.term (); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testHeartbeatTimeout() throws IOException, InterruptedException { testHeartbeatTimeout(false); }
#vulnerable code @Test public void testHeartbeatTimeout() throws IOException, InterruptedException { Ctx ctx = ZMQ.createContext(); assertThat(ctx, notNullValue()); SocketBase server = prepServerSocket(ctx, true, false); assertThat(server, notNullValue()); SocketBase monitor = ZMQ.socket(ctx, ZMQ.ZMQ_PAIR); boolean rc = monitor.connect("inproc://monitor"); assertThat(rc, is(true)); String endpoint = (String) ZMQ.getSocketOptionExt(server, ZMQ.ZMQ_LAST_ENDPOINT); assertThat(endpoint, notNullValue()); Socket socket = new Socket("127.0.0.1", TestUtils.port(endpoint)); // Mock a ZMTP 3 client so we can forcibly time out a connection mockHandshake(socket); // By now everything should report as connected ZMQ.Event event = ZMQ.Event.read(monitor); assertThat(event.event, is(ZMQ.ZMQ_EVENT_ACCEPTED)); // We should have been disconnected event = ZMQ.Event.read(monitor); assertThat(event.event, is(ZMQ.ZMQ_EVENT_DISCONNECTED)); socket.close(); ZMQ.close(monitor); ZMQ.close(server); ZMQ.term(ctx); } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void destroy() { for (Socket socket : sockets) { destroySocket(socket); } sockets.clear(); // Only terminate context if we are on the main thread if (isMain() && context != null) { context.term(); context = null; } }
#vulnerable code public void destroy() { for (Socket socket : sockets) { socket.setLinger(linger); socket.close(); } sockets.clear(); // Only terminate context if we are on the main thread if (isMain() && context != null) { context.term(); } synchronized (this) { context = null; } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testLastEndpoint() { // Create the infrastructure Ctx ctx = ZMQ.init(1); assertThat(ctx, notNullValue()); SocketBase sb = ZMQ.socket(ctx, ZMQ.ZMQ_ROUTER); assertThat(sb, notNullValue()); bindAndVerify(sb, "tcp://127.0.0.1:5560"); bindAndVerify(sb, "tcp://127.0.0.1:5561"); bindAndVerify(sb, "ipc:///tmp/testep" + UUID.randomUUID().toString()); sb.close(); ctx.terminate(); }
#vulnerable code @Test public void testLastEndpoint() { // Create the infrastructure Ctx ctx = ZMQ.init(1); assertThat(ctx, notNullValue()); SocketBase sb = ZMQ.socket(ctx, ZMQ.ZMQ_ROUTER); assertThat(sb, notNullValue()); bindAndVerify(sb, "tcp://127.0.0.1:5560"); bindAndVerify(sb, "tcp://127.0.0.1:5561"); bindAndVerify(sb, "ipc:///tmp/testep"); sb.close(); ctx.terminate(); } #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 test_streaming_changes() throws IOException { HttpResponse httpResponse = ResponseOnFileStub.newInstance(200, "changes/changes_full.json"); StreamingChangesResult changes = new StreamingChangesResult(new ObjectMapper(), httpResponse); int i = 0; for (DocumentChange documentChange : changes) { Assert.assertEquals(++i, documentChange.getSequence()); } Assert.assertEquals(5, changes.getLastSeq()); changes.close(); }
#vulnerable code @Test public void test_streaming_changes() throws IOException { HttpResponse httpResponse = ResponseOnFileStub.newInstance(200, "changes/changes_full.json"); StreamingChangesResult changes = new StreamingChangesResult(new ObjectMapper(), httpResponse); int i = 0; for (DocumentChange documentChange : changes) { Assert.assertEquals(++i, documentChange.getSequence()); } Assert.assertEquals(5, changes.getLastSeq()); } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void visit(final UpdateRequest request) { coapRequest = Request.newPut(); buildRequestSettings(); coapRequest.getOptions().setUriPath(request.getRegistrationId()); Long lifetime = request.getLifeTimeInSec(); if (lifetime != null) coapRequest.getOptions().addUriQuery("lt=" + lifetime); String smsNumber = request.getSmsNumber(); if (smsNumber != null) coapRequest.getOptions().addUriQuery("sms=" + smsNumber); BindingMode bindingMode = request.getBindingMode(); if (bindingMode != null) coapRequest.getOptions().addUriQuery("b=" + bindingMode.toString()); LinkObject[] linkObjects = request.getObjectLinks(); if (linkObjects != null) coapRequest.setPayload(LinkObject.serialyse(linkObjects)); }
#vulnerable code @Override public void visit(final UpdateRequest request) { coapRequest = Request.newPut(); buildRequestSettings(); coapRequest.getOptions().setUriPath(request.getRegistrationId()); Long lifetime = request.getLifeTimeInSec(); if (lifetime != null) coapRequest.getOptions().addUriQuery("lt=" + lifetime); String smsNumber = request.getSmsNumber(); if (smsNumber != null) coapRequest.getOptions().addUriQuery("sms=" + smsNumber); BindingMode bindingMode = request.getBindingMode(); if (bindingMode != null) coapRequest.getOptions().addUriQuery("b=" + bindingMode.toString()); LinkObject[] linkObjects = request.getObjectLinks(); if (linkObjects == null) coapRequest.setPayload(LinkObject.serialyse(linkObjects)); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void createPSKClient() { ObjectsInitializer initializer = new ObjectsInitializer(); initializer.setInstancesForObject(LwM2mId.SECURITY, Security.psk( "coaps://" + server.getSecuredAddress().getHostString() + ":" + server.getSecuredAddress().getPort(), 12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY)); initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false)); initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U")); List<LwM2mObjectEnabler> objects = initializer.createMandatory(); objects.add(initializer.create(2)); InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint()); builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort()); builder.setObjects(objects); client = builder.build(); }
#vulnerable code public void createPSKClient() { ObjectsInitializer initializer = new ObjectsInitializer(); initializer.setInstancesForObject(LwM2mId.SECURITY, Security.psk( "coaps://" + server.getSecureAddress().getHostString() + ":" + server.getSecureAddress().getPort(), 12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY)); initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false)); initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U")); List<LwM2mObjectEnabler> objects = initializer.createMandatory(); objects.add(initializer.create(2)); InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint()); builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort()); builder.setObjects(objects); client = builder.build(); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void fireResourcesChanged(int instanceid, int... resourceIds) { transactionalListener.resourceChanged(this, instanceid, resourceIds); }
#vulnerable code protected void fireResourcesChanged(int instanceid, int... resourceIds) { if (listener != null) { listener.resourceChanged(this, instanceid, resourceIds); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void register_with_invalid_request() throws InterruptedException, IOException { // Check registration helper.assertClientNotRegisterered(); // create a register request without the list of supported object Request coapRequest = new Request(Code.POST); coapRequest.setDestinationContext(new AddressEndpointContext(helper.server.getUnsecuredAddress())); coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode()); coapRequest.getOptions().addUriPath("rd"); coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier); // send request CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0)); coapEndpoint.start(); coapEndpoint.sendRequest(coapRequest); // check response Response response = coapRequest.waitForResponse(1000); assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST); coapEndpoint.stop(); }
#vulnerable code @Test public void register_with_invalid_request() throws InterruptedException, IOException { // Check registration helper.assertClientNotRegisterered(); // create a register request without the list of supported object Request coapRequest = new Request(Code.POST); coapRequest.setDestination(helper.server.getUnsecuredAddress().getAddress()); coapRequest.setDestinationPort(helper.server.getUnsecuredAddress().getPort()); coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode()); coapRequest.getOptions().addUriPath("rd"); coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier); // send request CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0)); coapEndpoint.start(); coapEndpoint.sendRequest(coapRequest); // check response Response response = coapRequest.waitForResponse(1000); assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST); coapEndpoint.stop(); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected BootstrapWriteResponse doWrite(ServerIdentity identity, BootstrapWriteRequest request) { LwM2mPath path = request.getPath(); // Manage Object case if (path.isObject()) { for (LwM2mObjectInstance instanceNode : ((LwM2mObject) request.getNode()).getInstances().values()) { LwM2mInstanceEnabler instanceEnabler = instances.get(instanceNode.getId()); if (instanceEnabler == null) { doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode)); } else { doWrite(identity, new WriteRequest(Mode.REPLACE, path.getObjectId(), instanceEnabler.getId(), instanceNode.getResources().values())); } } return BootstrapWriteResponse.success(); } // Manage Instance case if (path.isObjectInstance()) { LwM2mObjectInstance instanceNode = (LwM2mObjectInstance) request.getNode(); LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId()); if (instanceEnabler == null) { doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode)); } else { doWrite(identity, new WriteRequest(Mode.REPLACE, request.getContentFormat(), path.getObjectId(), path.getObjectInstanceId(), instanceNode.getResources().values())); } return BootstrapWriteResponse.success(); } // Manage resource case LwM2mResource resource = (LwM2mResource) request.getNode(); LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId()); if (instanceEnabler == null) { doCreate(identity, new CreateRequest(path.getObjectId(), new LwM2mObjectInstance(path.getObjectInstanceId(), resource))); } else { instanceEnabler.write(identity, path.getResourceId(), resource); } return BootstrapWriteResponse.success(); }
#vulnerable code @Override protected BootstrapWriteResponse doWrite(ServerIdentity identity, BootstrapWriteRequest request) { LwM2mPath path = request.getPath(); // Manage Object case if (path.isObject()) { for (LwM2mObjectInstance instanceNode : ((LwM2mObject) request.getNode()).getInstances().values()) { LwM2mInstanceEnabler instanceEnabler = instances.get(instanceNode.getId()); if (instanceEnabler == null) { doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode)); } else { doWrite(identity, new WriteRequest(Mode.REPLACE, path.getObjectId(), path.getObjectInstanceId(), instanceNode.getResources().values())); } } return BootstrapWriteResponse.success(); } // Manage Instance case if (path.isObjectInstance()) { LwM2mObjectInstance instanceNode = (LwM2mObjectInstance) request.getNode(); LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId()); if (instanceEnabler == null) { doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode)); } else { doWrite(identity, new WriteRequest(Mode.REPLACE, request.getContentFormat(), path.getObjectId(), path.getObjectInstanceId(), instanceNode.getResources().values())); } return BootstrapWriteResponse.success(); } // Manage resource case LwM2mResource resource = (LwM2mResource) request.getNode(); LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId()); if (instanceEnabler == null) { doCreate(identity, new CreateRequest(path.getObjectId(), new LwM2mObjectInstance(path.getObjectInstanceId(), resource))); } else { instanceEnabler.write(identity, path.getResourceId(), resource); } return BootstrapWriteResponse.success(); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) { final LwM2mPath path = request.getPath(); // Manage Object case if (path.isObject()) { List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>(); for (LwM2mInstanceEnabler instance : instances.values()) { ReadResponse response = instance.observe(identity); if (response.isSuccess()) { lwM2mObjectInstances.add((LwM2mObjectInstance) response.getContent()); } } return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances)); } // Manage Instance case final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId()); if (instance == null) return ObserveResponse.notFound(); if (path.getResourceId() == null) { return instance.observe(identity); } // Manage Resource case return instance.observe(identity, path.getResourceId()); }
#vulnerable code @Override protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) { final LwM2mPath path = request.getPath(); // Manage Object case if (path.isObject()) { List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>(); for (Entry<Integer, LwM2mInstanceEnabler> entry : instances.entrySet()) { lwM2mObjectInstances.add(getLwM2mObjectInstance(entry.getKey(), entry.getValue(), identity, true)); } return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances)); } // Manage Instance case final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId()); if (instance == null) return ObserveResponse.notFound(); if (path.getResourceId() == null) { return ObserveResponse .success(getLwM2mObjectInstance(path.getObjectInstanceId(), instance, identity, true)); } // Manage Resource case return instance.observe(identity, path.getResourceId()); } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void remove(byte[] token) { try (Jedis j = pool.getResource()) { byte[] tokenKey = toKey(OBS_TKN, token); // fetch the observation by token byte[] serializedObs = j.get(tokenKey); if (serializedObs == null) return; org.eclipse.californium.core.observe.Observation obs = deserializeObs(serializedObs); String registrationId = obs.getRequest().getUserContext().get(CoapRequestBuilder.CTX_REGID); Registration registration = getRegistration(j, registrationId); if (registration == null) { LOG.warn("Unable to remove observation {}, registration {} does not exist anymore", obs.getRequest(), registrationId); return; } String endpoint = registration.getEndpoint(); byte[] lockValue = null; byte[] lockKey = toKey(LOCK_EP, endpoint); try { lockValue = RedisLock.acquire(j, lockKey); unsafeRemoveObservation(j, registrationId, token); } finally { RedisLock.release(j, lockKey, lockValue); } } }
#vulnerable code @Override public void remove(byte[] token) { try (Jedis j = pool.getResource()) { byte[] tokenKey = toKey(OBS_TKN, token); // fetch the observation by token byte[] serializedObs = j.get(tokenKey); if (serializedObs == null) return; org.eclipse.californium.core.observe.Observation obs = deserializeObs(serializedObs); String registrationId = obs.getRequest().getUserContext().get(CoapRequestBuilder.CTX_REGID); Registration registration = getRegistration(j, registrationId); String endpoint = registration.getEndpoint(); byte[] lockValue = null; byte[] lockKey = toKey(LOCK_EP, endpoint); try { lockValue = RedisLock.acquire(j, lockKey); unsafeRemoveObservation(j, registrationId, token); } finally { RedisLock.release(j, lockKey, lockValue); } } } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void createRPKClient() { createRPKClient(false); }
#vulnerable code public void createRPKClient() { ObjectsInitializer initializer = new ObjectsInitializer(); initializer.setInstancesForObject(LwM2mId.SECURITY, Security.rpk( "coaps://" + server.getSecuredAddress().getHostString() + ":" + server.getSecuredAddress().getPort(), 12345, clientPublicKey.getEncoded(), clientPrivateKey.getEncoded(), serverPublicKey.getEncoded())); initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false)); initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U")); List<LwM2mObjectEnabler> objects = initializer.createMandatory(); objects.add(initializer.create(2)); InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0); DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress); // TODO we should read the config from the security object // TODO no way to provide a dynamic config with the current scandium API config.setIdentity(clientPrivateKey, clientPublicKey); CoapServer coapServer = new CoapServer(); CoapEndpoint.CoapEndpointBuilder coapBuilder = new CoapEndpoint.CoapEndpointBuilder(); coapBuilder.setConnector(new DTLSConnector(config.build())); coapBuilder.setNetworkConfig(new NetworkConfig()); coapServer.addEndpoint(coapBuilder.build()); LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint()); builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort()); builder.setObjects(objects); client = builder.build(); setupClientMonitoring(); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void createClient() { // Create Security Object (with bootstrap server only) String bsUrl = "coap://" + bootstrapServer.getUnsecuredAddress().getHostString() + ":" + bootstrapServer.getUnsecuredAddress().getPort(); Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345); createClient(security); }
#vulnerable code @Override public void createClient() { // Create Security Object (with bootstrap server only) String bsUrl = "coap://" + bootstrapServer.getNonSecureAddress().getHostString() + ":" + bootstrapServer.getNonSecureAddress().getPort(); Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345); createClient(security); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void can_observe_timestamped_resource() throws InterruptedException { TestObservationListener listener = new TestObservationListener(); helper.server.getObservationService().addListener(listener); // observe device timezone ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(), new ObserveRequest(3, 0, 15)); assertEquals(ResponseCode.CONTENT, observeResponse.getCode()); assertNotNull(observeResponse.getCoapResponse()); assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class))); // an observation response should have been sent Observation observation = observeResponse.getObservation(); assertEquals("/3/0/15", observation.getPath().toString()); assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId()); // *** HACK send time-stamped notification as Leshan client does not support it *** // // create time-stamped nodes TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(), LwM2mSingleResource.newStringResource(15, "Paris")); List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>(); timestampedNodes.add(mostRecentNode); timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2, LwM2mSingleResource.newStringResource(15, "Londres"))); byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3/0/15"), new LwM2mModel(helper.createObjectModels()), new DefaultLwM2mValueConverter()); Response firstCoapResponse = (Response) observeResponse.getCoapResponse(); sendNotification(payload, firstCoapResponse, ContentFormat.JSON_CODE); // *** Hack End *** // // verify result listener.waitForNotification(2000); assertTrue(listener.receivedNotify().get()); assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent()); assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode()); assertNotNull(listener.getResponse().getCoapResponse()); assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class))); }
#vulnerable code @Test public void can_observe_timestamped_resource() throws InterruptedException { TestObservationListener listener = new TestObservationListener(); helper.server.getObservationService().addListener(listener); // observe device timezone ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(), new ObserveRequest(3, 0, 15)); assertEquals(ResponseCode.CONTENT, observeResponse.getCode()); assertNotNull(observeResponse.getCoapResponse()); assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class))); // an observation response should have been sent Observation observation = observeResponse.getObservation(); assertEquals("/3/0/15", observation.getPath().toString()); assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId()); // *** HACK send time-stamped notification as Leshan client does not support it *** // // create time-stamped nodes TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(), LwM2mSingleResource.newStringResource(15, "Paris")); List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>(); timestampedNodes.add(mostRecentNode); timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2, LwM2mSingleResource.newStringResource(15, "Londres"))); byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3/0/15"), new LwM2mModel(helper.createObjectModels())); Response firstCoapResponse = (Response) observeResponse.getCoapResponse(); sendNotification(payload, firstCoapResponse, ContentFormat.JSON_CODE); // *** Hack End *** // // verify result listener.waitForNotification(2000); assertTrue(listener.receivedNotify().get()); assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent()); assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode()); assertNotNull(listener.getResponse().getCoapResponse()); assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class))); } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void createClient() { // Create objects Enabler ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels())); initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec( "coap://" + server.getUnsecuredAddress().getHostString() + ":" + server.getUnsecuredAddress().getPort(), 12345)); initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false)); initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") { @Override public ExecuteResponse execute(int resourceid, String params) { if (resourceid == 4) { return ExecuteResponse.success(); } else { return super.execute(resourceid, params); } } }); List<LwM2mObjectEnabler> objects = initializer.createMandatory(); objects.addAll(initializer.create(2, 2000)); // Build Client LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get()); builder.setObjects(objects); client = builder.build(); }
#vulnerable code public void createClient() { // Create objects Enabler ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels())); initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec( "coap://" + server.getNonSecureAddress().getHostString() + ":" + server.getNonSecureAddress().getPort(), 12345)); initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false)); initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") { @Override public ExecuteResponse execute(int resourceid, String params) { if (resourceid == 4) { return ExecuteResponse.success(); } else { return super.execute(resourceid, params); } } }); List<LwM2mObjectEnabler> objects = initializer.createMandatory(); objects.addAll(initializer.create(2, 2000)); // Build Client LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get()); builder.setObjects(objects); client = builder.build(); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void createClient() { createClient(withoutSecurity(), null); }
#vulnerable code @Override public void createClient() { // Create Security Object (with bootstrap server only) String bsUrl = "coap://" + bootstrapServer.getUnsecuredAddress().getHostString() + ":" + bootstrapServer.getUnsecuredAddress().getPort(); Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345); createClient(security); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] encodeInteger(Number number) { ByteBuffer iBuf = null; long lValue = number.longValue(); if (lValue >= Byte.MIN_VALUE && lValue <= Byte.MAX_VALUE) { iBuf = ByteBuffer.allocate(1); iBuf.put((byte) lValue); } else if (lValue >= Short.MIN_VALUE && lValue <= Short.MAX_VALUE) { iBuf = ByteBuffer.allocate(2); iBuf.putShort((short) lValue); } else if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) { iBuf = ByteBuffer.allocate(4); iBuf.putInt((int) lValue); } else { iBuf = ByteBuffer.allocate(8); iBuf.putLong(lValue); } return iBuf.array(); }
#vulnerable code public static byte[] encodeInteger(Number number) { ByteBuffer iBuf = null; long longValue = number.longValue(); if (longValue == Long.MIN_VALUE) { throw new IllegalArgumentException( "Could not encode Long.MIN_VALUE, because of signed magnitude representation."); } long positiveValue = longValue < 0 ? -longValue : longValue; if (positiveValue <= Byte.MAX_VALUE) { iBuf = ByteBuffer.allocate(1); iBuf.put((byte) positiveValue); } else if (positiveValue <= Short.MAX_VALUE) { iBuf = ByteBuffer.allocate(2); iBuf.putShort((short) positiveValue); } else if (positiveValue <= Integer.MAX_VALUE) { iBuf = ByteBuffer.allocate(4); iBuf.putInt((int) positiveValue); } else if (positiveValue <= Long.MAX_VALUE) { iBuf = ByteBuffer.allocate(8); iBuf.putLong(positiveValue); } byte[] bytes = iBuf.array(); // set the most significant bit to 1 if negative value if (number.longValue() < 0) { bytes[0] |= 0b1000_0000; } return bytes; } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void initCsvTests(CsvDirectory csvDirectory) throws FileNotFoundException, IOException { File testsRoot = getDirectory(csvDirectory.value()); String extension = csvDirectory.extension(); testMethods = new ArrayList<Method>(); tests = new HashMap<String, List<List<String>>>(); collectCsvTests(testsRoot, extension, tests); }
#vulnerable code private void initCsvTests(CsvDirectory csvDirectory) throws FileNotFoundException, IOException { File directory = getDirectory(csvDirectory.value()); testMethods = new ArrayList<Method>(); tests = new HashMap<String, List<List<String>>>(); for (File f : directory.listFiles()) { if (f.getName().endsWith(csvDirectory.extension())) { tests.put(f.getAbsolutePath(), CsvReader.readCsv(new FileReader(f))); } } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void close () { super.close(); synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection. } // Select one last time to complete closing the socket. if (!isClosed) { isClosed = true; selector.wakeup(); try { selector.selectNow(); } catch (IOException ignored) { } } }
#vulnerable code public void close () { super.close(); // Select one last time to complete closing the socket. synchronized (updateLock) { if (!isClosed) { isClosed = true; selector.wakeup(); try { selector.selectNow(); } catch (IOException ignored) { } } } } #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 boolean isReturnTypeVoid() { return getReturnType() == null || getReturnType().isType(Void.TYPE); }
#vulnerable code @Override public boolean isReturnTypeVoid() { return getReturnType().isType(Void.TYPE); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Specification<T> combinedSpecs = null; for (Specification<T> spec : innerSpecs) { if (combinedSpecs == null) { combinedSpecs = Specification.where(spec); } else { combinedSpecs = combinedSpecs.or(spec); } } return combinedSpecs.toPredicate(root, query, cb); }
#vulnerable code @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) { Specifications<T> combinedSpecs = null; for (Specification<T> spec : innerSpecs) { if (combinedSpecs == null) { combinedSpecs = Specifications.where(spec); } else { combinedSpecs = combinedSpecs.or(spec); } } return combinedSpecs.toPredicate(root, query, cb); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") protected void createBean(AbstractClassBean<?> bean, Set<AbstractBean<?, ?>> beans) { beans.add(bean); manager.getResolver().addInjectionPoints(bean.getInjectionPoints()); for (AnnotatedMethod<Object> producerMethod : bean.getProducerMethods()) { ProducerMethodBean<?> producerMethodBean = createProducerMethodBean(producerMethod, bean, manager); beans.add(producerMethodBean); manager.getResolver().addInjectionPoints(producerMethodBean.getInjectionPoints()); registerEvents(producerMethodBean.getInjectionPoints(), beans); log.info("Web Bean: " + producerMethodBean); } for (AnnotatedField<Object> producerField : bean.getProducerFields()) { ProducerFieldBean<?> producerFieldBean = createProducerFieldBean(producerField, bean, manager); beans.add(producerFieldBean); log.info("Web Bean: " + producerFieldBean); } for (AnnotatedMethod<Object> initializerMethod : bean.getInitializerMethods()) { for (AnnotatedParameter<Object> parameter : initializerMethod.getAnnotatedParameters(Observable.class)) { registerEvent(parameter, beans); } } for (AnnotatedItem injectionPoint : bean.getInjectionPoints()) { if ( injectionPoint.isAnnotationPresent(Observable.class) ) { registerEvent(injectionPoint, beans); } if ( injectionPoint.isAnnotationPresent(Obtainable.class) ) { InstanceBean<Object, Field> instanceBean = createInstanceBean(injectionPoint, manager); beans.add(instanceBean); log.info("Web Bean: " + instanceBean); } } for (AnnotatedMethod<Object> observerMethod : bean.getObserverMethods()) { ObserverImpl<?> observer = createObserver(observerMethod, bean, manager); if (observerMethod.getAnnotatedParameters(Observes.class).size() == 1) { registerObserver(observer, observerMethod.getAnnotatedParameters(Observes.class).get(0).getType(), observerMethod.getAnnotatedParameters(Observes.class).get(0).getBindingTypesAsArray()); } else { throw new DefinitionException("Observer method can only have one parameter annotated @Observes " + observer); } } log.info("Web Bean: " + bean); }
#vulnerable code @SuppressWarnings("unchecked") protected void createBean(AbstractClassBean<?> bean, Set<AbstractBean<?, ?>> beans) { beans.add(bean); manager.getResolver().addInjectionPoints(bean.getInjectionPoints()); for (AnnotatedMethod<Object> producerMethod : bean.getProducerMethods()) { ProducerMethodBean<?> producerMethodBean = createProducerMethodBean(producerMethod, bean, manager); beans.add(producerMethodBean); manager.getResolver().addInjectionPoints(producerMethodBean.getInjectionPoints()); for (AnnotatedItem injectionPoint : producerMethodBean.getInjectionPoints()) { if ( injectionPoint.isAnnotationPresent(Observable.class) ) { EventBean<Object, Method> eventBean = createEventBean(injectionPoint, manager); beans.add(eventBean); log.info("Web Bean: " + eventBean); } } log.info("Web Bean: " + producerMethodBean); } for (AnnotatedField<Object> producerField : bean.getProducerFields()) { ProducerFieldBean<?> producerFieldBean = createProducerFieldBean(producerField, bean, manager); beans.add(producerFieldBean); log.info("Web Bean: " + producerFieldBean); } for (AnnotatedItem injectionPoint : bean.getInjectionPoints()) { if ( injectionPoint.isAnnotationPresent(Observable.class) ) { EventBean<Object, Field> eventBean = createEventBean(injectionPoint, manager); beans.add(eventBean); log.info("Web Bean: " + eventBean); } if ( injectionPoint.isAnnotationPresent(Obtainable.class) ) { InstanceBean<Object, Field> instanceBean = createInstanceBean(injectionPoint, manager); beans.add(instanceBean); log.info("Web Bean: " + instanceBean); } } for (AnnotatedMethod<Object> observerMethod : bean.getObserverMethods()) { ObserverImpl<?> observer = createObserver(observerMethod, bean, manager); if (observerMethod.getAnnotatedParameters(Observes.class).size() == 1) { registerObserver(observer, observerMethod.getAnnotatedParameters(Observes.class).get(0).getType(), observerMethod.getAnnotatedParameters(Observes.class).get(0).getBindingTypesAsArray()); } else { throw new DefinitionException("Observer method can only have one parameter annotated @Observes " + observer); } } log.info("Web Bean: " + bean); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void beginRequest(HttpServletRequest request) { }
#vulnerable code public static void beginRequest(HttpServletRequest request) { ManagerImpl manager = (ManagerImpl) JNDI.lookup("manager"); SessionContext sessionContext = (SessionContext) manager.getContext(SessionScoped.class); BeanMap sessionBeans = (BeanMap) request.getAttribute(SESSION_BEANMAP_KEY); sessionContext.setBeans(sessionBeans); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String toString() { if (toString != null) { return toString; } toString = toDetailedString(); return toString; }
#vulnerable code @Override public String toString() { if (toString != null) { return toString; } toString = "Annotated parameter " + Names.type2String(getDelegate().getClass()); return toString; } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("Manager\n"); buffer.append("Enabled deployment types: " + getEnabledDeploymentTypes() + "\n"); buffer.append("Registered contexts: " + contextMap.keySet() + "\n"); buffer.append("Registered beans: " + getBeans().size() + "\n"); buffer.append("Registered decorators: " + decorators.size() + "\n"); buffer.append("Registered interceptors: " + interceptors.size() + "\n"); return buffer.toString(); }
#vulnerable code @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append(Strings.collectionToString("Enabled deployment types: ", getEnabledDeploymentTypes())); buffer.append(eventManager.toString() + "\n"); buffer.append(MetaDataCache.instance().toString() + "\n"); buffer.append(resolver.toString() + "\n"); buffer.append(contextMap.toString() + "\n"); buffer.append(proxyPool.toString() + "\n"); buffer.append(Strings.collectionToString("Registered beans: ", getBeans())); buffer.append(Strings.collectionToString("Registered decorators: ", decorators)); buffer.append(Strings.collectionToString("Registered interceptors: ", interceptors)); return buffer.toString(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public final boolean isWebElementSufficientlyShown(WebElement webElement){ final WebView webView = viewFetcher.getFreshestView(viewFetcher.getCurrentViews(WebView.class)); final int[] xyWebView = new int[2]; if(webView != null && webElement != null){ webView.getLocationOnScreen(xyWebView); if(xyWebView[1] + webView.getHeight() > webElement.getLocationY()) return true; } return false; }
#vulnerable code public final boolean isWebElementSufficientlyShown(WebElement webElement){ final WebView webView = viewFetcher.getFreshestView(viewFetcher.getCurrentViews(WebView.class)); final int[] xyWebView = new int[2]; if(webElement != null){ webView.getLocationOnScreen(xyWebView); if(xyWebView[1] + webView.getHeight() > webElement.getLocationY()) return true; } return false; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean scrollScrollView(int direction, ArrayList<ScrollView> scrollViews){ ScrollView scroll = viewFetcher.getView(ScrollView.class, scrollViews, 0); if(scroll !=null){ int height = scroll.getHeight(); height--; int scrollTo = 0; if (direction == DOWN) { scrollTo = (height); } else if (direction == UP) { scrollTo = (-height); } scrollAmount = scroll.getScrollY(); scrollScrollViewTo(scroll,0, scrollTo); if (scrollAmount == scroll.getScrollY()) { return false; } else{ return true; } } return false; }
#vulnerable code private boolean scrollScrollView(int direction, ArrayList<ScrollView> scrollViews){ ScrollView scroll = viewFetcher.getView(ScrollView.class, scrollViews, 0); int height = scroll.getHeight(); height--; int scrollTo = 0; if (direction == DOWN) { scrollTo = (height); } else if (direction == UP) { scrollTo = (-height); } scrollAmount = scroll.getScrollY(); scrollScrollViewTo(scroll,0, scrollTo); if (scrollAmount == scroll.getScrollY()) { return false; } else{ return true; } } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Bitmap getBitmapOfView(final View view){ view.destroyDrawingCache(); view.buildDrawingCache(false); Bitmap orig = view.getDrawingCache(); Bitmap.Config config = null; if(orig == null) { return null; } config = orig.getConfig(); if(config == null) { config = Bitmap.Config.ARGB_8888; } Bitmap b = orig.copy(config, false); view.destroyDrawingCache(); return b; }
#vulnerable code private Bitmap getBitmapOfView(final View view){ view.destroyDrawingCache(); view.buildDrawingCache(false); Bitmap orig = view.getDrawingCache(); Bitmap.Config config = null; if(orig != null) { config = orig.getConfig(); } if(config == null) { config = Bitmap.Config.ARGB_8888; } Bitmap b = orig.copy(config, false); view.destroyDrawingCache(); return b; } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void finishOpenedActivities(){ // Stops the activityStack listener activitySyncTimer.cancel(); ArrayList<Activity> activitiesOpened = getAllOpenedActivities(); // Finish all opened activities for (int i = activitiesOpened.size()-1; i >= 0; i--) { sleeper.sleep(MINISLEEP); finishActivity(activitiesOpened.get(i)); } // Finish the initial activity, pressing Back for good measure finishActivity(getCurrentActivity()); sleeper.sleepMini(); try { inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); sleeper.sleep(MINISLEEP); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } catch (Throwable ignored) { // Guard against lack of INJECT_EVENT permission } activityStack.clear(); }
#vulnerable code public void finishOpenedActivities(){ ArrayList<Activity> activitiesOpened = getAllOpenedActivities(); // Finish all opened activities for (int i = activitiesOpened.size()-1; i >= 0; i--) { sleeper.sleep(MINISLEEP); finishActivity(activitiesOpened.get(i)); } // Finish the initial activity, pressing Back for good measure finishActivity(getCurrentActivity()); sleeper.sleepMini(); try { inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); sleeper.sleep(MINISLEEP); inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); } catch (Throwable ignored) { // Guard against lack of INJECT_EVENT permission } activityList.clear(); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testShortArray_AsShorts() throws Exception { assertArrayEquals(new byte[]{1, 2, 3, 4}, BeginBin().Short((short)0x0102, (short)0x0304).End().toByteArray()); }
#vulnerable code @Test public void testShortArray_AsShorts() throws Exception { assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)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 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 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testByte() throws Exception { assertArrayEquals(new byte[]{-34}, BeginBin().Byte(-34).End().toByteArray()); }
#vulnerable code @Test public void testByte() throws Exception { assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).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 testLong_LittleEndian() throws Exception { assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, BeginBin().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).End().toByteArray()); }
#vulnerable code @Test public void testLong_LittleEndian() throws Exception { assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).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 int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { int result; final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { result = this.readByteFromStream(); this.byteCounter++; return result; } else { result = 0; if (numOfBitsAsNumber == this.bitsInBuffer) { result = this.bitBuffer; this.bitBuffer = 0; this.bitsInBuffer = 0; if (numOfBitsAsNumber == 8) { this.byteCounter++; } return result; } int i = numOfBitsAsNumber; int theBitBuffer = this.bitBuffer; int theBitBufferCounter = this.bitsInBuffer; while (i > 0) { if (theBitBufferCounter == 0) { final int nextByte = this.readByteFromStream(); if (nextByte < 0) { if (i == numOfBitsAsNumber) { return nextByte; } else { break; } } else { theBitBuffer = nextByte; theBitBufferCounter = 8; this.byteCounter++; } } result = (result << 1) | (theBitBuffer & 1); theBitBuffer >>= 1; theBitBufferCounter--; i--; } this.bitBuffer = theBitBuffer; this.bitsInBuffer = theBitBufferCounter; return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i)); } }
#vulnerable code public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { int result; final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { result = this.readByteFromStream(); return result; } else { result = 0; if (numOfBitsAsNumber == this.bitsInBuffer){ result = this.bitBuffer; this.bitBuffer = 0; this.bitsInBuffer = 0; return result; } int i = numOfBitsAsNumber; int theBitBuffer = this.bitBuffer; int theBitBufferCounter = this.bitsInBuffer; while (i > 0) { if (theBitBufferCounter == 0) { final int nextByte = this.readByteFromStream(); if (nextByte < 0) { if (i == numOfBitsAsNumber) { return nextByte; } else { break; } } else { theBitBuffer = nextByte; theBitBufferCounter = 8; } } result = (result << 1) | (theBitBuffer & 1); theBitBuffer >>= 1; theBitBufferCounter--; i--; } this.bitBuffer = theBitBuffer; this.bitsInBuffer = theBitBufferCounter; return (JBBPUtils.reverseByte((byte) result) & 0xFF) >> (8 - (numOfBitsAsNumber - i)); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION