repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/WaitOutsideLoop.java
synchronized (obj) { while (<condition is false>) obj.wait(); // condition is true, perform appropriate action ... }
124
30.25
56
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/DoubleCheckedLockingBad3.java
private Object lock = new Object(); private MyImmutableObject f = null; public MyImmutableObject getMyImmutableObject() { if (f == null) { synchronized(lock) { if (f == null) { f = new MyImmutableObject(); } } } return f; // BAD }
266
18.071429
49
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/DoubleCheckedLockingBad2.java
private Object lock = new Object(); private volatile MyObject f = null; public MyObject getMyObject() { if (f == null) { synchronized(lock) { if (f == null) { f = new MyObject(); f.init(); // BAD } } } return f; }
257
16.2
35
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/InconsistentAccess.java
class MultiThreadCounter { public int counter = 0; public void modifyCounter() { synchronized(this) { counter--; } synchronized(this) { counter--; } synchronized(this) { counter--; } counter = counter + 3; // No synchronization } }
338
18.941176
53
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/SynchOnBoxedType.java
class BadSynchronize{ class ThreadA extends Thread{ private String value = "lock" public void run(){ synchronized(value){ //... } } } class ThreadB extends Thread{ private String value = "lock" public void run(){ synchronized(value){ //... } } } public void run(){ new ThreadA().start(); new ThreadB().start(); } }
372
12.321429
31
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/LazyInitStaticFieldGood.java
class Singleton { private static Resource resource; static { resource = new Resource(); // Initialize "resource" only once } public Resource getResource() { return resource; } }
217
18.818182
70
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/SynchOnBoxedTypeGood.java
class GoodSynchronize{ class ThreadA extends Thread{ private Object lock = new Object(); public void run(){ synchronized(lock){ //... } } } class ThreadB extends Thread{ private Object lock = new Object(); public void run(){ synchronized(lock){ //... } } } public void run(){ new ThreadA().start(); new ThreadB().start(); } }
385
12.785714
37
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/WaitWithTwoLocksGood.java
class WaitWithTwoLocksGood { private static class Message { public int id = 0; public String text = null; } private final Message message = new Message(); public void printText() { synchronized (message) { while(message.txt == null) try { message.wait(); } catch (InterruptedException e) { ... } System.out.println(message.id + ":" + message.text); message.text = null; message.notifyAll(); } } public void setText(String mesg) { synchronized (message) { message.id++; message.text = mesg; message.notifyAll(); } } }
750
23.225806
64
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/EmptyRunMethodInThreadGood.java
class GoodWithOverride{ public void runInThread(){ Thread thread = new Thread(){ @Override public void run(){ System.out.println("Doing something"); } }; thread.start; } } class GoodWithRunnable{ public void runInThread(){ Runnable thingToRun = new Runnable(){ @Override public void run(){ System.out.println("Doing something"); } }; Thread thread = new Thread(thingToRun()); thread.start(); } }
489
15.896552
46
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/EmptyRunMethodInThread.java
class Bad{ public void runInThread(){ Thread thread = new Thread(); thread.start(); } }
101
11.75
33
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/SleepWithLock.java
class StorageThread implements Runnable{ public static Integer counter = 0; private static final Object LOCK = new Object(); public void run() { System.out.println("StorageThread started."); synchronized(LOCK) { // "LOCK" is locked just before the thread goes to sleep try { Thread.sleep(5000); } catch (InterruptedException e) { ... } } System.out.println("StorageThread exited."); } } class OtherThread implements Runnable{ public void run() { System.out.println("OtherThread started."); synchronized(StorageThread.LOCK) { StorageThread.counter++; } System.out.println("OtherThread exited."); } } public class SleepWithLock { public static void main(String[] args) { new Thread(new StorageThread()).start(); new Thread(new OtherThread()).start(); } }
921
27.8125
86
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/BusyWait.java
class Message { public String text = ""; } class Receiver implements Runnable { private Message message; public Receiver(Message msg) { this.message = msg; } public void run() { while(message.text.isEmpty()) { try { Thread.sleep(5000); // Sleep while waiting for condition to be satisfied } catch (InterruptedException e) { } } System.out.println("Message Received at " + (System.currentTimeMillis()/1000)); System.out.println(message.text); } } class Sender implements Runnable { private Message message; public Sender(Message msg) { this.message = msg; } public void run() { System.out.println("Message sent at " + (System.currentTimeMillis()/1000)); message.text = "Hello World"; } } public class BusyWait { public static void main(String[] args) { Message msg = new Message(); new Thread(new Receiver(msg)).start(); new Thread(new Sender(msg)).start(); } }
1,045
25.820513
89
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/CallsToRunnableRun.java
public class ThreadDemo { public static void main(String args[]) { NewThread runnable = new NewThread(); runnable.run(); // Call to 'run' does not start a separate thread System.out.println("Main thread activity."); } } class NewThread extends Thread { public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Child thread activity."); } }
538
24.666667
76
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/CallsToRunnableRunFixed.java
public class ThreadDemo { public static void main(String args[]) { NewThread runnable = new NewThread(); runnable.start(); // Call 'start' method System.out.println("Main thread activity."); } }
278
30
88
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/StartInConstructorGood.java
class Super { Thread thread; public Super() { thread = new Thread() { public void run() { System.out.println(Super.this.toString()); } }; } public void start() { // good thread.start(); } public String toString() { return "hello"; } } class Test extends Super { private String name; public Test(String nm) { this.name = nm; } public String toString() { return super.toString() + " " + name; } public static void main(String[] args) { Test t = new Test("my friend"); t.start(); } }
650
18.147059
58
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/FutileSynchOnField.java
public class A { private Object field; public void setField(Object o){ synchronized (field){ // BAD: synchronize on the field to be updated field = o; // ... more code ... } } }
249
24
79
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/NotifyWithoutSynch.java
class ProducerConsumer { private static final int MAX_SIZE=3; private List<Object> buf = new ArrayList<Object>(); public synchronized void produce(Object o) { while (buf.size()==MAX_SIZE) { try { wait(); } catch (InterruptedException e) { ... } } buf.add(o); notifyAll(); } public Object consume() { while (buf.size()==0) { try { wait(); } catch (InterruptedException e) { ... } } Object o = buf.remove(0); notifyAll(); return o; } }
691
20.625
55
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/FutileSynchOnFieldGood.java
public class B { private final Object lock = new Object(); private Object field; public void setField(Object o){ synchronized (lock){ // GOOD: synchronize on a separate lock object field = o; // ... more code ... } } }
272
23.818182
79
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/BusyWaitGood.java
class Message { public String text = ""; } class Receiver implements Runnable { private Message message; public Receiver(Message msg) { this.message = msg; } public void run() { synchronized(message) { while(message.text.isEmpty()) { try { message.wait(); // Wait for a notification } catch (InterruptedException e) { } } } System.out.println("Message Received at " + (System.currentTimeMillis()/1000)); System.out.println(message.text); } } class Sender implements Runnable { private Message message; public Sender(Message msg) { this.message = msg; } public void run() { System.out.println("Message sent at " + (System.currentTimeMillis()/1000)); synchronized(message) { message.text = "Hello World"; message.notifyAll(); // Send notification } } } public class BusyWait { public static void main(String[] args) { Message msg = new Message(); new Thread(new Receiver(msg)).start(); new Thread(new Sender(msg)).start(); } }
1,178
25.795455
87
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/LazyInitStaticField.java
class Singleton { private static Resource resource; public Resource getResource() { if(resource == null) resource = new Resource(); // Lazily initialize "resource" return resource; } }
226
24.222222
71
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/DoubleCheckedLockingBad1.java
private Object lock = new Object(); private MyObject f = null; public MyObject getMyObject() { if (f == null) { synchronized(lock) { if (f == null) { f = new MyObject(); // BAD } } } return f; }
230
15.5
35
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/DateFormatThreadUnsafe.java
class DateFormattingThread implements Runnable { private static DateFormat dateF = new SimpleDateFormat("yyyyMMdd"); // Static field declared public void run() { for(int i=0; i < 10; i++){ try { Date d = dateF.parse("20121221"); System.out.println(d); } catch (ParseException e) { } } } } public class DateFormatThreadUnsafe { public static void main(String[] args) { for(int i=0; i<100; i++){ new Thread(new DateFormattingThread()).start(); } } }
576
25.227273
97
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/StartInConstructor.java
class Super { public Super() { new Thread() { public void run() { System.out.println(Super.this.toString()); } }.start(); // BAD: The thread is started in the constructor of 'Super'. } public String toString() { return "hello"; } } class Test extends Super { private String name; public Test(String nm) { // The thread is started before // this line is run this.name = nm; } public String toString() { return super.toString() + " " + name; } public static void main(String[] args) { new Test("my friend"); } }
661
21.066667
79
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/WaitWithTwoLocks.java
class WaitWithTwoLocks { private final Object idLock = new Object(); private int id = 0; private final Object textLock = new Object(); private String text = null; public void printText() { synchronized (idLock) { synchronized (textLock) { while(text == null) try { textLock.wait(); // The lock on "textLock" is released but not the // lock on "idLock". } catch (InterruptedException e) { ... } System.out.println(id + ":" + text); text = null; textLock.notifyAll(); } } } public void setText(String mesg) { synchronized (idLock) { // "setText" needs a lock on "idLock" but "printText" already // holds a lock on "idLock", leading to deadlock synchronized (textLock) { id++; text = mesg; idLock.notifyAll(); textLock.notifyAll(); } } } }
1,141
29.864865
93
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/DateFormatThreadUnsafeGood.java
class DateFormattingThread implements Runnable { private DateFormat dateF = new SimpleDateFormat("yyyyMMdd"); // Instance field declared public void run() { for(int i=0; i < 10; i++){ try { Date d = dateF.parse("20121221"); System.out.println(d); } catch (ParseException e) { } } } } public class DateFormatThreadUnsafeFix { public static void main(String[] args) { for(int i=0; i<100; i++){ new Thread(new DateFormattingThread()).start(); } } }
574
25.136364
92
java
codeql
codeql-master/java/ql/src/Likely Bugs/Concurrency/NotifyNotNotifyAll.java
class ProducerConsumer { private static final int MAX_SIZE=3; private List<Object> buf = new ArrayList<Object>(); public synchronized void produce(Object o) { while (buf.size()==MAX_SIZE) { try { wait(); } catch (InterruptedException e) { ... } } buf.add(o); notify(); // 'notify' is used } public synchronized Object consume() { while (buf.size()==0) { try { wait(); } catch (InterruptedException e) { ... } } Object o = buf.remove(0); notify(); // 'notify' is used return o; } }
739
21.424242
55
java
codeql
codeql-master/java/ql/src/Likely Bugs/Frameworks/Swing/BadlyOverriddenAdapter.java
add(new MouseAdapter() { public void mouseClickd(MouseEvent e) { // ... } });
93
17.8
43
java
codeql
codeql-master/java/ql/src/Likely Bugs/Frameworks/Swing/ThreadSafety.java
class MyFrame extends JFrame { public MyFrame() { setSize(640, 480); setTitle("BrokenSwing"); } } public class BrokenSwing { private static void doStuff(MyFrame frame) { // BAD: Direct call to a Swing component after it has been realized frame.setTitle("Title"); } public static void main(String[] args) { MyFrame frame = new MyFrame(); frame.setVisible(true); doStuff(frame); } }
462
23.368421
75
java
codeql
codeql-master/java/ql/src/Likely Bugs/Frameworks/Swing/ThreadSafetyGood.java
class MyFrame extends JFrame { public MyFrame() { setSize(640, 480); setTitle("BrokenSwing"); } } public class GoodSwing { private static void doStuff(final MyFrame frame) { SwingUtilities.invokeLater(new Runnable() { public void run() { // GOOD: Call to Swing component made via the // event-dispatching thread using 'invokeLater' frame.setTitle("Title"); } }); } public static void main(String[] args) { MyFrame frame = new MyFrame(); frame.setVisible(true); doStuff(frame); } }
635
24.44
63
java
codeql
codeql-master/java/ql/src/Likely Bugs/Frameworks/Swing/BadlyOverriddenAdapterGood.java
add(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // ... } });
108
17.166667
44
java
codeql
codeql-master/java/ql/src/Likely Bugs/Frameworks/JUnit/BadSuiteMethod.java
public class BadSuiteMethod extends TestCase { // BAD: JUnit 3.8 does not detect the following method as a 'suite' method. // The method should be public, static, and return 'junit.framework.Test' // or one of its subtypes. static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new MyTests("testEquals")); suite.addTest(new MyTests("testNotEquals")); return suite; } } public class CorrectSuiteMethod extends TestCase { // GOOD: JUnit 3.8 correctly detects the following method as a 'suite' method. public static Test suite() { TestSuite suite = new TestSuite(); suite.addTest(new MyTests("testEquals")); suite.addTest(new MyTests("testNotEquals")); return suite; } }
710
32.857143
79
java
codeql
codeql-master/java/ql/src/Likely Bugs/Frameworks/JUnit/TearDownNoSuper.java
// Abstract class that initializes then shuts down the // framework after each set of tests abstract class FrameworkTestCase extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); Framework.init(); } @Override protected void tearDown() throws Exception { super.tearDown(); Framework.shutdown(); } } // The following classes extend 'FrameworkTestCase' to reuse the // 'setUp' and 'tearDown' methods of the framework. public class TearDownNoSuper extends FrameworkTestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testFramework() { //... } public void testFramework2() { //... } @Override protected void tearDown() throws Exception { // BAD: Does not call 'super.tearDown'. May cause later tests to fail // when they try to re-initialize an already initialized framework. // Even if the framework allows re-initialization, it may maintain the // internal state, which could affect the results of succeeding tests. System.out.println("Tests complete"); } } public class TearDownSuper extends FrameworkTestCase { @Override protected void setUp() throws Exception { super.setUp(); } public void testFramework() { //... } public void testFramework2() { //... } @Override protected void tearDown() throws Exception { // GOOD: Correctly calls 'super.tearDown' to shut down the // framework. System.out.println("Tests complete"); super.tearDown(); } }
1,496
22.030769
72
java
codeql
codeql-master/java/ql/src/Likely Bugs/Frameworks/JUnit/TestCaseNoTests.java
// BAD: This test case class does not have any valid JUnit 3.8 test methods. public class TestCaseNoTests38 extends TestCase { // This is not a test case because it does not start with 'test'. public void simpleTest() { //... } // This is not a test case because it takes two parameters. public void testNotEquals(int i, int j) { assertEquals(i != j, true); } // This is recognized as a test, but causes JUnit to fail // when run because it is not public. void testEquals() { //... } } // GOOD: This test case class correctly declares test methods. public class MyTests extends TestCase { public void testEquals() { assertEquals(1, 1); } public void testNotEquals() { assertFalse(1 == 2); } }
719
24.714286
76
java
codeql
codeql-master/java/ql/src/Likely Bugs/Cloning/MissingCallToSuperCloneBad.java
class WrongPerson implements Cloneable { private String name; public WrongPerson(String name) { this.name = name; } // BAD: 'clone' does not call 'super.clone'. public WrongPerson clone() { return new WrongPerson(this.name); } } class WrongEmployee extends WrongPerson { public WrongEmployee(String name) { super(name); } // ALMOST RIGHT: 'clone' correctly calls 'super.clone', // but 'super.clone' is implemented incorrectly. public WrongEmployee clone() { return (WrongEmployee)super.clone(); } } public class MissingCallToSuperClone { public static void main(String[] args) { WrongEmployee e = new WrongEmployee("John Doe"); WrongEmployee eclone = e.clone(); // Causes a ClassCastException } }
788
28.222222
72
java
codeql
codeql-master/java/ql/src/Likely Bugs/Cloning/MissingMethodCloneGood.java
abstract class AbstractStack implements Cloneable { public AbstractStack clone() { try { return (AbstractStack) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError("Should not happen"); } } } class RightStack extends AbstractStack { private static final int MAX_STACK = 10; int[] elements = new int[MAX_STACK]; int top = -1; void push(int newInt) { elements[++top] = newInt; } int pop() { return elements[top--]; } // GOOD: 'clone' method to create a copy of the elements. public RightStack clone() { RightStack cloned = (RightStack) super.clone(); cloned.elements = elements.clone(); // 'cloned' has its own elements. return cloned; } } public class MissingMethodClone { public static void main(String[] args) { RightStack rs1 = new RightStack(); // rs1: {} rs1.push(1); // rs1: {1} rs1.push(2); // rs1: {1,2} RightStack rs1clone = rs1.clone(); // rs1clone: {1,2} rs1clone.pop(); // rs1clone: {1} rs1clone.push(3); // rs1clone: {1,3} System.out.println(rs1.pop()); // Correctly prints 2 } }
1,403
30.909091
78
java
codeql
codeql-master/java/ql/src/Likely Bugs/Cloning/MissingCallToSuperCloneGood.java
class Person implements Cloneable { private String name; public Person(String name) { this.name = name; } // GOOD: 'clone' correctly calls 'super.clone' public Person clone() { try { return (Person)super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError("Should never happen"); } } } class Employee extends Person { public Employee(String name) { super(name); } // GOOD: 'clone' correctly calls 'super.clone' public Employee clone() { return (Employee)super.clone(); } } public class MissingCallToSuperClone { public static void main(String[] args) { Employee e2 = new Employee("Jane Doe"); Employee e2clone = e2.clone(); // 'clone' correctly returns an object of type 'Employee' } }
836
26.9
96
java
codeql
codeql-master/java/ql/src/Likely Bugs/Cloning/MissingMethodCloneBad.java
abstract class AbstractStack implements Cloneable { public AbstractStack clone() { try { return (AbstractStack) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError("Should not happen"); } } } class WrongStack extends AbstractStack { private static final int MAX_STACK = 10; int[] elements = new int[MAX_STACK]; int top = -1; void push(int newInt) { elements[++top] = newInt; } int pop() { return elements[top--]; } // BAD: No 'clone' method to create a copy of the elements. // Therefore, the default 'clone' implementation (shallow copy) is used, which // is equivalent to: // // public WrongStack clone() { // WrongStack cloned = (WrongStack) super.clone(); // cloned.elements = elements; // Both 'this' and 'cloned' now use the same elements. // return cloned; // } } public class MissingMethodClone { public static void main(String[] args) { WrongStack ws1 = new WrongStack(); // ws1: {} ws1.push(1); // ws1: {1} ws1.push(2); // ws1: {1,2} WrongStack ws1clone = (WrongStack) ws1.clone(); // ws1clone: {1,2} ws1clone.pop(); // ws1clone: {1} ws1clone.push(3); // ws1clone: {1,3} System.out.println(ws1.pop()); // Because ws1 and ws1clone have the same // elements, this prints 3 instead of 2 } }
1,668
34.510638
97
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/StaticFieldWrittenByInstance.java
public class Customer { private static List<Customer> customers; public void initialize() { // AVOID: Static field is written to by instance method. customers = new ArrayList<Customer>(); register(); } public static void add(Customer c) { customers.add(c); } } // ... public class Department { public void addCustomer(String name) { Customer c = new Customer(n); // The following call overwrites the list of customers // stored in 'Customer' (see above). c.initialize(); Customer.add(c); } }
518
21.565217
58
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/EmptyBlock.java
public class Parser { public void parse(String input) { int pos = 0; // ... // AVOID: Empty block while (input.charAt(pos++) != '=') { } // ... } }
160
13.636364
40
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/PartiallyMaskedCatch.java
FileOutputStream fos = null; try { fos = new FileOutputStream(new File("may_not_exist.txt")); } catch (FileNotFoundException e) { // ask the user and try again } catch (IOException e) { // more serious, abort } finally { if (fos!=null) { try { fos.close(); } catch (IOException e) { /*ignore*/ } } }
303
29.4
77
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/UseBracesGood.java
class Cart { Map<Integer, Integer> items = ... public void addItem(Item i) { // Braces included. if (i != null) { log("Adding item: " + i); Integer curQuantity = items.get(i.getID()); if (curQuantity == null) curQuantity = 0; items.put(i.getID(), curQuantity+1); } } }
352
28.416667
55
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/UseBraces2.java
// Tab width 8 if (b) // Indentation: 1 tab f(); // Indentation: 2 tabs g(); // Indentation: 8 spaces // Tab width 4 if (b) // Indentation: 1 tab f(); // Indentation: 2 tabs g(); // Indentation: 8 spaces
272
29.333333
45
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/UseBraces.java
class Cart { Map<Integer, Integer> items = ... public void addItem(Item i) { // No braces and misleading indentation. if (i != null) log("Adding item: " + i); // Indentation suggests that the following statements // are in the body of the 'if'. Integer curQuantity = items.get(i.getID()); if (curQuantity == null) curQuantity = 0; items.put(i.getID(), curQuantity+1); } }
471
35.307692
65
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/ReturnValueIgnored.java
FileSystem.get(conf); // Return value is not used FileSystem fs = FileSystem.get(conf); // Return value is assigned to 'fs'
126
41.333333
74
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/InconsistentCallOnResult.java
DataOutputStream outValue = null; try { outValue = writer.prepareAppendValue(6); outValue.write("value0".getBytes()); } catch (IOException e) { } finally { if (outValue != null) { outValue.close(); } }
226
16.461538
44
java
codeql
codeql-master/java/ql/src/Likely Bugs/Statements/MissingEnumInSwitch.java
enum Answer { YES, NO, MAYBE } class Optimist { Answer interpret(Answer answer) { switch (answer) { case MAYBE: return Answer.YES; case NO: return Answer.MAYBE; // Missing case for 'YES' } throw new RuntimeException("uncaught case: " + answer); } }
275
16.25
57
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/BadAbsOfRandom.java
public static void main(String args[]) { Random r = new Random(); // BAD: 'mayBeNegativeInt' is negative if // 'nextInt()' returns 'Integer.MIN_VALUE'. int mayBeNegativeInt = Math.abs(r.nextInt()); // GOOD: 'nonNegativeInt' is always a value between 0 (inclusive) // and Integer.MAX_VALUE (exclusive). int nonNegativeInt = r.nextInt(Integer.MAX_VALUE); // GOOD: When 'nextInt' returns a negative number increment the returned value. int nextInt = r.nextInt(); if(nextInt < 0) nextInt++; int nonNegativeInt = Math.abs(nextInt); }
584
31.5
83
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/BadCheckOddGood.java
class CheckOdd { private static boolean isOdd(int x) { return x % 2 != 0; } public static void main(String[] args) { System.out.println(isOdd(-9)); // prints true } }
203
21.666667
53
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/LShiftLargerThanTypeWidth.java
long longVal = intVal << 32; // BAD
35
35
35
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/IntMultToLongGood.java
int i = 2000000000; long k = i*(long)i; // avoids overflow
58
28.5
38
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/IntMultToLong.java
int i = 2000000000; long j = i*i; // causes overflow
52
25.5
32
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/ConstantExpAppearsNonConstantGood.java
public boolean isEven(int x) { return x % 2 == 0; //Does work }
68
16.25
34
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/BadCheckOdd.java
class CheckOdd { private static boolean isOdd(int x) { return x % 2 == 1; } public static void main(String[] args) { System.out.println(isOdd(-9)); // prints false } }
204
21.777778
54
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/OctalLiteral.java
0
0
0
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/CondExprTypes.java
int i = 0; System.out.print(true ? 'x' : 0); // prints "x" System.out.print(true ? 'x' : i); // prints "120"
108
35.333333
49
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/ConstantExpAppearsNonConstant.java
public boolean isEven(int x) { return x % 1 == 0; //Does not work }
69
16.5
35
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/RandomUsedOnce.java
public static void main(String args[]) { // BAD: A new 'Random' object is created every time // a pseudo-random integer is required. int notReallyRandom = new Random().nextInt(); int notReallyRandom2 = new Random().nextInt(); // GOOD: The same 'Random' object is used to generate // two pseudo-random integers. Random r = new Random(); int random1 = r.nextInt(); int random2 = r.nextInt(); }
403
32.666667
55
java
codeql
codeql-master/java/ql/src/Likely Bugs/Arithmetic/LShiftLargerThanTypeWidthGood.java
long longVal = ((long)intVal) << 32; // GOOD
44
44
44
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/UnusedFormatArgBad.java
System.out.format("First string: %s Second string: %s", "Hello", "world", "!");
80
39.5
79
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/ToStringTypo.java
public class Customer { private String title; private String forename; private String surname; // ... public String tostring() { // The method is named 'tostring'. return title + " " + forename + " " + surname; } }
225
17.833333
63
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/HashCodeTypo.java
public class Person { private String title; private String forename; private String surname; // ... public int hashcode() { // The method is named 'hashcode'. int hash = 23 * title.hashCode(); hash ^= 13 * forename.hashCode(); return hash ^ surname.hashCode(); } }
279
19
60
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/ConstructorTypo.java
class MasterSingleton { // ... private static MasterSingleton singleton = new MasterSingleton(); public static MasterSingleton getInstance() { return singleton; } // Make the constructor 'protected' to prevent this class from being instantiated. protected void MasterSingleton() { } }
292
25.636364
83
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/MissingSpaceTypoBad.java
String s = "This text is" + "missing a space.";
50
16
27
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/SelfAssignment.java
static public MotionEvent obtainNoHistory(MotionEvent o) { MotionEvent ev = obtain(o.mNumPointers, 1); ev.mDeviceId = o.mDeviceId; o.mFlags = o.mFlags; // Variable is assigned to itself ... } static public MotionEvent obtainNoHistory(MotionEvent o) { MotionEvent ev = obtain(o.mNumPointers, 1); ev.mDeviceId = o.mDeviceId; ev.mFlags = o.mFlags; // Variable is assigned correctly ... }
420
29.071429
60
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/EqualsTypo.java
public class Complex { private double real; private double complex; // ... public boolean equal(Object obj) { // The method is named 'equal'. if (!getClass().equals(obj.getClass())) return false; Complex other = (Complex) obj; return real == other.real && complex == other.complex; } }
302
20.642857
68
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/ContainerSizeCmpZero.java
import java.io.File; class ContainerSizeCmpZero { private static File MakeFile(String filename) { if(filename != null && filename.length() >= 0) { return new File(filename); } return new File("default.name"); } }
242
19.25
52
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/ContradictoryTypeChecks.java
String getKind(Animal a) { if (a instanceof Mammal) { return "Mammal"; } else if (a instanceof Tiger) { return "Tiger!"; } else { return "unknown"; } }
161
17
33
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/ContainerSizeCmpZeroGood.java
import java.io.File; class ContainerSizeCmpZero { private static File MakeFile(String filename) { if(filename != null && !filename.isEmpty()) { return new File(filename); } return new File("default.name"); } }
239
19
51
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/MissingFormatArgBad.java
System.out.format("First string: %s Second string: %s", "Hello world");
72
35.5
71
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/DangerousNonCircuitLogic.java
public class Person { private String forename; private String surname; public boolean hasForename() { return forename != null && forename.length() > 0; // GOOD: Conditional-and operator } public boolean hasSurname() { return surname != null & surname.length() > 0; // BAD: Bitwise AND operator } // ... }
320
20.4
86
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/StringBufferCharInit.java
class Point { private double x, y; public Point(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { StringBuffer res = new StringBuffer('('); res.append(x); res.append(", "); res.append(y); res.append(')'); return res.toString(); } }
293
14.473684
43
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/SuspiciousDateFormat.java
System.out.println(new SimpleDateFormat("YYYY-MM-dd").format(new Date()));
75
37
74
java
codeql
codeql-master/java/ql/src/Likely Bugs/Likely Typos/ContradictoryTypeChecksGood.java
String getKind(Animal a) { if (a instanceof Tiger) { return "Tiger!"; } else if (a instanceof Mammal) { return "Mammal"; } else { return "unknown"; } }
161
17
34
java
codeql
codeql-master/java/ql/src/Likely Bugs/Inheritance/NoNonFinalInConstructor.java
public class Super { public Super() { init(); } public void init() { } } public class Sub extends Super { String s; int length; public Sub(String s) { this.s = s==null ? "" : s; } @Override public void init() { length = s.length(); } }
258
10.772727
32
java
codeql
codeql-master/java/ql/src/Likely Bugs/Reflection/AnnotationPresentCheck.java
public class AnnotationPresentCheck { public static @interface UntrustedData { } @UntrustedData public static String getUserData() { Scanner scanner = new Scanner(System.in); return scanner.nextLine(); } public static void main(String[] args) throws NoSuchMethodException, SecurityException { String data = getUserData(); Method m = AnnotationPresentCheck.class.getMethod("getUserData"); if(m.isAnnotationPresent(UntrustedData.class)) { // Returns 'false' System.out.println("Not trusting data from user."); } } }
537
30.647059
89
java
codeql
codeql-master/java/ql/src/Likely Bugs/Reflection/AnnotationPresentCheckFix.java
public class AnnotationPresentCheckFix { @Retention(RetentionPolicy.RUNTIME) // Annotate the annotation public static @interface UntrustedData { } @UntrustedData public static String getUserData() { Scanner scanner = new Scanner(System.in); return scanner.nextLine(); } public static void main(String[] args) throws NoSuchMethodException, SecurityException { String data = getUserData(); Method m = AnnotationPresentCheckFix.class.getMethod("getUserData"); if(m.isAnnotationPresent(UntrustedData.class)) { // Returns 'true' System.out.println("Not trusting data from user."); } } }
607
32.777778
89
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseSqlGood.java
public class CloseSqlGood { public static void runQuery(Connection con, String query) throws SQLException { try (Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query)) { while (rs.next()) { // process result set } } } }
265
25.6
80
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseReader.java
public class CloseReader { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new FileReader("C:\\test.txt")); System.out.println(br.readLine()); // ... } }
212
29.428571
73
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseWriter.java
public class CloseWriter { public static void main(String[] args) throws IOException { BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\test.txt")); bw.write("Hello world!"); // ... } }
203
28.142857
73
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseWriterNested.java
public class CloseWriterNested { public static void main(String[] args) throws IOException { OutputStreamWriter writer = null; try { // OutputStreamWriter may throw an exception, in which case the ... writer = new OutputStreamWriter( // ... FileOutputStream is not closed by the finally block new FileOutputStream("C:\\test.txt"), "UTF-8"); writer.write("Hello world!"); } finally { if (writer != null) writer.close(); } } }
462
27.9375
70
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseReaderNested.java
public class CloseReaderNested { public static void main(String[] args) throws IOException { InputStreamReader reader = null; try { // InputStreamReader may throw an exception, in which case the ... reader = new InputStreamReader( // ... FileInputStream is not closed by the finally block new FileInputStream("C:\\test.txt"), "UTF-8"); System.out.println(reader.read()); } finally { if (reader != null) reader.close(); } } }
462
27.9375
69
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseReaderGood.java
public class CloseReaderFix { public static void main(String[] args) throws IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader("C:\\test.txt")); System.out.println(br.readLine()); } finally { if(br != null) br.close(); // 'br' is closed } // ... } }
311
21.285714
60
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseSql.java
public class CloseSql { public static void runQuery(Connection con, String query) throws SQLException { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { // process result set } } }
245
26.333333
80
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseWriterNestedGood.java
public class CloseWriterNestedFix { public static void main(String[] args) throws IOException { FileOutputStream fos = null; OutputStreamWriter writer = null; try { fos = new FileOutputStream("C:\\test.txt"); writer = new OutputStreamWriter(fos); writer.write("Hello world!"); } finally { if (writer != null) writer.close(); // 'writer' is closed if (fos != null) fos.close(); // 'fos' is closed } } }
440
24.941176
60
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseWriterGood.java
public class CloseWriterFix { public static void main(String[] args) throws IOException { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter("C:\\test.txt")); bw.write("Hello world!"); } finally { if(bw != null) bw.close(); // 'bw' is closed } // ... } }
302
20.642857
60
java
codeql
codeql-master/java/ql/src/Likely Bugs/Resource Leaks/CloseReaderNestedGood.java
public class CloseReaderNestedFix { public static void main(String[] args) throws IOException { FileInputStream fis = null; InputStreamReader reader = null; try { fis = new FileInputStream("C:\\test.txt"); reader = new InputStreamReader(fis); System.out.println(reader.read()); } finally { if (reader != null) reader.close(); // 'reader' is closed if (fis != null) fis.close(); // 'fis' is closed } } }
441
25
60
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/WriteOnlyContainerGood.java
private Set<Node> reachableNodes = new HashSet<Node>(); boolean reachable(Node n) { if (reachableNodes.contains(n)) return true; boolean reachable; if (n == ROOT) reachable = true; else reachable = reachable(n.getParent()); if (reachable) reachableNodes.add(n); return reachable; }
300
19.066667
55
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/RemoveTypeMismatch2.java
HashSet<Short> set = new HashSet<Short>(); short s = 1; set.add(s); // Following statement fails, because the argument is a literal int, which is auto-boxed // to an Integer set.remove(1); System.out.println(set); // Prints [1] // Following statement succeeds, because the argument is a literal int that is cast to a short, // which is auto-boxed to a Short set.remove((short)1); System.out.println(set); // Prints []
419
37.181818
96
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/ReadOnlyContainer.java
boolean containsDuplicates(Object[] array) { java.util.Set<Object> seen = new java.util.HashSet<Object>(); for (Object o : array) { if (seen.contains(o)) return true; } return false; }
193
23.25
62
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/ContainsTypeMismatch2.java
HashSet<Short> set = new HashSet<Short>(); short s = 1; set.add(s); // Following statement prints 'false', because the argument is a literal int, which is auto-boxed // to an Integer System.out.println(set.contains(1)); // Following statement prints 'true', because the argument is a literal int that is cast to a short, // which is auto-boxed to a Short System.out.println(set.contains((short)1));
400
39.1
101
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/ArrayIndexOutOfBoundsBad.java
for (int i = 0; i <= a.length; i++) { // BAD sum += a[i]; }
62
14.75
44
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/ArrayIndexOutOfBoundsGood.java
for (int i = 0; i < a.length; i++) { // GOOD sum += a[i]; }
62
14.75
44
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/ContainsTypeMismatch.java
void m(List<String> list) { if (list.contains(123)) { // Call 'contains' with non-string argument (without quotation marks) // ... } }
139
27
97
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/IteratorRemoveMayFail.java
import java.util.Arrays; import java.util.Iterator; import java.util.List; public class A { private List<Integer> l; public A(Integer... is) { this.l = Arrays.asList(is); } public List<Integer> getList() { return l; } public static void main(String[] args) { A a = new A(23, 42); for (Iterator<Integer> iter = a.getList().iterator(); iter.hasNext();) if (iter.next()%2 != 0) iter.remove(); } }
422
17.391304
72
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/WriteOnlyContainer.java
private Set<Node> reachableNodes = new HashSet<Node>(); boolean reachable(Node n) { boolean reachable; if (n == ROOT) reachable = true; else reachable = reachable(n.getParent()); if (reachable) reachableNodes.add(n); return reachable; }
248
19.75
55
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/RemoveTypeMismatch.java
void m(List<String> list) { if (list.remove(123)) { // Call 'remove' with non-string argument (without quotation marks) // ... } }
135
26.2
93
java
codeql
codeql-master/java/ql/src/Likely Bugs/Collections/IteratorRemoveMayFailGood.java
import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ArrayList; public class A { private List<Integer> l; public A(Integer... is) { this.l = new ArrayList<Integer>(Arrays.asList(is)); } public List<Integer> getList() { return l; } public static void main(String[] args) { A a = new A(23, 42); for (Iterator<Integer> iter = a.getList().iterator(); iter.hasNext();) if (iter.next()%2 != 0) iter.remove(); } }
474
18.791667
72
java
codeql
codeql-master/java/ql/src/Likely Bugs/I18N/MissingLocaleArgument.java
public static void main(String args[]) { String phrase = "I miss my home in Mississippi."; // AVOID: Calling 'toLowerCase()' or 'toUpperCase()' // produces different results depending on what the default locale is. System.out.println(phrase.toUpperCase()); System.out.println(phrase.toLowerCase()); // GOOD: Explicitly setting the locale when calling 'toLowerCase()' or // 'toUpperCase()' ensures that the resulting string is // English, regardless of the default locale. System.out.println(phrase.toLowerCase(Locale.ENGLISH)); System.out.println(phrase.toUpperCase(Locale.ENGLISH)); }
627
43.857143
74
java
codeql
codeql-master/java/ql/src/Likely Bugs/Finalization/NullifiedSuperFinalizeGuarded.java
class GuardedLocalCache { private Collection<NativeResource> localResources; // A finalizer guardian, which performs the finalize actions for 'GuardedLocalCache' // even if a subclass does not call 'super.finalize' in its 'finalize' method private Object finalizerGuardian = new Object() { protected void finalize() throws Throwable { for (NativeResource r : localResources) { r.dispose(); } }; }; }
418
33.916667
85
java
codeql
codeql-master/java/ql/src/Likely Bugs/Finalization/NullifiedSuperFinalize.java
class LocalCache { private Collection<NativeResource> localResources; //... protected void finalize() throws Throwable { for (NativeResource r : localResources) { r.dispose(); } }; } class WrongCache extends LocalCache { //... @Override protected void finalize() throws Throwable { // BAD: Empty 'finalize', which does not call 'super.finalize'. // Native resources in LocalCache are not disposed of. } } class RightCache extends LocalCache { //... @Override protected void finalize() throws Throwable { // GOOD: 'finalize' calls 'super.finalize'. // Native resources in LocalCache are disposed of. super.finalize(); } }
755
23.387097
71
java