Skip to content

Commit

Permalink
Merge pull request #1600 from guwirth/fix-121-vulnerabilities
Browse files Browse the repository at this point in the history
remove vulnerabilities
  • Loading branch information
guwirth authored Nov 26, 2018
2 parents 9080dc2 + c850639 commit 223acac
Show file tree
Hide file tree
Showing 66 changed files with 228 additions and 273 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public class CommentedCodeCheck extends SquidCheck<Grammar> implements AstAndTok

private final CodeRecognizer codeRecognizer = new CodeRecognizer(THRESHOLD, new CxxRecognizer());

private final Pattern EOLPattern = Pattern.compile("\\R");
private static final Pattern EOL_PATTERN = Pattern.compile("\\R");

private static class CxxRecognizer implements LanguageFootprint {

Expand Down Expand Up @@ -85,7 +85,7 @@ public void visitToken(Token token) {
&& !value.startsWith("/*!")
&& !value.startsWith("/*@")
&& !value.startsWith("//@")) {
String[] lines = EOLPattern.split(getContext().getCommentAnalyser().getContents(value));
String[] lines = EOL_PATTERN.split(getContext().getCommentAnalyser().getContents(value));

for (int lineOffset = 0; lineOffset < lines.length; lineOffset++) {
if (codeRecognizer.isLineOfCode(lines[lineOffset])) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@
@SqaleConstantRemediation("5min")
public class ReservedNamesCheck extends SquidCheck<Grammar> implements CxxCharsetAwareVisitor {

private static String[] keywords = CxxKeyword.keywordValues();
private static final String[] keywords = CxxKeyword.keywordValues();
private Charset charset = Charset.forName("UTF-8");
private static final Pattern defineDeclarationPattern = Pattern.compile("^\\s*#define\\s+([^\\s(]+).*$");
private static final Pattern DEFINE_DECLARATION_PATTERN = Pattern.compile("^\\s*#define\\s+([^\\s(]+).*$");


@Override
Expand All @@ -67,7 +67,7 @@ public void visitFile(AstNode astNode) {
int nr = 0;
for (String line : lines) {
nr++;
Matcher matcher = defineDeclarationPattern.matcher(line);
Matcher matcher = DEFINE_DECLARATION_PATTERN.matcher(line);
if (matcher.matches()) {
String name = matcher.group(1);
if (name.startsWith("_") && name.length() > 1 && Character.isUpperCase(name.charAt(1))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,33 +19,29 @@
*/
package org.sonar.cxx.checks.metrics;

import com.sonar.sslr.api.AstNode;
import com.sonar.sslr.api.AstNodeType;
import com.sonar.sslr.api.Grammar;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Optional;

import org.sonar.cxx.CxxComplexityConstants;
import org.sonar.cxx.utils.CxxReportIssue;
import org.sonar.cxx.visitors.CxxComplexityScope;
import org.sonar.cxx.visitors.CxxComplexitySource;
import org.sonar.cxx.visitors.MultiLocatitionSquidCheck;

import com.sonar.sslr.api.AstNode;
import com.sonar.sslr.api.AstNodeType;
import com.sonar.sslr.api.Grammar;

/**
* This is an enhanced version of
* org.sonar.squidbridge.metrics.ComplexityVisitor, which is used in order to
* compute the Cyclomatic Complexity.
* This is an enhanced version of org.sonar.squidbridge.metrics.ComplexityVisitor, which is used in order to compute the
* Cyclomatic Complexity.
*
* @param <G>
*/
public abstract class CxxCyclomaticComplexityCheck<G extends Grammar> extends MultiLocatitionSquidCheck<G> {

/**
* Stack for tracking the nested scopes (e.g. declaration of classes can be
* nested). Complexity of the inner scopes is added to the complexity of outer
* scopes.
* Stack for tracking the nested scopes (e.g. declaration of classes can be nested). Complexity of the inner scopes is
* added to the complexity of outer scopes.
*/
private Deque<CxxComplexityScope> complexityScopes;

Expand All @@ -55,10 +51,8 @@ public abstract class CxxCyclomaticComplexityCheck<G extends Grammar> extends Mu
protected abstract int getMaxComplexity();

/**
* @return valid AstNodeType if complexity is calculated for some language
* constructs only (e.g. function definition, class definition etc).
* Return Optional.empty() if the complexity is calculated for entire
* file.
* @return valid AstNodeType if complexity is calculated for some language constructs only (e.g. function definition,
* class definition etc). Return Optional.empty() if the complexity is calculated for entire file.
*/
protected abstract Optional<AstNodeType> getScopeType();

Expand All @@ -69,7 +63,7 @@ public abstract class CxxCyclomaticComplexityCheck<G extends Grammar> extends Mu

@Override
public void init() {
subscribeTo(CxxComplexityConstants.CyclomaticComplexityAstNodeTypes);
subscribeTo(CxxComplexityConstants.getCyclomaticComplexityTypes());
final Optional<AstNodeType> scopeType = getScopeType();
if (scopeType.isPresent()) {
final AstNodeType additionalNode = scopeType.get();
Expand Down Expand Up @@ -106,7 +100,7 @@ public void visitNode(AstNode astNode) {
complexityScopes.addFirst(new CxxComplexityScope(astNode.getTokenLine()));
}

if (astNode.is(CxxComplexityConstants.CyclomaticComplexityAstNodeTypes)) {
if (astNode.is(CxxComplexityConstants.getCyclomaticComplexityTypes())) {
// for nested scopes (e.g. nested classes) the inner classes
// add complexity to the outer ones
for (CxxComplexityScope scope : complexityScopes) {
Expand Down Expand Up @@ -135,7 +129,7 @@ private void analyzeScopeComplexity() {
if (scope.getComplexity() > maxComplexity) {
final StringBuilder msg = new StringBuilder();
msg.append("The Cyclomatic Complexity of this ").append(getScopeName()).append(" is ").append(currentComplexity)
.append(" which is greater than ").append(maxComplexity).append(" authorized.");
.append(" which is greater than ").append(maxComplexity).append(" authorized.");

final CxxReportIssue issue = new CxxReportIssue(getRuleKey(), null, scope.getStartingLine(), msg.toString());
for (CxxComplexitySource source : scope.getSources()) {
Expand All @@ -144,4 +138,4 @@ private void analyzeScopeComplexity() {
createMultiLocationViolation(issue);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,9 @@ public void init() {

@Override
public void visitNode(AstNode node) {
int nbParameters = 0;
AstNode parameterList = node.getFirstChild(CxxGrammarImpl.parameterDeclarationList);
if (parameterList != null) {
nbParameters = parameterList.getChildren(CxxGrammarImpl.parameterDeclaration).size();
int nbParameters = parameterList.getChildren(CxxGrammarImpl.parameterDeclaration).size();
if (nbParameters > max) {
String message = "parameter list has {0} parameters, which is greater than the {1} authorized.";
getContext().createLineViolation(this, message, node, nbParameters, max);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ public class CommentContainsPatternChecker {
description = "The violation message")
private final String message;

private Pattern p;
private final Pattern p;

private static final Pattern EOLPattern = Pattern.compile("\\R");
private static final Pattern EOL_PATTERN = Pattern.compile("\\R");

/**
* CommentContainsPatternChecker
Expand Down Expand Up @@ -88,7 +88,7 @@ public void visitToken(Token token) {
String comment = triviaToken.getOriginalValue();
int line = triviaToken.getLine();
if (indexOfIgnoreCase(comment) != -1) {
String[] lines = EOLPattern.split(comment);
String[] lines = EOL_PATTERN.split(comment);

for (int i = 0; i < lines.length; i++) {
int start = indexOfIgnoreCase(lines[i]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,9 @@ private static boolean matches(String[] expectedLines, List<String> lines) {
result = true;

Iterator<String> it = lines.iterator();
for (int i = 0; i < expectedLines.length; i++) {
for (String expectedLine : expectedLines) {
String line = it.next();
if (!line.equals(expectedLines[i])) {
if (!line.equals(expectedLine)) {
result = false;
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,14 @@
@NoSqale
public class NoSonarCheck extends SquidCheck<Grammar> implements AstAndTokenVisitor {

private static final Pattern EOLPattern = Pattern.compile("\\R");
private static final Pattern EOL_PATTERN = Pattern.compile("\\R");

@Override
public void visitToken(Token token) {
for (Trivia trivia : token.getTrivia()) {
if (trivia.isComment()) {
String[] commentLines = EOLPattern
.split(getContext().getCommentAnalyser().getContents(trivia.getToken().getOriginalValue()), -1);
String[] commentLines = EOL_PATTERN
.split(getContext().getCommentAnalyser().getContents(trivia.getToken().getOriginalValue()), -1);
int line = trivia.getToken().getLine();

for (String commentLine : commentLines) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

public class TooManyLinesOfCodeInFunctionCheckTest {

private TooManyLinesOfCodeInFunctionCheck check = new TooManyLinesOfCodeInFunctionCheck();
private final TooManyLinesOfCodeInFunctionCheck check = new TooManyLinesOfCodeInFunctionCheck();

@Test
@SuppressWarnings("squid:S2699") // ... verify contains the assertion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ private CxxCheckList() {
}

public static List<Class> getChecks() {
return new ArrayList<Class>(Arrays.asList(
return new ArrayList<>(Arrays.asList(
org.sonar.cxx.checks.BooleanEqualityComparisonCheck.class,
org.sonar.cxx.checks.CollapsibleIfCandidateCheck.class,
org.sonar.cxx.checks.CommentedCodeCheck.class,
Expand Down
12 changes: 3 additions & 9 deletions cxx-lint/src/main/java/org/sonar/cxx/cxxlint/CxxLint.java
Original file line number Diff line number Diff line change
Expand Up @@ -97,24 +97,18 @@ public static String readFile(String filename) {

/**
* @param args the command line arguments
* @throws IOException
* @throws UnsupportedEncodingException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws java.Exception
*/
public static void main(String[] args) {

CommandLineParser commandlineParser = new DefaultParser();
Options options = createCommandLineOptions();
CommandLine parsedArgs = null;
String settingsFile = "";
String encodingOfFile = "UTF-8";
File targetFile = null;
boolean isNotOptionS = true;

try {
parsedArgs = commandlineParser.parse(createCommandLineOptions(), args);
CommandLine parsedArgs = commandlineParser.parse(createCommandLineOptions(), args);
if (!parsedArgs.hasOption("f")) {
throw new ParseException("f option mandatory");
} else {
Expand Down Expand Up @@ -423,8 +417,8 @@ private static void handleVCppAdditionalOptions(String platformToolset, String p
|| "V140".equals(platformToolset)) {
HashMap<String, List<String>> uniqueIncludes = new HashMap<>();
HashMap<String, Set<String>> uniqueDefines = new HashMap<>();
uniqueDefines.put(fileToAnalyse, new HashSet<String>());
uniqueIncludes.put(fileToAnalyse, new ArrayList<String>());
uniqueDefines.put(fileToAnalyse, new HashSet<>());
uniqueIncludes.put(fileToAnalyse, new ArrayList<>());
CxxVCppBuildLogParser lineOptionsParser = new CxxVCppBuildLogParser(uniqueIncludes, uniqueDefines);
lineOptionsParser.setPlatform(platform);
lineOptionsParser.setPlatformToolset(platformToolset);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,26 +54,14 @@ public BullseyeParser() {
public void processReport(File report, final Map<String, CoverageMeasures> coverageData)
throws XMLStreamException {
LOG.debug("Parsing 'Bullseye' format");
StaxParser topLevelparser = new StaxParser(new StaxParser.XmlStreamHandler() {
/**
* {@inheritDoc}
*/
@Override
public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException {
rootCursor.advance();
collectCoverageLeafNodes(rootCursor.getAttrValue("dir"), rootCursor.childElementCursor("src"), coverageData);
}
StaxParser topLevelparser = new StaxParser((SMHierarchicCursor rootCursor) -> {
rootCursor.advance();
collectCoverageLeafNodes(rootCursor.getAttrValue("dir"), rootCursor.childElementCursor("src"), coverageData);
});

StaxParser parser = new StaxParser(new StaxParser.XmlStreamHandler() {
/**
* {@inheritDoc}
*/
@Override
public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException {
rootCursor.advance();
collectCoverage2(rootCursor.getAttrValue("dir"), rootCursor.childElementCursor("folder"), coverageData);
}
StaxParser parser = new StaxParser((SMHierarchicCursor rootCursor) -> {
rootCursor.advance();
collectCoverage2(rootCursor.getAttrValue("dir"), rootCursor.childElementCursor("folder"), coverageData);
});

topLevelparser.parse(report);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class CoberturaParser extends CxxCoverageParser {

private static final Logger LOG = Loggers.get(CoberturaParser.class);
private Optional<Path> baseDir;
private static final Pattern conditionsPattern = Pattern.compile("\\((.*?)\\)");
private static final Pattern CONDITION_PATTERN = Pattern.compile("\\((.*?)\\)");

public CoberturaParser() {
// no operation but necessary for list of coverage parsers
Expand Down Expand Up @@ -122,7 +122,7 @@ private static void collectFileData(SMInputCursor clazz, CoverageMeasures builde
String isBranch = line.getAttrValue("branch");
String text = line.getAttrValue("condition-coverage");
if (text != null && "true".equals(isBranch) && !text.trim().isEmpty()) {
Matcher m = conditionsPattern.matcher(text);
Matcher m = CONDITION_PATTERN.matcher(text);
if (m.find()) {
String[] conditions = m.group(1).split("/");
builder.setConditions(lineId, Integer.parseInt(conditions[1]), Integer.parseInt(conditions[0]));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,6 @@ public void execute(SensorContext context) {
LOG.info("Searching coverage reports by path with basedir '{}' and search prop '{}'",
context.fileSystem().baseDir(), getReportPathKey());
LOG.info("Searching for coverage reports '{}'", Arrays.toString(reportsKey));

Map<String, CoverageMeasures> coverageMeasures = null;

LOG.info("Coverage BaseDir '{}' ", context.fileSystem().baseDir());

if (context.config().hasKey(getReportPathKey())) {
Expand All @@ -100,7 +97,7 @@ public void execute(SensorContext context) {
}

List<File> reports = getReports(context.config(), context.fileSystem().baseDir(), getReportPathKey());
coverageMeasures = processReports(reports, this.cache.unitCoverageCache());
Map<String, CoverageMeasures> coverageMeasures = processReports(reports, this.cache.unitCoverageCache());
saveMeasures(context, coverageMeasures);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,9 @@ public VisualStudioParser() {
public void processReport(File report, final Map<String, CoverageMeasures> coverageData)
throws XMLStreamException {
LOG.debug("Parsing 'Visual Studio' format");
StaxParser parser = new StaxParser(new StaxParser.XmlStreamHandler() {
/**
* {@inheritDoc}
*/
@Override
public void stream(SMHierarchicCursor rootCursor) throws XMLStreamException {
rootCursor.advance();
collectModuleMeasures(rootCursor.descendantElementCursor("module"), coverageData);
}
StaxParser parser = new StaxParser((SMHierarchicCursor rootCursor) -> {
rootCursor.advance();
collectModuleMeasures(rootCursor.descendantElementCursor("module"), coverageData);
});
parser.parse(report);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
public final class DrMemoryParser {

private static final Logger LOG = Loggers.get(DrMemoryParser.class);
public static final Pattern rx_message_finder = Pattern.compile("^Error #\\d+:(.*)");
public static final Pattern rx_file_finder = Pattern.compile("^.*\\[(.*):(\\d+)\\]$");
public static final Pattern RX_MESSAGE_FINDER = Pattern.compile("^Error #\\d+:(.*)");
public static final Pattern RX_FILE_FINDER = Pattern.compile("^.*\\[(.*):(\\d+)\\]$");
public static final int TOP_COUNT = 4;

/**
Expand Down Expand Up @@ -103,7 +103,7 @@ public String toString() {
}

private DrMemoryErrorType type = DrMemoryErrorType.UNRECOGNIZED;
private List<Location> stackTrace = new ArrayList<>();
private final List<Location> stackTrace = new ArrayList<>();
private String message = "";

public DrMemoryErrorType getType() {
Expand Down Expand Up @@ -149,15 +149,15 @@ public static List<DrMemoryError> parse(File file, String charset) {
List<String> elements = getElements(file, charset);

for (String element : elements) {
Matcher m = rx_message_finder.matcher(element);
Matcher m = RX_MESSAGE_FINDER.matcher(element);

if (m.find()) {
DrMemoryError error = new DrMemoryError();
error.type = extractErrorType(m.group(1));
String[] elementSplitted = CxxUtils.EOLPattern.split(element);
String[] elementSplitted = CxxUtils.EOL_PATTERN.split(element);
error.message = elementSplitted[0];
for (String elementPart : elementSplitted) {
Matcher locationMatcher = rx_file_finder.matcher(elementPart);
Matcher locationMatcher = RX_FILE_FINDER.matcher(elementPart);
if (locationMatcher.find()) {
Location location = new Location();
location.file = locationMatcher.group(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public class CxxPCLintSensor extends CxxIssuesReportSensor {

private static final Logger LOG = Loggers.get(CxxPCLintSensor.class);
public static final String REPORT_PATH_KEY = "pclint.reportPath";
public static final Pattern misraRulePattern = Pattern.compile(
public static final Pattern MISRA_RULE_PATTERN = Pattern.compile(
// Rule nn.nn -or- Rule nn-nn-nn
"Rule\\x20(\\d{1,2}.\\d{1,2}|\\d{1,2}-\\d{1,2}-\\d{1,2})(,|\\])");

Expand Down Expand Up @@ -144,7 +144,7 @@ private boolean isInputValid(@Nullable String file, @Nullable String line,
* Concatenate M with the MISRA rule number to get the new rule id to save the violation to.
*/
private String mapMisraRulesToUniqueSonarRules(String msg, Boolean isMisra2012) {
Matcher matcher = misraRulePattern.matcher(msg);
Matcher matcher = MISRA_RULE_PATTERN.matcher(msg);
if (matcher.find()) {
String misraRule = matcher.group(1);
String newKey;
Expand Down
Loading

0 comments on commit 223acac

Please sign in to comment.