code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public InnerClassAccess getInnerClassAccess(INVOKESTATIC inv, ConstantPoolGen cpg) throws ClassNotFoundException {
String methodName = inv.getMethodName(cpg);
if (methodName.startsWith("access$")) {
String className = inv.getClassName(cpg);
return getInnerClassAccess(className, methodName);
}
return null;
} | java |
private Map<String, InnerClassAccess> getAccessMapForClass(String className) throws ClassNotFoundException {
Map<String, InnerClassAccess> map = classToAccessMap.get(className);
if (map == null) {
map = new HashMap<>(3);
if (!className.startsWith("[")) {
JavaClass javaClass = Repository.lookupClass(className);
Method[] methodList = javaClass.getMethods();
for (Method method : methodList) {
String methodName = method.getName();
if (!methodName.startsWith("access$")) {
continue;
}
Code code = method.getCode();
if (code == null) {
continue;
}
if (DEBUG) {
System.out.println("Analyzing " + className + "." + method.getName()
+ " as an inner-class access method...");
}
byte[] instructionList = code.getCode();
String methodSig = method.getSignature();
InstructionCallback callback = new InstructionCallback(javaClass, methodName, methodSig, instructionList);
// try {
new BytecodeScanner().scan(instructionList, callback);
// } catch (LookupFailure lf) {
// throw lf.getException();
// }
InnerClassAccess access = callback.getAccess();
if (DEBUG) {
System.out.println((access != null ? "IS" : "IS NOT") + " an inner-class access method");
}
if (access != null) {
map.put(methodName, access);
}
}
}
if (map.size() == 0) {
map = Collections.emptyMap();
} else {
map = new HashMap<>(map);
}
classToAccessMap.put(className, map);
}
return map;
} | java |
public int getMnemonic() {
int mnemonic = KeyEvent.VK_UNDEFINED;
if (!MAC_OS_X) {
int index = getMnemonicIndex();
if ((index >= 0) && ((index + 1) < myAnnotatedString.length())) {
mnemonic = Character.toUpperCase(myAnnotatedString.charAt(index + 1));
}
}
return mnemonic;
} | java |
public static void localiseButton(AbstractButton button, String key, String defaultString, boolean setMnemonic) {
AnnotatedString as = new AnnotatedString(L10N.getLocalString(key, defaultString));
button.setText(as.toString());
int mnemonic;
if (setMnemonic && (mnemonic = as.getMnemonic()) != KeyEvent.VK_UNDEFINED) {
button.setMnemonic(mnemonic);
button.setDisplayedMnemonicIndex(as.getMnemonicIndex());
}
} | java |
public MethodHash computeHash(Method method) {
final MessageDigest digest = Util.getMD5Digest();
byte[] code;
if (method.getCode() == null || method.getCode().getCode() == null) {
code = new byte[0];
} else {
code = method.getCode().getCode();
}
BytecodeScanner.Callback callback = (opcode, index) -> digest.update((byte) opcode);
BytecodeScanner bytecodeScanner = new BytecodeScanner();
bytecodeScanner.scan(code, callback);
hash = digest.digest();
return this;
} | java |
static int compareGroups(BugGroup m1, BugGroup m2) {
int result = m1.compareTo(m2);
if (result == 0) {
return m1.getShortDescription().compareToIgnoreCase(m2.getShortDescription());
}
return result;
} | java |
static int compareMarkers(IMarker m1, IMarker m2) {
if (m1 == null || m2 == null || !m1.exists() || !m2.exists()) {
return 0;
}
int rank1 = MarkerUtil.findBugRankForMarker(m1);
int rank2 = MarkerUtil.findBugRankForMarker(m2);
int result = rank1 - rank2;
if (result != 0) {
return result;
}
int prio1 = MarkerUtil.findConfidenceForMarker(m1).ordinal();
int prio2 = MarkerUtil.findConfidenceForMarker(m2).ordinal();
result = prio1 - prio2;
if (result != 0) {
return result;
}
String a1 = m1.getAttribute(IMarker.MESSAGE, "");
String a2 = m2.getAttribute(IMarker.MESSAGE, "");
return a1.compareToIgnoreCase(a2);
} | java |
public void setParamsWithProperty(BitSet nonNullSet) {
for (int i = 0; i < 32; ++i) {
setParamWithProperty(i, nonNullSet.get(i));
}
} | java |
public void setParamWithProperty(int param, boolean hasProperty) {
if (param < 0 || param > 31) {
return;
}
if (hasProperty) {
bits |= (1 << param);
} else {
bits &= ~(1 << param);
}
} | java |
public BitSet getMatchingParameters(BitSet nullArgSet) {
BitSet result = new BitSet();
for (int i = 0; i < 32; ++i) {
result.set(i, nullArgSet.get(i) && hasProperty(i));
}
return result;
} | java |
public static int getNumParametersForInvocation(InvokeInstruction inv, ConstantPoolGen cpg) {
SignatureParser sigParser = new SignatureParser(inv.getSignature(cpg));
return sigParser.getNumParameters();
} | java |
public void build() {
int numGood = 0, numBytecodes = 0;
if (DEBUG) {
System.out.println("Method: " + methodGen.getName() + " - " + methodGen.getSignature() + "in class "
+ methodGen.getClassName());
}
// Associate line number information with each InstructionHandle
LineNumberTable table = methodGen.getLineNumberTable(methodGen.getConstantPool());
if (table != null && table.getTableLength() > 0) {
checkTable(table);
InstructionHandle handle = methodGen.getInstructionList().getStart();
while (handle != null) {
int bytecodeOffset = handle.getPosition();
if (bytecodeOffset < 0) {
throw new IllegalStateException("Bad bytecode offset: " + bytecodeOffset);
}
if (DEBUG) {
System.out.println("Looking for source line for bytecode offset " + bytecodeOffset);
}
int sourceLine;
try {
sourceLine = table.getSourceLine(bytecodeOffset);
} catch (ArrayIndexOutOfBoundsException e) {
if (LINE_NUMBER_BUG) {
throw e;
} else {
sourceLine = -1;
}
}
if (sourceLine >= 0) {
++numGood;
}
lineNumberMap.put(handle, new LineNumber(bytecodeOffset, sourceLine));
handle = handle.getNext();
++numBytecodes;
}
hasLineNumbers = true;
if (DEBUG) {
System.out.println("\t" + numGood + "/" + numBytecodes + " had valid line numbers");
}
}
} | java |
public void setReturnValue(MethodDescriptor methodDesc, TypeQualifierValue<?> tqv, TypeQualifierAnnotation tqa) {
Map<TypeQualifierValue<?>, TypeQualifierAnnotation> map = returnValueMap.get(methodDesc);
if (map == null) {
map = new HashMap<>();
returnValueMap.put(methodDesc, map);
}
map.put(tqv, tqa);
if (DEBUG) {
System.out.println("tqdb: " + methodDesc + " for " + tqv + " ==> " + tqa);
}
} | java |
public TypeQualifierAnnotation getReturnValue(MethodDescriptor methodDesc, TypeQualifierValue<?> tqv) {
//
// TODO: handling of overridden methods?
//
Map<TypeQualifierValue<?>, TypeQualifierAnnotation> map = returnValueMap.get(methodDesc);
if (map == null) {
return null;
}
return map.get(tqv);
} | java |
public void setParameter(MethodDescriptor methodDesc, int param, TypeQualifierValue<?> tqv, TypeQualifierAnnotation tqa) {
Map<TypeQualifierValue<?>, TypeQualifierAnnotation> map = parameterMap.get(methodDesc, param);
if (map == null) {
map = new HashMap<>();
parameterMap.put(methodDesc, param, map);
}
map.put(tqv, tqa);
if (DEBUG) {
System.out.println("tqdb: " + methodDesc + " parameter " + param + " for " + tqv + " ==> " + tqa);
}
} | java |
public TypeQualifierAnnotation getParameter(MethodDescriptor methodDesc, int param, TypeQualifierValue<?> tqv) {
//
// TODO: handling of overridden methods?
//
Map<TypeQualifierValue<?>, TypeQualifierAnnotation> map = parameterMap.get(methodDesc, param);
if (map == null) {
return null;
}
return map.get(tqv);
} | java |
protected static boolean isLongOrDouble(FieldInstruction fieldIns, ConstantPoolGen cpg) {
Type type = fieldIns.getFieldType(cpg);
int code = type.getType();
return code == Const.T_LONG || code == Const.T_DOUBLE;
} | java |
protected static Variable snarfFieldValue(FieldInstruction fieldIns, ConstantPoolGen cpg, ValueNumberFrame frame)
throws DataflowAnalysisException {
if (isLongOrDouble(fieldIns, cpg)) {
int numSlots = frame.getNumSlots();
ValueNumber topValue = frame.getValue(numSlots - 1);
ValueNumber nextValue = frame.getValue(numSlots - 2);
return new LongOrDoubleLocalVariable(topValue, nextValue);
} else {
return new LocalVariable(frame.getTopValue());
}
} | java |
public static Collection<TypeQualifierValue<?>> getRelevantTypeQualifiers(MethodDescriptor methodDescriptor, CFG cfg)
throws CheckedAnalysisException {
final HashSet<TypeQualifierValue<?>> result = new HashSet<>();
XMethod xmethod = XFactory.createXMethod(methodDescriptor);
if (FIND_EFFECTIVE_RELEVANT_QUALIFIERS) {
if (DEBUG_FIND_EFFECTIVE_RELEVANT_QUALIFIERS) {
System.out.println("**** Finding effective type qualifiers for " + xmethod);
}
//
// This will take care of methods using fields annotated with
// a type qualifier.
//
getDirectlyRelevantTypeQualifiers(xmethod, result);
// For all known type qualifiers, find the effective (direct,
// inherited,
// or default) type qualifier annotations
// on the method and all methods directly called by the method.
//
addEffectiveRelevantQualifiers(result, xmethod);
IAnalysisCache analysisCache = Global.getAnalysisCache();
ConstantPoolGen cpg = analysisCache.getClassAnalysis(ConstantPoolGen.class, methodDescriptor.getClassDescriptor());
for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
Location location = i.next();
Instruction ins = location.getHandle().getInstruction();
if (ins instanceof InvokeInstruction) {
if (ins instanceof INVOKEDYNAMIC) {
// TODO handle INVOKEDYNAMIC
} else {
XMethod called = XFactory.createXMethod((InvokeInstruction) ins, cpg);
addEffectiveRelevantQualifiers(result, called);
}
}
if (DEBUG_FIND_EFFECTIVE_RELEVANT_QUALIFIERS) {
System.out.println("===> result: " + result);
}
}
//
// XXX: this code can go away eventually
//
if (!methodDescriptor.isStatic()) {
// Instance method - must consider type qualifiers inherited
// from superclasses
SupertypeTraversalVisitor visitor = new OverriddenMethodsVisitor(xmethod) {
/*
* (non-Javadoc)
*
* @see edu.umd.cs.findbugs.ba.ch.OverriddenMethodsVisitor#
* visitOverriddenMethod(edu.umd.cs.findbugs.ba.XMethod)
*/
@Override
protected boolean visitOverriddenMethod(XMethod xmethod) {
getDirectlyRelevantTypeQualifiers(xmethod, result);
return true;
}
};
try {
AnalysisContext.currentAnalysisContext().getSubtypes2()
.traverseSupertypesDepthFirst(xmethod.getClassDescriptor(), visitor);
} catch (ClassNotFoundException e) {
AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(e);
return Collections.<TypeQualifierValue<?>> emptySet();
} catch (UncheckedAnalysisException e) {
AnalysisContext.currentAnalysisContext().getLookupFailureCallback()
.logError("Error getting relevant type qualifiers for " + xmethod.toString(), e);
return Collections.<TypeQualifierValue<?>> emptySet();
}
}
}
return result;
} | java |
public static ClassDescriptor createClassDescriptorFromResourceName(String resourceName) {
if (!isClassResource(resourceName)) {
throw new IllegalArgumentException("Resource " + resourceName + " is not a class");
}
return createClassDescriptor(resourceName.substring(0, resourceName.length() - 6));
} | java |
public static @CheckForNull
ClassDescriptor createClassDescriptorFromFieldSignature(String signature) {
int start = signature.indexOf('L');
if (start < 0) {
return null;
}
int end = signature.indexOf(';', start);
if (end < 0) {
return null;
}
return createClassDescriptor(signature.substring(start + 1, end));
} | java |
public void setPluginList(Path src) {
if (pluginList == null) {
pluginList = src;
} else {
pluginList.append(src);
}
} | java |
public void addAllowedClass(String className) {
String classRegex = START + dotsToRegex(className) + ".class$";
LOG.debug("Class regex: {}", classRegex);
patternList.add(Pattern.compile(classRegex).matcher(""));
} | java |
public void addAllowedPackage(String packageName) {
if (packageName.endsWith(".")) {
packageName = packageName.substring(0, packageName.length() - 1);
}
String packageRegex = START + dotsToRegex(packageName) + SEP + JAVA_IDENTIFIER_PART + "+.class$";
LOG.debug("Package regex: {}", packageRegex);
patternList.add(Pattern.compile(packageRegex).matcher(""));
} | java |
public void addAllowedPrefix(String prefix) {
if (prefix.endsWith(".")) {
prefix = prefix.substring(0, prefix.length() - 1);
}
LOG.debug("Allowed prefix: {}", prefix);
String packageRegex = START + dotsToRegex(prefix) + SEP;
LOG.debug("Prefix regex: {}", packageRegex);
patternList.add(Pattern.compile(packageRegex).matcher(""));
} | java |
@Deprecated
public @Nonnull
String getMessage(String key) {
BugPattern bugPattern = DetectorFactoryCollection.instance().lookupBugPattern(key);
if (bugPattern == null) {
return L10N.getLocalString("err.missing_pattern", "Error: missing bug pattern for key") + " " + key;
}
return bugPattern.getAbbrev() + ": " + bugPattern.getLongDescription();
} | java |
public @Nonnull
String getDetailHTML(String key) {
BugPattern bugPattern = DetectorFactoryCollection.instance().lookupBugPattern(key);
if (bugPattern == null) {
return L10N.getLocalString("err.missing_pattern", "Error: missing bug pattern for key") + " " + key;
}
return bugPattern.getDetailHTML();
} | java |
public String getAnnotationDescription(String key) {
try {
return annotationDescriptionBundle.getString(key);
} catch (MissingResourceException mre) {
if (DEBUG) {
return "TRANSLATE(" + key + ") (param={0}}";
} else {
try {
return englishAnnotationDescriptionBundle.getString(key);
} catch (MissingResourceException mre2) {
return key + " {0}";
}
}
}
} | java |
public String getBugCategoryDescription(String category) {
BugCategory bc = DetectorFactoryCollection.instance().getBugCategory(category);
return (bc != null ? bc.getShortDescription() : category);
} | java |
JPanel createSourceCodePanel() {
Font sourceFont = new Font("Monospaced", Font.PLAIN, (int) Driver.getFontSize());
mainFrame.getSourceCodeTextPane().setFont(sourceFont);
mainFrame.getSourceCodeTextPane().setEditable(false);
mainFrame.getSourceCodeTextPane().getCaret().setSelectionVisible(true);
mainFrame.getSourceCodeTextPane().setDocument(SourceCodeDisplay.SOURCE_NOT_RELEVANT);
JScrollPane sourceCodeScrollPane = new JScrollPane(mainFrame.getSourceCodeTextPane());
sourceCodeScrollPane.getVerticalScrollBar().setUnitIncrement(20);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(sourceCodeScrollPane, BorderLayout.CENTER);
panel.revalidate();
if (MainFrame.GUI2_DEBUG) {
System.out.println("Created source code panel");
}
return panel;
} | java |
public void scrollLineToVisible(int line, int margin) {
int maxMargin = (parentHeight() - 20) / 2;
if (margin > maxMargin) {
margin = Math.max(0, maxMargin);
}
scrollLineToVisibleImpl(line, margin);
} | java |
public void scrollLinesToVisible(int startLine, int endLine, Collection<Integer> otherLines) {
int startY, endY;
try {
startY = lineToY(startLine);
} catch (BadLocationException ble) {
if (MainFrame.GUI2_DEBUG) {
ble.printStackTrace();
}
return; // give up
}
try {
endY = lineToY(endLine);
} catch (BadLocationException ble) {
endY = startY; // better than nothing
}
int max = parentHeight() - 0;
if (endY - startY > max) {
endY = startY + max;
} else if (otherLines != null && otherLines.size() > 0) {
int origin = startY + endY / 2;
PriorityQueue<Integer> pq = new PriorityQueue<>(otherLines.size(), new DistanceComparator(origin));
for (int line : otherLines) {
int otherY;
try {
otherY = lineToY(line);
} catch (BadLocationException ble) {
continue; // give up on this one
}
pq.add(otherY);
}
while (!pq.isEmpty()) {
int y = pq.remove();
int lo = Math.min(startY, y);
int hi = Math.max(endY, y);
if (hi - lo > max) {
break;
} else {
startY = lo;
endY = hi;
}
}
}
if (endY - startY > max) {
endY = startY + max;
}
scrollYToVisibleImpl((startY + endY) / 2, max / 2);
} | java |
private void examineBasicBlocks() throws DataflowAnalysisException, CFGBuilderException {
// Look for null check blocks where the reference being checked
// is definitely null, or null on some path
Iterator<BasicBlock> bbIter = invDataflow.getCFG().blockIterator();
while (bbIter.hasNext()) {
BasicBlock basicBlock = bbIter.next();
if (basicBlock.isNullCheck()) {
analyzeNullCheck(invDataflow, basicBlock);
} else if (!basicBlock.isEmpty()) {
// Look for all reference comparisons where
// - both values compared are definitely null, or
// - one value is definitely null and one is definitely not null
// These cases are not null dereferences,
// but they are quite likely to indicate an error, so while
// we've got
// information about null values, we may as well report them.
InstructionHandle lastHandle = basicBlock.getLastInstruction();
Instruction last = lastHandle.getInstruction();
switch (last.getOpcode()) {
case Const.IF_ACMPEQ:
case Const.IF_ACMPNE:
analyzeRefComparisonBranch(basicBlock, lastHandle);
break;
case Const.IFNULL:
case Const.IFNONNULL:
analyzeIfNullBranch(basicBlock, lastHandle);
break;
default:
break;
}
}
}
} | java |
private void examineNullValues() throws CFGBuilderException, DataflowAnalysisException {
Set<LocationWhereValueBecomesNull> locationWhereValueBecomesNullSet = invDataflow.getAnalysis()
.getLocationWhereValueBecomesNullSet();
if (DEBUG_DEREFS) {
System.out.println("----------------------- examineNullValues " + locationWhereValueBecomesNullSet.size());
}
Map<ValueNumber, SortedSet<Location>> bugStatementLocationMap = new HashMap<>();
// Inspect the method for locations where a null value is guaranteed to
// be dereferenced. Add the dereference locations
Map<ValueNumber, NullValueUnconditionalDeref> nullValueGuaranteedDerefMap = new HashMap<>();
// Check every location
CFG cfg = classContext.getCFG(method);
for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
Location location = i.next();
if (DEBUG_DEREFS) {
System.out.println("At location " + location);
}
checkForUnconditionallyDereferencedNullValues(location, bugStatementLocationMap, nullValueGuaranteedDerefMap,
vnaDataflow.getFactAtLocation(location), invDataflow.getFactAtLocation(location),
uvdDataflow.getFactAfterLocation(location), false);
}
HashSet<ValueNumber> npeIfStatementCovered = new HashSet<>(nullValueGuaranteedDerefMap.keySet());
Map<ValueNumber, SortedSet<Location>> bugEdgeLocationMap = new HashMap<>();
checkEdges(cfg, nullValueGuaranteedDerefMap, bugEdgeLocationMap);
Map<ValueNumber, SortedSet<Location>> bugLocationMap = bugEdgeLocationMap;
bugLocationMap.putAll(bugStatementLocationMap);
// For each value number that is null somewhere in the
// method, collect the set of locations where it becomes null.
// FIXME: we may see some locations that are not guaranteed to be
// dereferenced (how to fix this?)
Map<ValueNumber, Set<Location>> nullValueAssignmentMap = findNullAssignments(locationWhereValueBecomesNullSet);
reportBugs(nullValueGuaranteedDerefMap, npeIfStatementCovered, bugLocationMap, nullValueAssignmentMap);
} | java |
private void noteUnconditionallyDereferencedNullValue(Location thisLocation,
Map<ValueNumber, SortedSet<Location>> bugLocations,
Map<ValueNumber, NullValueUnconditionalDeref> nullValueGuaranteedDerefMap, UnconditionalValueDerefSet derefSet,
IsNullValue isNullValue, ValueNumber valueNumber) {
if (DEBUG) {
System.out.println("%%% HIT for value number " + valueNumber + " @ " + thisLocation);
}
Set<Location> unconditionalDerefLocationSet = derefSet.getUnconditionalDerefLocationSet(valueNumber);
if (unconditionalDerefLocationSet.isEmpty()) {
AnalysisContext.logError("empty set of unconditionally dereferenced locations at "
+ thisLocation.getHandle().getPosition() + " in " + classContext.getClassDescriptor() + "."
+ method.getName() + method.getSignature());
return;
}
// OK, we have a null value that is unconditionally
// derferenced. Make a note of the locations where it
// will be dereferenced.
NullValueUnconditionalDeref thisNullValueDeref = nullValueGuaranteedDerefMap.get(valueNumber);
if (thisNullValueDeref == null) {
thisNullValueDeref = new NullValueUnconditionalDeref();
nullValueGuaranteedDerefMap.put(valueNumber, thisNullValueDeref);
}
thisNullValueDeref.add(isNullValue, unconditionalDerefLocationSet);
if (thisLocation != null) {
SortedSet<Location> locationsForThisBug = bugLocations.get(valueNumber);
if (locationsForThisBug == null) {
locationsForThisBug = new TreeSet<>();
bugLocations.put(valueNumber, locationsForThisBug);
}
locationsForThisBug.add(thisLocation);
}
} | java |
private void examineRedundantBranches() {
for (RedundantBranch redundantBranch : redundantBranchList) {
if (DEBUG) {
System.out.println("Redundant branch: " + redundantBranch);
}
int lineNumber = redundantBranch.lineNumber;
// The source to bytecode compiler may sometimes duplicate blocks of
// code along different control paths. So, to report the bug,
// we check to ensure that the branch is REALLY determined each
// place it is duplicated, and that it is determined in the same
// way.
boolean confused = undeterminedBranchSet.get(lineNumber)
|| (definitelySameBranchSet.get(lineNumber) && definitelyDifferentBranchSet.get(lineNumber));
// confused if there is JSR confusion or multiple null checks with
// different results on the same line
boolean reportIt = true;
if (lineMentionedMultipleTimes.get(lineNumber) && confused) {
reportIt = false;
} else if (redundantBranch.location.getBasicBlock().isInJSRSubroutine() /*
* occurs
* in
* a
* JSR
*/
&& confused) {
reportIt = false;
} else {
int pc = redundantBranch.location.getHandle().getPosition();
for (CodeException e : method.getCode().getExceptionTable()) {
if (e.getCatchType() == 0 && e.getStartPC() != e.getHandlerPC() && e.getEndPC() <= pc
&& pc <= e.getEndPC() + 5) {
reportIt = false;
}
}
}
if (reportIt) {
collector.foundRedundantNullCheck(redundantBranch.location, redundantBranch);
}
}
} | java |
private void analyzeIfNullBranch(BasicBlock basicBlock, InstructionHandle lastHandle) throws DataflowAnalysisException {
Location location = new Location(lastHandle, basicBlock);
IsNullValueFrame frame = invDataflow.getFactAtLocation(location);
if (!frame.isValid()) {
// This is probably dead code due to an infeasible exception edge.
return;
}
IsNullValue top = frame.getTopValue();
// Find the line number.
int lineNumber = getLineNumber(method, lastHandle);
if (lineNumber < 0) {
return;
}
if (!(top.isDefinitelyNull() || top.isDefinitelyNotNull())) {
if (DEBUG) {
System.out.println("Line " + lineNumber + " undetermined");
}
undeterminedBranchSet.set(lineNumber);
return;
}
// Figure out if the branch is always taken
// or always not taken.
short opcode = lastHandle.getInstruction().getOpcode();
boolean definitelySame = top.isDefinitelyNull();
if (opcode != Const.IFNULL) {
definitelySame = !definitelySame;
}
if (definitelySame) {
if (DEBUG) {
System.out.println("Line " + lineNumber + " always same");
}
definitelySameBranchSet.set(lineNumber);
} else {
if (DEBUG) {
System.out.println("Line " + lineNumber + " always different");
}
definitelyDifferentBranchSet.set(lineNumber);
}
RedundantBranch redundantBranch = new RedundantBranch(location, lineNumber, top);
// Determine which control edge is made infeasible by the redundant
// comparison
boolean wantNull = (opcode == Const.IFNULL);
int infeasibleEdgeType = (wantNull == top.isDefinitelyNull()) ? EdgeTypes.FALL_THROUGH_EDGE : EdgeTypes.IFCMP_EDGE;
Edge infeasibleEdge = invDataflow.getCFG().getOutgoingEdgeWithType(basicBlock, infeasibleEdgeType);
redundantBranch.setInfeasibleEdge(infeasibleEdge);
if (DEBUG) {
System.out.println("Adding redundant branch: " + redundantBranch);
}
redundantBranchList.add(redundantBranch);
} | java |
public @Nonnull BugPattern getBugPattern() {
BugPattern result = DetectorFactoryCollection.instance().lookupBugPattern(getType());
if (result != null) {
return result;
}
AnalysisContext.logError("Unable to find description of bug pattern " + getType());
result = DetectorFactoryCollection.instance().lookupBugPattern("UNKNOWN");
if (result != null) {
return result;
}
return BugPattern.REALLY_UNKNOWN;
} | java |
@CheckForNull
private <T extends BugAnnotation> T findPrimaryAnnotationOfType(Class<T> cls) {
T firstMatch = null;
for (Iterator<BugAnnotation> i = annotationIterator(); i.hasNext();) {
BugAnnotation annotation = i.next();
if (cls.isAssignableFrom(annotation.getClass())) {
if (annotation.getDescription().endsWith("DEFAULT")) {
return cls.cast(annotation);
} else if (firstMatch == null) {
firstMatch = cls.cast(annotation);
}
}
}
return firstMatch;
} | java |
public @CheckForNull <A extends BugAnnotation> A getAnnotationWithRole(Class<A> c, String role) {
for(BugAnnotation a : annotationList) {
if (c.isInstance(a) && Objects.equals(role, a.getDescription())) {
return c.cast(a);
}
}
return null;
} | java |
public String getProperty(String name) {
BugProperty prop = lookupProperty(name);
return prop != null ? prop.getValue() : null;
} | java |
public String getProperty(String name, String defaultValue) {
String value = getProperty(name);
return value != null ? value : defaultValue;
} | java |
@Nonnull
public BugInstance setProperty(String name, String value) {
BugProperty prop = lookupProperty(name);
if (prop != null) {
prop.setValue(value);
} else {
prop = new BugProperty(name, value);
addProperty(prop);
}
return this;
} | java |
public BugProperty lookupProperty(String name) {
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name)) {
break;
}
prop = prop.getNext();
}
return prop;
} | java |
public boolean deleteProperty(String name) {
BugProperty prev = null;
BugProperty prop = propertyListHead;
while (prop != null) {
if (prop.getName().equals(name)) {
break;
}
prev = prop;
prop = prop.getNext();
}
if (prop != null) {
if (prev != null) {
// Deleted node in interior or at tail of list
prev.setNext(prop.getNext());
} else {
// Deleted node at head of list
propertyListHead = prop.getNext();
}
if (prop.getNext() == null) {
// Deleted node at end of list
propertyListTail = prev;
}
return true;
} else {
// No such property
return false;
}
} | java |
@Nonnull
public BugInstance addAnnotations(Collection<? extends BugAnnotation> annotationCollection) {
for (BugAnnotation annotation : annotationCollection) {
add(annotation);
}
return this;
} | java |
@Nonnull
public BugInstance addClassAndMethod(PreorderVisitor visitor) {
addClass(visitor);
XMethod m = visitor.getXMethod();
addMethod(visitor);
if (!MemberUtils.isUserGenerated(m)) {
foundInAutogeneratedMethod();
}
return this;
} | java |
@Nonnull
public BugInstance addClassAndMethod(JavaClass javaClass, Method method) {
addClass(javaClass.getClassName());
addMethod(javaClass, method);
if (!MemberUtils.isUserGenerated(method)) {
foundInAutogeneratedMethod();
}
return this;
} | java |
@Nonnull
public BugInstance addClass(ClassNode classNode) {
String dottedClassName = ClassName.toDottedClassName(classNode.name);
ClassAnnotation classAnnotation = new ClassAnnotation(dottedClassName);
add(classAnnotation);
return this;
} | java |
@Nonnull
public BugInstance addClass(PreorderVisitor visitor) {
String className = visitor.getDottedClassName();
addClass(className);
return this;
} | java |
@Nonnull
public BugInstance addSuperclass(PreorderVisitor visitor) {
String className = ClassName.toDottedClassName(visitor.getSuperclassName());
addClass(className);
return this;
} | java |
@Nonnull
public BugInstance addType(String typeDescriptor) {
TypeAnnotation typeAnnotation = new TypeAnnotation(typeDescriptor);
add(typeAnnotation);
return this;
} | java |
@Nonnull
public BugInstance addField(String className, String fieldName, String fieldSig, boolean isStatic) {
addField(new FieldAnnotation(className, fieldName, fieldSig, isStatic));
return this;
} | java |
@Nonnull
public BugInstance addField(FieldVariable field) {
return addField(field.getClassName(), field.getFieldName(), field.getFieldSig(), field.isStatic());
} | java |
@Nonnull
public BugInstance addField(FieldDescriptor fieldDescriptor) {
FieldAnnotation fieldAnnotation = FieldAnnotation.fromFieldDescriptor(fieldDescriptor);
add(fieldAnnotation);
return this;
} | java |
@Nonnull
public BugInstance addVisitedField(PreorderVisitor visitor) {
FieldAnnotation f = FieldAnnotation.fromVisitedField(visitor);
addField(f);
return this;
} | java |
@Nonnull
public BugInstance addOptionalLocalVariable(DismantleBytecode dbc, OpcodeStack.Item item) {
int register = item.getRegisterNumber();
if (register >= 0) {
this.add(LocalVariableAnnotation.getLocalVariableAnnotation(dbc.getMethod(), register, dbc.getPC() - 1, dbc.getPC()));
}
return this;
} | java |
@Nonnull
public BugInstance addMethod(PreorderVisitor visitor) {
MethodAnnotation methodAnnotation = MethodAnnotation.fromVisitedMethod(visitor);
addMethod(methodAnnotation);
addSourceLinesForMethod(methodAnnotation, SourceLineAnnotation.fromVisitedMethod(visitor));
return this;
} | java |
@Nonnull
public BugInstance addCalledMethod(DismantleBytecode visitor) {
return addMethod(MethodAnnotation.fromCalledMethod(visitor)).describe(MethodAnnotation.METHOD_CALLED);
} | java |
@Nonnull
public BugInstance addCalledMethod(String className, String methodName, String methodSig, boolean isStatic) {
return addMethod(MethodAnnotation.fromCalledMethod(className, methodName, methodSig, isStatic)).describe(
MethodAnnotation.METHOD_CALLED);
} | java |
@Nonnull
public BugInstance addParameterAnnotation(int index, String role) {
return addInt(index + 1).describe(role);
} | java |
@Nonnull
public BugInstance addString(char c) {
add(StringAnnotation.fromRawString(Character.toString(c)));
return this;
} | java |
@Nonnull
public BugInstance addSourceLine(ClassContext classContext, MethodGen methodGen, String sourceFile, InstructionHandle start,
InstructionHandle end) {
// Make sure start and end are really in the right order.
if (start.getPosition() > end.getPosition()) {
InstructionHandle tmp = start;
start = end;
end = tmp;
}
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstructionRange(classContext, methodGen,
sourceFile, start, end);
if (sourceLineAnnotation != null) {
add(sourceLineAnnotation);
}
return this;
} | java |
@Nonnull
public BugInstance addUnknownSourceLine(String className, String sourceFile) {
SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.createUnknown(className, sourceFile);
if (sourceLineAnnotation != null) {
add(sourceLineAnnotation);
}
return this;
} | java |
@Nonnull
public BugInstance describe(String description) {
annotationList.get(annotationList.size() - 1).setDescription(description);
return this;
} | java |
public ExceptionSet getEdgeExceptionSet(Edge edge) {
CachedExceptionSet cachedExceptionSet = thrownExceptionSetMap.get(edge.getSource());
return cachedExceptionSet.getEdgeExceptionSet(edge);
} | java |
private CachedExceptionSet getCachedExceptionSet(BasicBlock basicBlock) {
CachedExceptionSet cachedExceptionSet = thrownExceptionSetMap.get(basicBlock);
if (cachedExceptionSet == null) {
// When creating the cached exception type set for the first time:
// - the block result is set to TOP, so it won't match
// any block result that has actually been computed
// using the analysis transfer function
// - the exception set is created as empty (which makes it
// return TOP as its common superclass)
TypeFrame top = createFact();
makeFactTop(top);
cachedExceptionSet = new CachedExceptionSet(top, exceptionSetFactory.createExceptionSet());
thrownExceptionSetMap.put(basicBlock, cachedExceptionSet);
}
return cachedExceptionSet;
} | java |
private CachedExceptionSet computeBlockExceptionSet(BasicBlock basicBlock, TypeFrame result) throws DataflowAnalysisException {
ExceptionSet exceptionSet = computeThrownExceptionTypes(basicBlock);
TypeFrame copyOfResult = createFact();
copy(result, copyOfResult);
CachedExceptionSet cachedExceptionSet = new CachedExceptionSet(copyOfResult, exceptionSet);
thrownExceptionSetMap.put(basicBlock, cachedExceptionSet);
return cachedExceptionSet;
} | java |
private ExceptionSet computeEdgeExceptionSet(Edge edge, ExceptionSet thrownExceptionSet) {
if (thrownExceptionSet.isEmpty()) {
return thrownExceptionSet;
}
ExceptionSet result = exceptionSetFactory.createExceptionSet();
if (edge.getType() == UNHANDLED_EXCEPTION_EDGE) {
// The unhandled exception edge always comes
// after all of the handled exception edges.
result.addAll(thrownExceptionSet);
thrownExceptionSet.clear();
return result;
}
BasicBlock handlerBlock = edge.getTarget();
CodeExceptionGen handler = handlerBlock.getExceptionGen();
ObjectType catchType = handler.getCatchType();
if (Hierarchy.isUniversalExceptionHandler(catchType)) {
result.addAll(thrownExceptionSet);
thrownExceptionSet.clear();
} else {
// Go through the set of thrown exceptions.
// Any that will DEFINITELY be caught be this handler, remove.
// Any that MIGHT be caught, but won't definitely be caught,
// remain.
for (ExceptionSet.ThrownExceptionIterator i = thrownExceptionSet.iterator(); i.hasNext();) {
// ThrownException thrownException = i.next();
ObjectType thrownType = i.next();
boolean explicit = i.isExplicit();
if (DEBUG) {
System.out.println("\texception type " + thrownType + ", catch type " + catchType);
}
try {
if (Hierarchy.isSubtype(thrownType, catchType)) {
// Exception can be thrown along this edge
result.add(thrownType, explicit);
// And it will definitely be caught
i.remove();
if (DEBUG) {
System.out.println("\tException is subtype of catch type: " + "will definitely catch");
}
} else if (Hierarchy.isSubtype(catchType, thrownType)) {
// Exception possibly thrown along this edge
result.add(thrownType, explicit);
if (DEBUG) {
System.out.println("\tException is supertype of catch type: " + "might catch");
}
}
} catch (ClassNotFoundException e) {
// As a special case, if a class hierarchy lookup
// fails, then we will conservatively assume that the
// exception in question CAN, but WON'T NECESSARILY
// be caught by the handler.
AnalysisContext.reportMissingClass(e);
result.add(thrownType, explicit);
}
}
}
return result;
} | java |
private ExceptionSet computeThrownExceptionTypes(BasicBlock basicBlock) throws
DataflowAnalysisException {
ExceptionSet exceptionTypeSet = exceptionSetFactory.createExceptionSet();
InstructionHandle pei = basicBlock.getExceptionThrower();
Instruction ins = pei.getInstruction();
// Get the exceptions that BCEL knows about.
// Note that all of these are unchecked.
ExceptionThrower exceptionThrower = (ExceptionThrower) ins;
Class<?>[] exceptionList = exceptionThrower.getExceptions();
for (Class<?> aExceptionList : exceptionList) {
exceptionTypeSet.addImplicit(ObjectTypeFactory.getInstance(aExceptionList.getName()));
}
// Assume that an Error may be thrown by any instruction.
exceptionTypeSet.addImplicit(Hierarchy.ERROR_TYPE);
if (ins instanceof ATHROW) {
// For ATHROW instructions, we generate *two* blocks
// for which the ATHROW is an exception thrower.
//
// - The first, empty basic block, does the null check
// - The second block, which actually contains the ATHROW,
// throws the object on the top of the operand stack
//
// We make a special case of the block containing the ATHROW,
// by removing all of the implicit exceptions,
// and using type information to figure out what is thrown.
if (basicBlock.containsInstruction(pei)) {
// This is the actual ATHROW, not the null check
// and implicit exceptions.
exceptionTypeSet.clear();
// The frame containing the thrown value is the start fact
// for the block, because ATHROW is guaranteed to be
// the only instruction in the block.
TypeFrame frame = getStartFact(basicBlock);
// Check whether or not the frame is valid.
// Sun's javac sometimes emits unreachable code.
// For example, it will emit code that follows a JSR
// subroutine call that never returns.
// If the frame is invalid, then we can just make
// a conservative assumption that anything could be
// thrown at this ATHROW.
if (!frame.isValid()) {
exceptionTypeSet.addExplicit(Type.THROWABLE);
} else if (frame.getStackDepth() == 0) {
throw new IllegalStateException("empty stack " + " thrown by " + pei + " in "
+ SignatureConverter.convertMethodSignature(methodGen));
} else {
Type throwType = frame.getTopValue();
if (throwType instanceof ObjectType) {
exceptionTypeSet.addExplicit((ObjectType) throwType);
} else if (throwType instanceof ExceptionObjectType) {
exceptionTypeSet.addAll(((ExceptionObjectType) throwType).getExceptionSet());
} else {
// Not sure what is being thrown here.
// Be conservative.
if (DEBUG) {
System.out.println("Non object type " + throwType + " thrown by " + pei + " in "
+ SignatureConverter.convertMethodSignature(methodGen));
}
exceptionTypeSet.addExplicit(Type.THROWABLE);
}
}
}
}
// If it's an InvokeInstruction, add declared exceptions and
// RuntimeException
if (ins instanceof InvokeInstruction) {
ConstantPoolGen cpg = methodGen.getConstantPool();
InvokeInstruction inv = (InvokeInstruction) ins;
ObjectType[] declaredExceptionList = Hierarchy2.findDeclaredExceptions(inv, cpg);
if (declaredExceptionList == null) {
// Couldn't find declared exceptions,
// so conservatively assume it could thrown any checked
// exception.
if (DEBUG) {
System.out.println("Couldn't find declared exceptions for "
+ SignatureConverter.convertMethodSignature(inv, cpg));
}
exceptionTypeSet.addExplicit(Hierarchy.EXCEPTION_TYPE);
} else {
for (ObjectType aDeclaredExceptionList : declaredExceptionList) {
exceptionTypeSet.addExplicit(aDeclaredExceptionList);
}
}
exceptionTypeSet.addImplicit(Hierarchy.RUNTIME_EXCEPTION_TYPE);
}
if (DEBUG) {
System.out.println(pei + " can throw " + exceptionTypeSet);
}
return exceptionTypeSet;
} | java |
@CheckForNull
public static JavaClass getOuterClass(JavaClass obj) throws ClassNotFoundException {
for (Attribute a : obj.getAttributes()) {
if (a instanceof InnerClasses) {
for (InnerClass ic : ((InnerClasses) a).getInnerClasses()) {
if (obj.getClassNameIndex() == ic.getInnerClassIndex()) {
// System.out.println("Outer class is " +
// ic.getOuterClassIndex());
ConstantClass oc = (ConstantClass) obj.getConstantPool().getConstant(ic.getOuterClassIndex());
String ocName = oc.getBytes(obj.getConstantPool());
return Repository.lookupClass(ocName);
}
}
}
}
return null;
} | java |
public void addVerticesToSet(Set<VertexType> set) {
// Add the vertex for this object
set.add(this.m_vertex);
// Add vertices for all children
Iterator<SearchTree<VertexType>> i = childIterator();
while (i.hasNext()) {
SearchTree<VertexType> child = i.next();
child.addVerticesToSet(set);
}
} | java |
private void checkQualifier(XMethod xmethod, CFG cfg, TypeQualifierValue<?> typeQualifierValue,
ForwardTypeQualifierDataflowFactory forwardDataflowFactory,
BackwardTypeQualifierDataflowFactory backwardDataflowFactory, ValueNumberDataflow vnaDataflow)
throws CheckedAnalysisException {
if (DEBUG) {
System.out.println("----------------------------------------------------------------------");
System.out.println("Checking type qualifier " + typeQualifierValue.toString() + " on method "
+ xmethod.toString());
if (typeQualifierValue.isStrictQualifier()) {
System.out.println(" Strict type qualifier");
}
System.out.println("----------------------------------------------------------------------");
}
if (DEBUG_DATAFLOW) {
System.out.println("********* Valuenumber analysis *********");
DataflowCFGPrinter<ValueNumberFrame, ValueNumberAnalysis> p = new DataflowCFGPrinter<>(vnaDataflow);
p.print(System.out);
}
ForwardTypeQualifierDataflow forwardDataflow = forwardDataflowFactory.getDataflow(typeQualifierValue);
if (DEBUG_DATAFLOW && (DEBUG_DATAFLOW_MODE.startsWith("forward") || "both".equals(DEBUG_DATAFLOW_MODE))) {
System.out.println("********* Forwards analysis *********");
DataflowCFGPrinter<TypeQualifierValueSet, ForwardTypeQualifierDataflowAnalysis> p = new DataflowCFGPrinter<>(
forwardDataflow);
p.print(System.out);
}
BackwardTypeQualifierDataflow backwardDataflow = backwardDataflowFactory.getDataflow(typeQualifierValue);
if (DEBUG_DATAFLOW && (DEBUG_DATAFLOW_MODE.startsWith("backward") || "both".equals(DEBUG_DATAFLOW_MODE))) {
System.out.println("********* Backwards analysis *********");
DataflowCFGPrinter<TypeQualifierValueSet, BackwardTypeQualifierDataflowAnalysis> p = new DataflowCFGPrinter<>(
backwardDataflow);
p.print(System.out);
}
checkDataflow(xmethod, cfg, typeQualifierValue, vnaDataflow, forwardDataflow, backwardDataflow);
checkValueSources(xmethod, cfg, typeQualifierValue, vnaDataflow, forwardDataflow, backwardDataflow);
} | java |
public void setMethodHash(XMethod method, byte[] methodHash) {
methodHashMap.put(method, new MethodHash(method.getName(), method.getSignature(), method.isStatic(), methodHash));
} | java |
public void setClassHash(byte[] classHash) {
this.classHash = new byte[classHash.length];
System.arraycopy(classHash, 0, this.classHash, 0, classHash.length);
} | java |
public ClassHash computeHash(JavaClass javaClass) {
this.className = javaClass.getClassName();
Method[] methodList = new Method[javaClass.getMethods().length];
// Sort methods
System.arraycopy(javaClass.getMethods(), 0, methodList, 0, javaClass.getMethods().length);
Arrays.sort(methodList, (o1, o2) -> {
// sort by name, then signature
int cmp = o1.getName().compareTo(o2.getName());
if (cmp != 0) {
return cmp;
}
return o1.getSignature().compareTo(o2.getSignature());
});
Field[] fieldList = new Field[javaClass.getFields().length];
// Sort fields
System.arraycopy(javaClass.getFields(), 0, fieldList, 0, javaClass.getFields().length);
Arrays.sort(fieldList, (o1, o2) -> {
int cmp = o1.getName().compareTo(o2.getName());
if (cmp != 0) {
return cmp;
}
return o1.getSignature().compareTo(o2.getSignature());
});
MessageDigest digest = Util.getMD5Digest();
// Compute digest of method names and signatures, in order.
// Also, compute method hashes.
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
for (Method method : methodList) {
work(digest, method.getName(), encoder);
work(digest, method.getSignature(), encoder);
MethodHash methodHash = new MethodHash().computeHash(method);
methodHashMap.put(XFactory.createXMethod(javaClass, method), methodHash);
}
// Compute digest of field names and signatures.
for (Field field : fieldList) {
work(digest, field.getName(), encoder);
work(digest, field.getSignature(), encoder);
}
classHash = digest.digest();
return this;
} | java |
public static String hashToString(byte[] hash) {
StringBuilder buf = new StringBuilder();
for (byte b : hash) {
buf.append(HEX_CHARS[(b >> 4) & 0xF]);
buf.append(HEX_CHARS[b & 0xF]);
}
return buf.toString();
} | java |
public static byte[] stringToHash(String s) {
if (s.length() % 2 != 0) {
throw new IllegalArgumentException("Invalid hash string: " + s);
}
byte[] hash = new byte[s.length() / 2];
for (int i = 0; i < s.length(); i += 2) {
byte b = (byte) ((hexDigitValue(s.charAt(i)) << 4) + hexDigitValue(s.charAt(i + 1)));
hash[i / 2] = b;
}
return hash;
} | java |
public static Variable lookup(String varName, BindingSet bindingSet) {
if (bindingSet == null) {
return null;
}
Binding binding = bindingSet.lookup(varName);
return (binding != null) ? binding.getVariable() : null;
} | java |
public WarningPropertySet<T> addProperty(T prop) {
map.put(prop, Boolean.TRUE);
return this;
} | java |
public WarningPropertySet<T> setProperty(T prop, String value) {
map.put(prop, value);
return this;
} | java |
public boolean checkProperty(T prop, Object value) {
Object attribute = getProperty(prop);
return (attribute != null && attribute.equals(value));
} | java |
public int computePriority(int basePriority) {
boolean relaxedReporting = FindBugsAnalysisFeatures.isRelaxedMode();
boolean atLeastMedium = false;
boolean falsePositive = false;
boolean atMostLow = false;
boolean atMostMedium = false;
boolean peggedHigh = false;
int aLittleBitLower = 0;
int priority = basePriority;
if (!relaxedReporting) {
for (T warningProperty : map.keySet()) {
PriorityAdjustment adj = warningProperty.getPriorityAdjustment();
if (adj == PriorityAdjustment.PEGGED_HIGH) {
peggedHigh = true;
priority--;
} else if (adj == PriorityAdjustment.FALSE_POSITIVE) {
falsePositive = true;
atMostLow = true;
} else if (adj == PriorityAdjustment.A_LITTLE_BIT_LOWER_PRIORITY) {
aLittleBitLower++;
} else if (adj == PriorityAdjustment.A_LITTLE_BIT_HIGHER_PRIORITY) {
aLittleBitLower--;
} else if (adj == PriorityAdjustment.RAISE_PRIORITY) {
--priority;
} else if (adj == PriorityAdjustment.RAISE_PRIORITY_TO_AT_LEAST_NORMAL) {
--priority;
atLeastMedium = true;
} else if (adj == PriorityAdjustment.LOWER_PRIORITY_TO_AT_MOST_NORMAL) {
++priority;
atMostMedium = true;
} else if (adj == PriorityAdjustment.RAISE_PRIORITY_TO_HIGH) {
return Priorities.HIGH_PRIORITY;
} else if (adj == PriorityAdjustment.LOWER_PRIORITY) {
++priority;
} else if (adj == PriorityAdjustment.AT_MOST_LOW) {
priority++;
atMostLow = true;
} else if (adj == PriorityAdjustment.AT_MOST_MEDIUM) {
atMostMedium = true;
} else if (adj == PriorityAdjustment.NO_ADJUSTMENT) {
assert true; // do nothing
} else {
throw new IllegalStateException("Unknown priority " + adj);
}
}
if (peggedHigh && !falsePositive) {
return Priorities.HIGH_PRIORITY;
}
if (aLittleBitLower >= 3 || priority == 1 && aLittleBitLower == 2) {
priority++;
} else if (aLittleBitLower <= -2) {
priority--;
}
if (atMostMedium) {
priority = Math.max(Priorities.NORMAL_PRIORITY, priority);
}
if (falsePositive && !atLeastMedium) {
return Priorities.EXP_PRIORITY + 1;
} else if (atMostLow) {
return Math.min(Math.max(Priorities.LOW_PRIORITY, priority), Priorities.EXP_PRIORITY);
}
if (atLeastMedium && priority > Priorities.NORMAL_PRIORITY) {
priority = Priorities.NORMAL_PRIORITY;
}
if (priority < Priorities.HIGH_PRIORITY) {
priority = Priorities.HIGH_PRIORITY;
} else if (priority > Priorities.EXP_PRIORITY) {
priority = Priorities.EXP_PRIORITY;
}
}
return priority;
} | java |
public void decorateBugInstance(BugInstance bugInstance) {
int priority = computePriority(bugInstance.getPriority());
bugInstance.setPriority(priority);
for (Map.Entry<T, Object> entry : map.entrySet()) {
WarningProperty prop = entry.getKey();
Object attribute = entry.getValue();
if (attribute == null) {
attribute = "";
}
bugInstance.setProperty(prop.getName(), attribute.toString());
}
} | java |
public ValueNumber getEntryValueForParameter(int param) {
SignatureParser sigParser = new SignatureParser(methodGen.getSignature());
int p = 0;
int slotOffset = methodGen.isStatic() ? 0 : 1;
for ( String paramSig : sigParser.parameterSignatures()) {
if (p == param) {
return getEntryValue(slotOffset);
}
p++;
slotOffset += SignatureParser.getNumSlotsForType(paramSig);
}
throw new IllegalStateException();
} | java |
public static void writeCollection(XMLOutput xmlOutput, Collection<? extends XMLWriteable> collection) throws IOException {
for (XMLWriteable obj : collection) {
obj.writeXML(xmlOutput);
}
} | java |
@Override
public void addParameterAnnotation(int param, AnnotationValue annotationValue) {
HashMap<Integer, Map<ClassDescriptor, AnnotationValue>> updatedAnnotations = new HashMap<>(
methodParameterAnnotations);
Map<ClassDescriptor, AnnotationValue> paramMap = updatedAnnotations.get(param);
if (paramMap == null) {
paramMap = new HashMap<>();
updatedAnnotations.put(param, paramMap);
}
paramMap.put(annotationValue.getAnnotationClass(), annotationValue);
methodParameterAnnotations = updatedAnnotations;
TypeQualifierApplications.updateAnnotations(this);
} | java |
String getResourceName() {
if (!resourceNameKnown) {
// The resource name of a classfile can only be determined by
// reading
// the file and parsing the constant pool.
// If we can't do this for some reason, then we just
// make the resource name equal to the filename.
try {
resourceName = getClassDescriptor().toResourceName();
} catch (Exception e) {
resourceName = fileName;
}
resourceNameKnown = true;
}
return resourceName;
} | java |
public InputStream getInputStreamFromOffset(int offset) throws IOException {
loadFileData();
return new ByteArrayInputStream(data, offset, data.length - offset);
} | java |
public void addLineOffset(int offset) {
if (numLines >= lineNumberMap.length) {
// Grow the line number map.
int capacity = lineNumberMap.length * 2;
int[] newLineNumberMap = new int[capacity];
System.arraycopy(lineNumberMap, 0, newLineNumberMap, 0, lineNumberMap.length);
lineNumberMap = newLineNumberMap;
}
lineNumberMap[numLines++] = offset;
} | java |
public int getLineOffset(int line) {
try {
loadFileData();
} catch (IOException e) {
System.err.println("SourceFile.getLineOffset: " + e.getMessage());
return -1;
}
if (line < 0 || line >= numLines) {
return -1;
}
return lineNumberMap[line];
} | java |
public void findStronglyConnectedComponents(GraphType g, GraphToolkit<GraphType, EdgeType, VertexType> toolkit) {
// Perform the initial depth first search
DepthFirstSearch<GraphType, EdgeType, VertexType> initialDFS = new DepthFirstSearch<>(g);
if (m_vertexChooser != null) {
initialDFS.setVertexChooser(m_vertexChooser);
}
initialDFS.search();
// Create a transposed graph
Transpose<GraphType, EdgeType, VertexType> t = new Transpose<>();
GraphType transpose = t.transpose(g, toolkit);
// Create a set of vertices in the transposed graph,
// in descending order of finish time in the initial
// depth first search.
VisitationTimeComparator<VertexType> comparator = new VisitationTimeComparator<>(
initialDFS.getFinishTimeList(), VisitationTimeComparator.DESCENDING);
Set<VertexType> descendingByFinishTimeSet = new TreeSet<>(comparator);
Iterator<VertexType> i = transpose.vertexIterator();
while (i.hasNext()) {
descendingByFinishTimeSet.add(i.next());
}
// Create a SearchTreeBuilder for transposed DFS
SearchTreeBuilder<VertexType> searchTreeBuilder = new SearchTreeBuilder<>();
// Now perform a DFS on the transpose, choosing the vertices
// to visit in the main loop by descending finish time
final Iterator<VertexType> vertexIter = descendingByFinishTimeSet.iterator();
DepthFirstSearch<GraphType, EdgeType, VertexType> transposeDFS = new DepthFirstSearch<GraphType, EdgeType, VertexType>(
transpose) {
@Override
protected VertexType getNextSearchTreeRoot() {
while (vertexIter.hasNext()) {
VertexType vertex = vertexIter.next();
if (visitMe(vertex)) {
return vertex;
}
}
return null;
}
};
if (m_vertexChooser != null) {
transposeDFS.setVertexChooser(m_vertexChooser);
}
transposeDFS.setSearchTreeCallback(searchTreeBuilder);
transposeDFS.search();
// The search tree roots of the second DFS represent the
// strongly connected components. Note that we call copySearchTree()
// to make the returned search trees relative to the original
// graph, not the transposed graph (which would be very confusing).
Iterator<SearchTree<VertexType>> j = searchTreeBuilder.searchTreeIterator();
while (j.hasNext()) {
m_stronglyConnectedSearchTreeList.add(copySearchTree(j.next(), t));
}
} | java |
public Collection<String> split() {
String s = ident;
Set<String> result = new HashSet<>();
while (s.length() > 0) {
StringBuilder buf = new StringBuilder();
char first = s.charAt(0);
buf.append(first);
int i = 1;
if (s.length() > 1) {
boolean camelWord;
if (Character.isLowerCase(first)) {
camelWord = true;
} else {
char next = s.charAt(i++);
buf.append(next);
camelWord = Character.isLowerCase(next);
}
while (i < s.length()) {
char c = s.charAt(i);
if (Character.isUpperCase(c)) {
if (camelWord) {
break;
}
} else if (!camelWord) {
break;
}
buf.append(c);
++i;
}
if (!camelWord && i < s.length()) {
buf.deleteCharAt(buf.length() - 1);
--i;
}
}
result.add(buf.toString().toLowerCase(Locale.US));
s = s.substring(i);
}
return result;
} | java |
private static void collectAllAnonymous(List<IType> list, IParent parent, boolean allowNested) throws JavaModelException {
IJavaElement[] children = parent.getChildren();
for (int i = 0; i < children.length; i++) {
IJavaElement childElem = children[i];
if (isAnonymousType(childElem)) {
list.add((IType) childElem);
}
if (childElem instanceof IParent) {
if (allowNested || !(childElem instanceof IType)) {
collectAllAnonymous(list, (IParent) childElem, allowNested);
}
}
}
} | java |
private static void sortAnonymous(List<IType> anonymous, IType anonType) {
SourceOffsetComparator sourceComparator = new SourceOffsetComparator();
final AnonymClassComparator classComparator = new AnonymClassComparator(anonType, sourceComparator);
Collections.sort(anonymous, classComparator);
// if (Reporter.DEBUG) {
// debugCompilePrio(classComparator);
// }
} | java |
public static void addFindBugsNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (hasFindBugsNature(project)) {
return;
}
IProjectDescription description = project.getDescription();
String[] prevNatures = description.getNatureIds();
for (int i = 0; i < prevNatures.length; i++) {
if (FindbugsPlugin.NATURE_ID.equals(prevNatures[i])) {
// nothing to do
return;
}
}
String[] newNatures = new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length] = FindbugsPlugin.NATURE_ID;
if (DEBUG) {
for (int i = 0; i < newNatures.length; i++) {
System.out.println(newNatures[i]);
}
}
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
} | java |
public static boolean hasFindBugsNature(IProject project) {
try {
return ProjectUtilities.isJavaProject(project) && project.hasNature(FindbugsPlugin.NATURE_ID);
} catch (CoreException e) {
FindbugsPlugin.getDefault().logException(e, "Error while testing SpotBugs nature for project " + project);
}
return false;
} | java |
public static void removeFindBugsNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (!hasFindBugsNature(project)) {
return;
}
IProjectDescription description = project.getDescription();
String[] prevNatures = description.getNatureIds();
ArrayList<String> newNaturesList = new ArrayList<>();
for (int i = 0; i < prevNatures.length; i++) {
if (!FindbugsPlugin.NATURE_ID.equals(prevNatures[i])) {
newNaturesList.add(prevNatures[i]);
}
}
String[] newNatures = newNaturesList.toArray(new String[newNaturesList.size()]);
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
} | java |
public void execute() throws CFGBuilderException {
JavaClass jclass = classContext.getJavaClass();
Method[] methods = jclass.getMethods();
LOG.debug("Class has {} methods", methods.length);
// Add call graph nodes for all methods
for (Method method : methods) {
callGraph.addNode(method);
}
LOG.debug("Added {} nodes to graph", callGraph.getNumVertices());
// Scan methods for self calls
for (Method method : methods) {
MethodGen mg = classContext.getMethodGen(method);
if (mg == null) {
continue;
}
scan(callGraph.getNodeForMethod(method));
}
LOG.debug("Found {} self calls", callGraph.getNumEdges());
} | java |
public Iterator<CallSite> callSiteIterator() {
return new Iterator<CallSite>() {
private final Iterator<CallGraphEdge> iter = callGraph.edgeIterator();
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
public CallSite next() {
return iter.next().getCallSite();
}
@Override
public void remove() {
iter.remove();
}
};
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.