diff --git a/README.md b/README.md index a897ae0..d609bc1 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,7 @@ Set `VERSION` variable if you want to specify project version - `cocoemu` - `cocodump` - `synthm` + - `cdp-java` - `logisim-banked-memory` - `logisim-cdm-emulator` - `logisim-runner` diff --git a/cdp-java/.gitignore b/cdp-java/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/cdp-java/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/cdp-java/build.gradle b/cdp-java/build.gradle new file mode 100644 index 0000000..dc2ee8f --- /dev/null +++ b/cdp-java/build.gradle @@ -0,0 +1,31 @@ +plugins { + id 'java' +} + +group = 'org.cdm.debug' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.java-websocket:Java-WebSocket:1.5.3' + implementation 'com.google.code.gson:gson:2.10.1' + testImplementation platform('org.junit:junit-bom:5.10.0') + testImplementation 'org.junit.jupiter:junit-jupiter' +} + +test { + useJUnitPlatform() +} + +jar { + from { + configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } + } + + duplicatesStrategy = DuplicatesStrategy.EXCLUDE +} + +sourceCompatibility = JavaVersion.VERSION_1_8 +targetCompatibility = JavaVersion.VERSION_1_8 diff --git a/cdp-java/gradle/wrapper/gradle-wrapper.jar b/cdp-java/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/cdp-java/gradle/wrapper/gradle-wrapper.jar differ diff --git a/cdp-java/gradle/wrapper/gradle-wrapper.properties b/cdp-java/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..80da607 --- /dev/null +++ b/cdp-java/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Aug 02 04:45:08 NOVT 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/cdp-java/gradlew b/cdp-java/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/cdp-java/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/cdp-java/gradlew.bat b/cdp-java/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/cdp-java/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/cdp-java/settings.gradle b/cdp-java/settings.gradle new file mode 100644 index 0000000..06bd8a9 --- /dev/null +++ b/cdp-java/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'cdp-java' + diff --git a/cdp-java/src/main/java/org/cdm/debug/MessageHandler.java b/cdp-java/src/main/java/org/cdm/debug/MessageHandler.java new file mode 100644 index 0000000..daa2455 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/MessageHandler.java @@ -0,0 +1,182 @@ +package org.cdm.debug; + +import com.google.gson.Gson; +import org.cdm.debug.dto.*; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +public abstract class MessageHandler extends Thread { + private BlockingQueue messageQueue; + private Consumer sendMessageCallback; + + private boolean stopped = false; + + public void setMessageQueue(BlockingQueue messageQueue) { + this.messageQueue = messageQueue; + } + + public void setSendMessageCallback(Consumer sendMessageCallback) { + this.sendMessageCallback = sendMessageCallback; + } + + protected void sendMessage(String message) { + if (sendMessageCallback != null) { + sendMessageCallback.accept(message); + } + } + + protected void sendResponse(DebuggerResponse response) { + sendMessage( + new Gson().toJson(response) + ); + } + + protected void sendDebugEvent(String eventType) { + sendMessage( + new Gson().toJson( + new DebugEvent(eventType) + ) + ); + } + + @Override + public void run() { + while (!stopped) { + handleMessage(true); + } + } + + public void requestStop() { + stopped = true; + this.interrupt(); + } + + public void handleMessage(boolean block) { + if (!block && messageQueue.isEmpty()) { + return; + } + + RawMessage message; + + try { + message = messageQueue.poll(100, TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + stopped = true; + return; + } + + if (message == null) { + return; + } + + System.out.printf("%s %s\n", message.action, message.data); + + DebuggerResponse response; + + switch (message.action) { + case MessageActions.PING: + response = new PingResponse("Pong"); + break; + case MessageActions.SET_BREAKPOINTS: + response = handleBreakpointsMessage( + new Gson().fromJson(message.data, BreakpointsMessage.class) + ); + break; + case MessageActions.SET_LINE_LOCATIONS: + response = handleLineLocationsMessage( + new Gson().fromJson(message.data, LineLocationsMessage.class) + ); + break; + case MessageActions.STEP: + response = handleStepMessage(); + break; + case MessageActions.RUN: + response = handleRunMessage( + new Gson().fromJson(message.data, RunMessage.class) + ); + break; + case MessageActions.PAUSE: + response = handlePauseMessage(); + break; + case MessageActions.RESET: + response = handleResetMessage(); + break; + case MessageActions.LOAD: + String source = new Gson().fromJson( + message.data.get(LoadMessage.SOURCE_FIELD), + String.class + ); + + switch (source) { + case PathLoadMessage.SOURCE: + response = handlePathLoadMessage( + new Gson().fromJson(message.data, PathLoadMessage.class) + ); + break; + case BytesLoadMessage.SOURCE: + response = handleBytesLoadMessage( + new Gson().fromJson(message.data, BytesLoadMessage.class) + ); + break; + default: + response = new FailResponse("Unknown source: " + source); + } + break; + case MessageActions.INIT: + response = handleInitMessage( + new Gson().fromJson(message.data, InitializationMessage.class) + ); + break; + case MessageActions.GET_REGISTERS: + response = handleGetRegistersMessage(); + break; + case MessageActions.GET_MEMORY: + response = handleGetMemoryMessage( + new Gson().fromJson(message.data, GetMemoryMessage.class) + ); + break; + case MessageActions.SET_MEMORY: + response = handleSetMemoryMessage( + new Gson().fromJson(message.data, SetMemoryMessage.class) + ); + break; + case MessageActions.GET_TUNNEL: + response = handleGetTunnelMessage( + new Gson().fromJson(message.data, GetTunnelMessage.class) + ); + break; + default: + response = new FailResponse("Unknown action: " + message.action); + } + + sendResponse(response); + } + + protected abstract DebuggerResponse handleBreakpointsMessage(BreakpointsMessage message); + + protected abstract DebuggerResponse handleLineLocationsMessage(LineLocationsMessage message); + + protected abstract DebuggerResponse handleStepMessage(); + + protected abstract DebuggerResponse handleRunMessage(RunMessage message); + + protected abstract DebuggerResponse handlePauseMessage(); + + protected abstract DebuggerResponse handleResetMessage(); + + protected abstract DebuggerResponse handleInitMessage(InitializationMessage message); + + protected abstract DebuggerResponse handleGetRegistersMessage(); + + protected abstract DebuggerResponse handleGetMemoryMessage(GetMemoryMessage message); + + protected abstract DebuggerResponse handlePathLoadMessage(PathLoadMessage message); + + protected abstract DebuggerResponse handleBytesLoadMessage(BytesLoadMessage message); + + protected abstract DebuggerResponse handleSetMemoryMessage(SetMemoryMessage message); + + protected abstract DebuggerResponse handleGetTunnelMessage(GetTunnelMessage message); +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/ActionResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/ActionResponse.java new file mode 100644 index 0000000..eccb12d --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/ActionResponse.java @@ -0,0 +1,9 @@ +package org.cdm.debug.dto; + +public class ActionResponse extends SuccessResponse { + public String action; + + public ActionResponse(String action) { + this.action = action; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/BreakpointsMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/BreakpointsMessage.java new file mode 100644 index 0000000..57c1c82 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/BreakpointsMessage.java @@ -0,0 +1,8 @@ +package org.cdm.debug.dto; + +import java.util.List; + +public class BreakpointsMessage implements DebuggerMessage { + public List breakpoints; + public Integer context; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/BytesLoadMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/BytesLoadMessage.java new file mode 100644 index 0000000..230ce8f --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/BytesLoadMessage.java @@ -0,0 +1,6 @@ +package org.cdm.debug.dto; + +public class BytesLoadMessage extends LoadMessage { + public static final String SOURCE = "bytes"; + public int[] bytes; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/DebugEvent.java b/cdp-java/src/main/java/org/cdm/debug/dto/DebugEvent.java new file mode 100644 index 0000000..7d9eb04 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/DebugEvent.java @@ -0,0 +1,19 @@ +package org.cdm.debug.dto; + +public class DebugEvent extends SuccessResponse { + public static final String REASON_FETCH = "fetch"; + public static final String REASON_BREAKPOINT = "breakpoint"; + public static final String REASON_LINE = "line"; + public static final String REASON_EXCEPTION = "exception"; + public static final String REASON_HALT = "halt"; + public static final String REASON_PAUSE = "pause"; + public static final String REASON_UNKNOWN = "unknown"; + + public String action = "debugEvent"; + + String reason; + + public DebugEvent(String reason) { + this.reason = reason; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/DebuggerMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/DebuggerMessage.java new file mode 100644 index 0000000..27399c7 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/DebuggerMessage.java @@ -0,0 +1,4 @@ +package org.cdm.debug.dto; + +public interface DebuggerMessage { +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/DebuggerResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/DebuggerResponse.java new file mode 100644 index 0000000..ab87a1d --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/DebuggerResponse.java @@ -0,0 +1,4 @@ +package org.cdm.debug.dto; + +public interface DebuggerResponse { +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/FailResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/FailResponse.java new file mode 100644 index 0000000..f16d52e --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/FailResponse.java @@ -0,0 +1,10 @@ +package org.cdm.debug.dto; + +public class FailResponse implements DebuggerResponse { + public String status = "FAIL"; + public String message; + + public FailResponse(String message) { + this.message = message; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/GetMemoryMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/GetMemoryMessage.java new file mode 100644 index 0000000..3cb8c58 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/GetMemoryMessage.java @@ -0,0 +1,6 @@ +package org.cdm.debug.dto; + +public class GetMemoryMessage implements DebuggerMessage { + public Integer offset; + public Integer size; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/GetMemoryResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/GetMemoryResponse.java new file mode 100644 index 0000000..3f1300d --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/GetMemoryResponse.java @@ -0,0 +1,12 @@ +package org.cdm.debug.dto; + +import java.util.List; + +public class GetMemoryResponse extends SuccessResponse { + public String action = MessageActions.GET_MEMORY; + public List bytes; + + public GetMemoryResponse(List bytes) { + this.bytes = bytes; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/GetRegistersResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/GetRegistersResponse.java new file mode 100644 index 0000000..5efbf6a --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/GetRegistersResponse.java @@ -0,0 +1,12 @@ +package org.cdm.debug.dto; + +import java.util.List; + +public class GetRegistersResponse extends SuccessResponse { + public String action = MessageActions.GET_REGISTERS; + public List registers; + + public GetRegistersResponse(List registers) { + this.registers = registers; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/GetTunnelMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/GetTunnelMessage.java new file mode 100644 index 0000000..a086b90 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/GetTunnelMessage.java @@ -0,0 +1,5 @@ +package org.cdm.debug.dto; + +public class GetTunnelMessage implements DebuggerMessage { + public String name; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/GetTunnelResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/GetTunnelResponse.java new file mode 100644 index 0000000..7f80538 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/GetTunnelResponse.java @@ -0,0 +1,10 @@ +package org.cdm.debug.dto; + +public class GetTunnelResponse extends SuccessResponse { + public String action = MessageActions.GET_TUNNEL; + public Integer value; + + public GetTunnelResponse(Integer value) { + this.value = value; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/InitializationMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/InitializationMessage.java new file mode 100644 index 0000000..e13d37c --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/InitializationMessage.java @@ -0,0 +1,6 @@ +package org.cdm.debug.dto; + +public class InitializationMessage implements DebuggerMessage { + public String target; + public String memoryConfiguration = MemoryConfiguratons.HARVARD; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/InitializationResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/InitializationResponse.java new file mode 100644 index 0000000..1385937 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/InitializationResponse.java @@ -0,0 +1,19 @@ +package org.cdm.debug.dto; + +import java.util.List; + +public class InitializationResponse extends SuccessResponse { + public final String action = MessageActions.INIT; + + boolean supportsExceptions; + List registerNames; + List registerSizes; + int ramSize; + + public InitializationResponse(boolean supportsExceptions, List registerNames, List registerSizes, int ramSize) { + this.supportsExceptions = supportsExceptions; + this.registerNames = registerNames; + this.registerSizes = registerSizes; + this.ramSize = ramSize; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/LineLocationsMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/LineLocationsMessage.java new file mode 100644 index 0000000..f24c985 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/LineLocationsMessage.java @@ -0,0 +1,8 @@ +package org.cdm.debug.dto; + +import java.util.List; + +public class LineLocationsMessage implements DebuggerMessage { + public List lineLocations; + public Integer context; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/LoadMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/LoadMessage.java new file mode 100644 index 0000000..bbd1693 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/LoadMessage.java @@ -0,0 +1,5 @@ +package org.cdm.debug.dto; + +public class LoadMessage implements DebuggerMessage { + public static final String SOURCE_FIELD = "source"; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/MemoryConfiguratons.java b/cdp-java/src/main/java/org/cdm/debug/dto/MemoryConfiguratons.java new file mode 100644 index 0000000..0e6ad0a --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/MemoryConfiguratons.java @@ -0,0 +1,6 @@ +package org.cdm.debug.dto; + +public class MemoryConfiguratons { + public static final String VON_NEUMANN = "vonNeumann"; + public static final String HARVARD = "harvard"; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/MessageActions.java b/cdp-java/src/main/java/org/cdm/debug/dto/MessageActions.java new file mode 100644 index 0000000..f784281 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/MessageActions.java @@ -0,0 +1,17 @@ +package org.cdm.debug.dto; + +public class MessageActions { + public static final String PING = "ping"; + public static final String SET_BREAKPOINTS = "setBreakpoints"; + public static final String SET_LINE_LOCATIONS = "setLineLocations"; + public static final String STEP = "step"; + public static final String RUN = "run"; + public static final String PAUSE = "pause"; + public static final String RESET = "reset"; + public static final String LOAD = "load"; + public static final String INIT = "init"; + public static final String GET_REGISTERS = "getRegisters"; + public static final String GET_MEMORY = "getMemory"; + public static final String SET_MEMORY = "setMemory"; + public static final String GET_TUNNEL = "getTunnel"; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/PathLoadMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/PathLoadMessage.java new file mode 100644 index 0000000..2905bff --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/PathLoadMessage.java @@ -0,0 +1,6 @@ +package org.cdm.debug.dto; + +public class PathLoadMessage extends LoadMessage { + public static final String SOURCE = "path"; + public String path; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/PingResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/PingResponse.java new file mode 100644 index 0000000..9c72b33 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/PingResponse.java @@ -0,0 +1,10 @@ +package org.cdm.debug.dto; + +public class PingResponse extends SuccessResponse { + public String action = MessageActions.PING; + public String message; + + public PingResponse(String message) { + this.message = message; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/RawMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/RawMessage.java new file mode 100644 index 0000000..62ab2b2 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/RawMessage.java @@ -0,0 +1,10 @@ +package org.cdm.debug.dto; + +import com.google.gson.JsonObject; + +public class RawMessage { + + public static final String ACTION_FIELD = "action"; + public String action; + public JsonObject data; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/RunMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/RunMessage.java new file mode 100644 index 0000000..3a224d5 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/RunMessage.java @@ -0,0 +1,7 @@ +package org.cdm.debug.dto; + +import java.util.List; + +public class RunMessage implements DebuggerMessage { + public List stopConditions; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/SetMemoryMessage.java b/cdp-java/src/main/java/org/cdm/debug/dto/SetMemoryMessage.java new file mode 100644 index 0000000..0a39660 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/SetMemoryMessage.java @@ -0,0 +1,6 @@ +package org.cdm.debug.dto; + +public class SetMemoryMessage implements DebuggerMessage { + public Integer offset; + public Integer value; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/dto/SuccessResponse.java b/cdp-java/src/main/java/org/cdm/debug/dto/SuccessResponse.java new file mode 100644 index 0000000..2c60180 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/dto/SuccessResponse.java @@ -0,0 +1,5 @@ +package org.cdm.debug.dto; + +public class SuccessResponse implements DebuggerResponse { + public final String status = "OK"; +} diff --git a/cdp-java/src/main/java/org/cdm/debug/runtime/ProcessorInfo.java b/cdp-java/src/main/java/org/cdm/debug/runtime/ProcessorInfo.java new file mode 100644 index 0000000..379841c --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/runtime/ProcessorInfo.java @@ -0,0 +1,11 @@ +package org.cdm.debug.runtime; + +import java.util.List; + +public interface ProcessorInfo { + String getDisplayName(); + int getMemorySize(); + List getRegisterNames(); + List getRegisterSizes(); + boolean supportsExceptions(); +} diff --git a/cdp-java/src/main/java/org/cdm/debug/runtime/ProcessorState.java b/cdp-java/src/main/java/org/cdm/debug/runtime/ProcessorState.java new file mode 100644 index 0000000..08efebe --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/runtime/ProcessorState.java @@ -0,0 +1,17 @@ +package org.cdm.debug.runtime; + +import java.util.List; + +public interface ProcessorState { + boolean isFetching(); + boolean isHalted(); + int getProgramCounter(); + List getRegisters(); + + default boolean exceptionHappened() { + throw new UnsupportedOperationException(); + } + default int getExceptionNumber() { + throw new UnsupportedOperationException(); + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/runtime/StopConditions.java b/cdp-java/src/main/java/org/cdm/debug/runtime/StopConditions.java new file mode 100644 index 0000000..b9f82ed --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/runtime/StopConditions.java @@ -0,0 +1,99 @@ +package org.cdm.debug.runtime; + +import org.cdm.debug.dto.DebugEvent; + +import java.util.List; + +public class StopConditions { + private boolean stopOnException = false; + private boolean stopOnLine = false; + private boolean stopOnBreakpoint = false; + private boolean stopOnFetch = false; + + public StopConditions exception() { + stopOnException = true; + + return this; + } + + public StopConditions line() { + stopOnLine = true; + + return this; + } + + public StopConditions breakpoint() { + stopOnBreakpoint = true; + + return this; + } + + public StopConditions fetch() { + stopOnFetch = true; + + return this; + } + + public StopConditions all() { + stopOnBreakpoint = true; + stopOnLine = true; + stopOnException = true; + stopOnFetch = true; + + return this; + } + + public boolean stopOnBreakpoint() { + return stopOnBreakpoint; + } + + public boolean stopOnLine() { + return stopOnLine; + } + + public boolean stopOnException() { + return stopOnException; + } + + public boolean stopOnFetch() { + return stopOnFetch; + } + + public static StopConditions fromStrings(List strings) { + StopConditions stopConditions = new StopConditions(); + + stopConditions.stopOnFetch = strings.contains(DebugEvent.REASON_FETCH); + stopConditions.stopOnLine = strings.contains(DebugEvent.REASON_LINE); + stopConditions.stopOnBreakpoint = strings.contains(DebugEvent.REASON_BREAKPOINT); + stopConditions.stopOnException = strings.contains(DebugEvent.REASON_EXCEPTION); + + return stopConditions; + } + + public static StopConditions check( + ProcessorState state, + ProcessorInfo adapter, + StopConditions stopConditions, + List breakpoints, + List lineLocations + ) { + StopConditions checkedStopConditions = new StopConditions(); + + checkedStopConditions.stopOnFetch = state.isFetching() && stopConditions.stopOnFetch(); + + checkedStopConditions.stopOnBreakpoint = state.isFetching() && stopConditions.stopOnBreakpoint() + && breakpoints.contains(state.getProgramCounter()); + + checkedStopConditions.stopOnLine = state.isFetching() && stopConditions.stopOnLine() + && lineLocations.contains(state.getProgramCounter()); + + if (adapter.supportsExceptions()) { + checkedStopConditions.stopOnException = state.isFetching() && stopConditions.stopOnException() + && state.exceptionHappened(); + } else { + checkedStopConditions.stopOnException = false; + } + + return checkedStopConditions; + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/server/Server.java b/cdp-java/src/main/java/org/cdm/debug/server/Server.java new file mode 100644 index 0000000..f7cdaeb --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/server/Server.java @@ -0,0 +1,118 @@ +package org.cdm.debug.server; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.cdm.debug.MessageHandler; +import org.cdm.debug.dto.RawMessage; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; + +import java.net.BindException; +import java.net.InetSocketAddress; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.function.Supplier; + +public class Server extends WebSocketServer { + + private static final int DEFAULT_PORT = 7001; + private static final int QUEUE_INITIAL_CAPACITY = 100; + + private final BlockingQueue messageQueue = new ArrayBlockingQueue<>(QUEUE_INITIAL_CAPACITY); + private final Supplier messageHandlerFactory; + + private MessageHandler messageHandler; + + private WebSocket currentConnection; + + public Server(Supplier messageHandlerFactory) { + super(new InetSocketAddress(DEFAULT_PORT)); + + this.messageHandlerFactory = messageHandlerFactory; + } + public Server(int port, Supplier messageHandlerFactory) { + super(new InetSocketAddress(port)); + + this.messageHandlerFactory = messageHandlerFactory; + } + + public BlockingQueue getMessageQueue() { + return messageQueue; + } + + @Override + public void stop() throws InterruptedException { + if (messageHandler != null) { + messageHandler.requestStop(); + } + + super.stop(); + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + if (this.getConnections().size() > 1) { + conn.close(); + System.err.println("Already connected"); + return; + } + + currentConnection = conn; + //DebuggerComponent.setServerStatus(ServerStatus.CONNECTED); + System.out.println("Debug client connected"); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + currentConnection = null; + //DebuggerComponent.setServerStatus(ServerStatus.WAITING); + System.out.println("Debug client disconnected"); + } + + @Override + public void onMessage(WebSocket conn, String message) { + System.out.println("Got message " + message); + + Gson gson = new Gson(); + + JsonObject parsedMessage = gson.fromJson(message, JsonObject.class); + + RawMessage rawMessage = new RawMessage(); + + rawMessage.action = gson.fromJson( + parsedMessage.get(RawMessage.ACTION_FIELD), + String.class + ); + rawMessage.data = parsedMessage; + + messageQueue.add(rawMessage); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + if (ex instanceof BindException) { + //DebuggerComponent.setServerStatus("Bind error"); + } else { + //DebuggerComponent.setServerStatus(ex.getMessage()); + } + + System.err.println("Debug server error: " + ex); + } + + @Override + public void onStart() { + System.out.println("Started debug server on " + this.getAddress()); + + messageHandler = messageHandlerFactory.get(); + messageHandler.setMessageQueue(messageQueue); + messageHandler.setSendMessageCallback(this::sendMessage); + messageHandler.start(); + } + + public void sendMessage(String message) { + if (currentConnection != null && currentConnection.isOpen()) { + currentConnection.send(message); + } + } +} diff --git a/cdp-java/src/main/java/org/cdm/debug/server/ServerStatus.java b/cdp-java/src/main/java/org/cdm/debug/server/ServerStatus.java new file mode 100644 index 0000000..64fc808 --- /dev/null +++ b/cdp-java/src/main/java/org/cdm/debug/server/ServerStatus.java @@ -0,0 +1,7 @@ +package org.cdm.debug.server; + +public class ServerStatus { + public static final String DOWN = "Server down"; + public static final String WAITING = "Waiting for client"; + public static final String CONNECTED = "Client connected"; +}