Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions java-frontend-semsitter/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
<groupId>org.sonarsource.semsitter</groupId>
<artifactId>analyzer-wire</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.semsitter;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.protobuf.CodedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.sonarsource.semsitter.wire.Document;

/**
* Client of one SemSitter Java analyzer server process. Control messages are JSON lines. A {@code get-file} answer
* carries a {@link Document} and a {@code get-types} answer carries a JSON object, each prefixed by the byte count
* the header names. The process starts with the client and ends with {@link #close()}.
*/
public final class SemSitterClient implements AutoCloseable {

static final String PROTOCOL_MAJOR = "2";

private static final List<String> SERVER_FLAGS = List.of("--server", "--lang", "java", "--modifiers", "--structural",
"--decl-location", "--field-items", "--field-reference-edges", "--override-edges");

private final Process process;
private final BufferedWriter toServer;
private final InputStream fromServer;
private int nextId = 1;

private SemSitterClient(Process process) {
this.process = process;
this.toServer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), StandardCharsets.UTF_8));
this.fromServer = process.getInputStream();
}

/**
* Starts the server on the sources of {@code projectRoot} and checks that it speaks this protocol.
*/
public static SemSitterClient start(Path executable, Path projectRoot) throws IOException {
return start(command(List.of(executable.toAbsolutePath().toString()), projectRoot));
}

static SemSitterClient start(List<String> command) throws IOException {
Process process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.INHERIT).start();
SemSitterClient client = new SemSitterClient(process);

Check failure on line 71 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java

View check run for this annotation

SonarQube-Next / SonarQube Code Analysis

Use try-with-resources or close this "SemSitterClient" in a "finally" clause.

[S2095] Resources should be closed See more on https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.java%3Ajava&pullRequest=6542&issues=ce0139c7-cada-4aac-af52-3e70c317935c&open=ce0139c7-cada-4aac-af52-3e70c317935c
try {
String protocol = client.send(client.command("hello")).get("protocol").getAsString();
if (!protocol.startsWith(PROTOCOL_MAJOR + ".")) {
throw new IOException("Unsupported SemSitter protocol " + protocol);
}
} catch (IOException | RuntimeException e) {
process.destroyForcibly();
throw e;
}
return client;
}

static List<String> command(List<String> launcher, Path projectRoot) {
String root = projectRoot.toAbsolutePath().toString();
List<String> command = new ArrayList<>(launcher);
command.addAll(SERVER_FLAGS);
command.addAll(List.of("--src", root, "--project-root", root));
return command;
}

public void setSettings(Map<String, List<String>> settings) throws IOException {
JsonObject request = command("set-settings");
JsonObject values = new JsonObject();
settings.forEach((key, list) -> {
JsonArray array = new JsonArray();
list.forEach(array::add);
values.add(key, array);
});
request.add("settings", values);
send(request);
}

/**
* Scans {@code files}, or the source roots when empty.
* @return how many files the server scanned
*/
public int fullGen(Collection<String> files) throws IOException {
JsonObject request = command("full-gen");
if (!files.isEmpty()) {
JsonArray array = new JsonArray();
files.forEach(array::add);
request.add("files", array);
}
return send(request).get("files").getAsInt();
}

public Document getFile(String path, int ahead) throws IOException {
JsonObject request = command("get-file");
request.addProperty("path", path);
request.addProperty("ahead", ahead);
CodedInputStream input = CodedInputStream.newInstance(exchange(request).payload);
input.setRecursionLimit(Integer.MAX_VALUE);
return Document.parseFrom(input);
}
Comment on lines +118 to +125

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Bug: getFile/getTypes call exchange() without the lock send() holds

send is synchronized, which shows the client is meant to be safe across threads. getFile and getTypes call the unsynchronized exchange directly, though, so they skip that lock. If a getFile overlaps a send (for example hasPackage or close) or another getFile, the two can race on nextId, write interleaved bytes to toServer, and each read the other's header and payload from fromServer. The result is id-mismatch failures or a payload parsed as the wrong document. The fix is to make exchange itself synchronized, so all three paths go through one lock.

Put the lock on exchange so every request/response pair is atomic:

private JsonObject send(JsonObject request) throws IOException {
  return exchange(request).header;
}

private synchronized Answer exchange(JsonObject request) throws IOException {
  • Apply fix

Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎


/**
* @return the JSON object of declarations, as {@code types.schema.json} describes it
*/
public byte[] getTypes(Collection<String> names) throws IOException {
JsonObject request = command("get-types");
JsonArray array = new JsonArray();
names.forEach(array::add);
request.add("names", array);
return exchange(request).payload;
}

public Map<String, Boolean> hasPackage(Collection<String> names) throws IOException {
JsonObject request = command("has-package");
JsonArray array = new JsonArray();
names.forEach(array::add);
request.add("names", array);
Map<String, Boolean> found = new LinkedHashMap<>();
for (Map.Entry<String, JsonElement> entry : send(request).getAsJsonObject("packages").entrySet()) {
found.put(entry.getKey(), entry.getValue().getAsBoolean());
}
return found;
}

private JsonObject command(String name) {

Check warning on line 150 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java

View check run for this annotation

SonarQube-Next / SonarQube Code Analysis

Make "command" a "static" method.

[S2325] "private" and "final" methods that don't access instance data should be "static" See more on https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.java%3Ajava&pullRequest=6542&issues=cdf42b51-f5bc-43e8-b84e-b4c3ec795354&open=cdf42b51-f5bc-43e8-b84e-b4c3ec795354
JsonObject request = new JsonObject();
request.addProperty("cmd", name);
return request;
}

private synchronized JsonObject send(JsonObject request) throws IOException {
return exchange(request).header;
}

private Answer exchange(JsonObject request) throws IOException {
int id = nextId;
nextId++;
request.addProperty("id", id);
try {
toServer.write(request.toString());
toServer.write('\n');
toServer.flush();
String text = readLine(fromServer);
JsonObject header = JsonParser.parseString(text).getAsJsonObject();
byte[] payload = new byte[0];
if (header.has("payload_bytes")) {
payload = fromServer.readNBytes(header.get("payload_bytes").getAsInt());
}
Comment on lines +171 to +173

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Edge Case: A truncated payload is accepted without any error

InputStream.readNBytes(n) returns fewer than n bytes when the stream hits EOF. If the server crashes or closes stdout partway through a payload, the client never notices. getTypes would return cut-off JSON, and getFile would hand a short buffer to Document.parseFrom. Protobuf accepts input that stops on a field boundary, so the caller can silently get an incomplete Document. The fix is to compare the length of the bytes read with payload_bytes and throw an IOException if they differ.

Fail when fewer bytes arrive than the header announced:

if (header.has("payload_bytes")) {
  int expected = header.get("payload_bytes").getAsInt();
  payload = fromServer.readNBytes(expected);
  if (payload.length != expected) {
    throw new IOException("SemSitter server closed its output after " + payload.length + " of " + expected + " payload bytes");
  }
}
  • Apply fix

Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎

if (header.get("id").getAsInt() != id) {
throw new IOException("SemSitter server answered request " + header.get("id") + " instead of " + id);
}
if (!header.get("ok").getAsBoolean()) {
throw new IOException("SemSitter server: " + header.get("error").getAsString());
}
return new Answer(header, payload);
} catch (IOException e) {
String message = e.getMessage().startsWith("SemSitter") ? e.getMessage() : ("SemSitter server: " + e.getMessage());
throw new IOException(message, e);
}
}

/**
* Asks the server to quit and waits for it, forcing it to stop when it does not answer.
*/
@Override
public void close() {
try {
if (process.isAlive()) {
send(command("quit"));
toServer.close();
if (!process.waitFor(10, TimeUnit.SECONDS)) {
process.destroyForcibly();
}
}
} catch (IOException e) {
process.destroyForcibly();
Comment on lines +187 to +201

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Bug: close() hangs forever when the server never answers the quit request

The javadoc says close() forces the server to stop "when it does not answer", but close() first calls send(quit), and send blocks on Response.parseDelimitedFrom(fromServer) with no timeout. The 10-second waitFor is only reached after a quit response arrives. So if the process is still alive but stuck (deadlocked, busy in a long scan, or stopped writing to stdout), close() and any try-with-resources around the client block forever, and destroyForcibly() is never called. start() has the same problem: a server that never answers hello blocks start() with no way out. Fix: write the quit request and close stdin without waiting for the reply, then use process.waitFor(timeout) as the only wait and call destroyForcibly() when it runs out. Or read the reply on a separate thread with a timeout.

Send quit without waiting for the reply, so that the timed waitFor is the only wait.:

if (process.isAlive()) {
  synchronized (this) {
    Request.newBuilder().setId(nextId++).setQuit(QuitRequest.getDefaultInstance()).build().writeDelimitedTo(toServer);
    toServer.close();
  }
  if (!process.waitFor(10, TimeUnit.SECONDS)) {
    process.destroyForcibly();
  }
}
  • Apply fix

Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎

} catch (InterruptedException e) {
process.destroyForcibly();
Thread.currentThread().interrupt();
}
}

private static String readLine(InputStream in) throws IOException {
ByteArrayOutputStream line = new ByteArrayOutputStream();
for (int b = in.read(); b != '\n'; b = in.read()) {
if (b < 0) {
throw new IOException("SemSitter server closed its output");
}
line.write(b);
}
return line.toString(StandardCharsets.UTF_8);
}

private static final class Answer {
private final JsonObject header;
private final byte[] payload;

private Answer(JsonObject header, byte[] payload) {
this.header = header;
this.payload = payload;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.semsitter;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.sonarsource.semsitter.wire.Document;
import org.sonarsource.semsitter.wire.Node;

/**
* Stand-in for the SemSitter server, run as a separate process by the tests. The first argument is the protocol
* version it announces. {@code --exit-after-hello} stops after the handshake and {@code --wrong-id} answers
* {@code get-file} with another id. A requested path ending with {@code Deep.java} gets a tree nested
* {@link #DEEP_TREE_DEPTH} levels deep.
*/
public final class FakeServer {

static final int DEEP_TREE_DEPTH = 1_000;

private FakeServer() {
}

public static void main(String[] args) {
try (InputStream in = new FileInputStream(FileDescriptor.in); OutputStream out = new FileOutputStream(FileDescriptor.out)) {
serve(List.of(args), in, out);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

private static void serve(List<String> args, InputStream in, OutputStream out) throws IOException {
String line;
while ((line = readLine(in)) != null) {
JsonObject request = JsonParser.parseString(line).getAsJsonObject();
JsonObject header = new JsonObject();
header.addProperty("id", args.contains("--wrong-id") && "get-file".equals(request.get("cmd").getAsString()) ? 0 : request.get("id").getAsInt());
header.addProperty("ok", true);
byte[] payload = answer(request, header, args.get(0));
if (payload.length > 0) {
header.addProperty("payload_bytes", payload.length);
}
out.write(header.toString().getBytes(StandardCharsets.UTF_8));
out.write('\n');
out.write(payload);
out.flush();
if ("quit".equals(request.get("cmd").getAsString()) || ("hello".equals(request.get("cmd").getAsString()) && args.contains("--exit-after-hello"))) {
return;
}
}
}

private static byte[] answer(JsonObject request, JsonObject header, String protocol) {
switch (request.get("cmd").getAsString()) {
case "hello" -> header.addProperty("protocol", protocol);
case "set-settings" -> header.add("settings", request.get("settings"));
case "full-gen" -> header.addProperty("files", request.has("files") ? request.getAsJsonArray("files").size() : 0);
case "get-file" -> {
String path = request.get("path").getAsString();
if (path.endsWith("Nope.java")) {
header.addProperty("ok", false);
header.addProperty("error", "no such file " + path);
return new byte[0];
}
header.addProperty("format", "protobuf");
Node.Builder tree = Node.newBuilder().setKind("program");
if (path.endsWith("Deep.java")) {
for (int depth = 0; depth < DEEP_TREE_DEPTH; depth++) {
tree = Node.newBuilder().setKind("parenthesized_expression").addChildren(tree);
}
}
return Document.newBuilder().setPath(path).setTree(tree).build().toByteArray();
}
case "get-types" -> {
header.addProperty("format", "json");
return "{\"java.lang.String\":{\"kind\":\"class\"}}".getBytes(StandardCharsets.UTF_8);
}
case "has-package" -> {
JsonObject packages = new JsonObject();
request.getAsJsonArray("names").forEach(name -> packages.addProperty(name.getAsString(), name.getAsString().startsWith("java")));
header.add("packages", packages);
}
default -> {
// a quit request has no result beyond ok
}
}
return new byte[0];
}

private static String readLine(InputStream in) throws IOException {
ByteArrayOutputStream line = new ByteArrayOutputStream();
for (int b = in.read(); b != '\n'; b = in.read()) {
if (b < 0) {
return line.size() == 0 ? null : line.toString(StandardCharsets.UTF_8);
}
line.write(b);
}
return line.toString(StandardCharsets.UTF_8);
}
}
Loading
Loading