Skip to content
Open
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
60 changes: 56 additions & 4 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,27 @@ that provides a completely automated preprocessing, compilation, installation
and profiling of JavaCard code on JavaCard smart cards or in the jCardSim
simulator.

Why profiling?
--------------
* *Side-channel security* -- non-constant execution time or memory usage can leak secret key material. The per-trap histograms immediately reveal whether a branch or loop depends on secret data.
* *Performance optimisation* -- identify slow operations and decide whether to move them to native JavaCard commands.
* *Hardware validation* -- confirm that your applet behaves identically on the real card and in the simulator before deployment.

What you get
~~~~~~~~~~~~
After a successful run, JCProfilerNext produces:

* timing or memory measurements,
* an interactive visualisation of those measurements with per-line histograms,
* original source files annotated with inline measurement comments,
* frequency table of every JavaCard API call made by your applet (stats mode only).

Prerequisites
-------------
* Install JDK 8 or newer.
* Obtain a copy of the JavaCard Development Kit, e.g. from this link:https://github.com/martinpaljak/oracle_javacard_sdks[GitHub archive] maintained by Martin Paljak.
* [Real card only] The card must have sufficient free EEPROM space for your applet. The instrumented applet is larger than the original (profiling traps are inserted), so ensure a few extra kilobytes are available. Use `--simulator` to avoid this requirement entirely.
* [Real card only] A PC/SC-compatible smart card reader and its drivers must be installed.

.Compatibility Matrix
[cols="^1,^2"]
Expand Down Expand Up @@ -40,6 +57,16 @@ Compilation
.. directly using Gradle: `./gradlew run --args='--help'`.
.. directly using built JAR: `java -jar build/libs/JCProfilerNext-1.0-SNAPSHOT.jar --help`.
.. directly from distribution archives in `build/distributions`.
.. as a standalone binary (recommended): run `./gradlew installDist`, then use
`build/install/JCProfilerNext/bin/JCProfilerNext` (Unix) or
`build\install\JCProfilerNext\bin\JCProfilerNext.bat` (Windows).
You can add this `bin/` directory to your `PATH` for convenient access.

Profiling Applet Uninstallation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you installed an applet on a real card during a profiling run, remove it using
link:https://github.com/martinpaljak/GlobalPlatformPro[GlobalPlatformPro]:
The default package AID is `123456789001` and the default applet AID is `12345678900101`.

Execution modes
---------------
Expand All @@ -58,7 +85,7 @@ locating a user-provided delimiter pattern inside each captured trace.
This mode is currently under development and available in the
link:https://github.com/crocs-muni/JCProfilerNext/tree/spa-time[`spa-time` branch].

Time Example
Time example
~~~~~~~~~~~~
Consider the `example` method in the following class. The outer loop is clearly
not constant since its iteration count depends on the input value. On the other
Expand Down Expand Up @@ -108,8 +135,11 @@ public class Example extends Applet {
Run as:
[source,console]
----
$ ./gradlew run --args="--work-dir example --jckit jc222_kit --executable example --ins 0xEE --data-regex 00[0-9A-F]{2} --repeat-count 100"
$ ./gradlew run --args="--work-dir example --jckit jc222_kit --entry-point example.Example --executable example --ins 0xEE --data-regex 00[0-9A-F]{2} --repeat-count 100"
----
The `--entry-point` value is the *fully-qualified class name* (`package.ClassName`).
The `--executable` value is the *unqualified method name* (`methodName`).

JCProfilerNext will process all sources in the `example` directory and will
also use this directory to store all intermediate results:

Expand All @@ -125,7 +155,7 @@ produced by JCProfilerNext, you will see that some parts of the code are indeed
not constant, namely if you inspect the corresponding histograms of traps
after the `for` loops.

Memory Example
Memory example
~~~~~~~~~~~~~~
Consider the following source code:

Expand Down Expand Up @@ -169,7 +199,7 @@ deselect memory may also affect the amount of free transient memory and vice ver
See link:https://crocs-muni.github.io/JCProfilerNext/example-memory.html[`measurements.html`]
for visualisation of the measurements.

Stats Example
Stats example
~~~~~~~~~~~~~
Consider the following source code:

Expand Down Expand Up @@ -203,6 +233,28 @@ javacard.security,KeyPair,genKeyPair(),1
javacard.security,KeyPair,"KeyPair(byte,short)",1
----

FAQ
---

*My card is not recognised / connection fails.*::
Check that a PC/SC driver for your reader is installed and that no other application is locking the card.

*Compilation fails with a javac error.*::
Verify that your JDK version is compatible with the target JavaCard SDK — see the Compatibility Matrix.
JDK 8 offers the widest compatibility (JavaCard 2.2.1+).

*The tool crashes with an unexpected exception.*::
Re-run with `--debug`, collect the full output, and open an issue at
https://github.com/crocs-muni/JCProfilerNext.
Please include the `--debug` log and the exact command you ran.

*Measurements are inconsistent between runs.*::
Increase `--repeat-count` (default: 1000) to reduce statistical noise.

*What JDK should I use?*::
JDK 8 is recommended for the widest JavaCard SDK compatibility.
See the Compatibility Matrix under _Prerequisites_ for details.

Limitations
-----------

Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ repositories {

dependencies {
// commandline arguments parsing
implementation 'com.beust:jcommander:1.82'
implementation 'org.jcommander:jcommander:1.85' // last version that supports Java 8

// Spoon
implementation 'fr.inria.gforge.spoon:spoon-core:9.1.0' // last version that supports Java 8
Expand Down
46 changes: 35 additions & 11 deletions src/main/java/jcprofiler/JCProfiler.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,24 @@ private JCProfiler() {}
*/
public static void run(final Args args) {
if (args.mode == Mode.stats) {
log.info("Collecting API usage statistics.");
log.info("");
log.info("+---------------------------------+");
log.info("| Stage 1/1: stats |");
log.info("+---------------------------------+");
new Instrumenter(args).generateStatistics();
log.info("Collecting complete.");
log.info("");
log.info("Done. Results written to: {}", args.workDir.toAbsolutePath());
log.info(" APIstatistics.csv -- API usage frequency table");
return;
}

// Instrumentation
if (args.startFrom.ordinal() <= Stage.instrumentation.ordinal()) {
log.info("Instrumentation started.");
log.info("");
log.info("+---------------------------------+");
log.info("| Stage 1/5: instrumentation |");
log.info("+---------------------------------+");
JCProfilerUtil.moveToSubDirIfNotExists(args.workDir, JCProfilerUtil.getSourceInputDirectory(args.workDir));

new Instrumenter(args).process();
log.info("Instrumentation complete.");
}
Expand All @@ -64,7 +71,10 @@ public static void run(final Args args) {

// Compilation
if (args.startFrom.ordinal() <= Stage.compilation.ordinal()) {
log.info("Compilation started.");
log.info("");
log.info("+---------------------------------+");
log.info("| Stage 2/5: compilation |");
log.info("+---------------------------------+");
Compiler.compile(args, entryPoint);
log.info("Compilation complete.");
}
Expand All @@ -75,11 +85,13 @@ public static void run(final Args args) {
// Installation
CardManager cardManager = null;
if (args.startFrom.ordinal() <= Stage.installation.ordinal()) {
// noop for --simulator
log.info("");
log.info("+---------------------------------+");
log.info("| Stage 3/5: installation |");
log.info("+---------------------------------+");
if (args.useSimulator) {
log.info("Skipping installation because simulator is used.");
log.info("Skipping installation (simulator mode).");
} else {
log.info("Installation started.");
cardManager = Installer.installOnCard(args, entryPoint);
log.info("Installation complete.");
}
Expand All @@ -90,12 +102,15 @@ public static void run(final Args args) {

// Profiling
if (args.startFrom.ordinal() <= Stage.profiling.ordinal()) {
log.info("");
log.info("+---------------------------------+");
log.info("| Stage 4/5: profiling |");
log.info("+---------------------------------+");
// Connect if the installation was skipped or simulator is used
if (cardManager == null)
// TODO: move connection stuff to a separate class?
cardManager = Installer.connect(args, entryPoint);

log.info("Profiling started.");
final AbstractProfiler profiler = AbstractProfiler.create(args, cardManager, model);
profiler.profile();
profiler.generateCSV();
Expand All @@ -106,11 +121,20 @@ public static void run(final Args args) {
return;

// Visualisation
log.info("Visualising results.");
log.info("");
log.info("+---------------------------------+");
log.info("| Stage 5/5: visualisation |");
log.info("+---------------------------------+");
final AbstractVisualiser vis = AbstractVisualiser.create(args, model);
vis.loadAndProcessMeasurements();
vis.generateHTML();
vis.insertMeasurementsToSources();
log.info("Visualising results complete.");
log.info("Visualisation complete.");

log.info("");
log.info("Done. Results written to: {}", args.workDir.toAbsolutePath());
log.info(" measurements.csv -- raw per-trap measurements");
log.info(" measurements.html -- interactive visualisation");
log.info(" sources_perf/ -- sources annotated with inline measurements");
}
}
60 changes: 57 additions & 3 deletions src/main/java/jcprofiler/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package jcprofiler;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.UnixStyleUsageFormatter;

import jcprofiler.args.Args;
import jcprofiler.util.JCProfilerUtil;
Expand All @@ -24,6 +25,7 @@
*/
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private static final String CARD_MANAGER_LOGGER = "cz.muni.fi.crocs.rcard.client.CardManager";

/**
* JCProfilerNext's entry point method
Expand All @@ -32,13 +34,22 @@ public class Main {
*/
public static void main(final String[] argv) {
Configurator.setRootLevel(Level.INFO);
Configurator.setLevel(CARD_MANAGER_LOGGER, Level.WARN);

// parse commandline arguments
final Args args = new Args();
final JCommander jc = JCommander.newBuilder()
.addObject(args)
.programName("JCProfilerNext")
.build();
jc.setUsageFormatter(new UnixStyleUsageFormatter(jc));

// show help
if (argv.length == 0) {
jc.usage();
printHelpExtras();
return;
}

try {
jc.parse(argv);
Expand All @@ -47,19 +58,24 @@ public static void main(final String[] argv) {
System.exit(1);
}

// show help
if (args.help) {
jc.usage();
printHelpExtras();
return;
}

// TODO: add proper versioning info as well
log.info("Welcome to JCProfilerNext!");
log.info("Command-line arguments parsed successfully.");
if (args.debug) {
if (args.trace) {
args.debug = true;
Configurator.setRootLevel(Level.TRACE);
Configurator.setLevel(CARD_MANAGER_LOGGER, Level.TRACE);
log.info("LogLevel set to TRACE.");
} else if (args.debug) {
Configurator.setRootLevel(Level.DEBUG);
log.info("LogLevel set to DEBUG.");
}
Comment thread
xhanulik marked this conversation as resolved.
Resolved
log.debug("Command-line arguments parsed successfully.");

// log basic info
log.info("Found JavaCard SDK {} ({})", args.jcSDK.getRelease(), args.jcSDK.getRoot().getAbsolutePath());
Expand All @@ -82,6 +98,44 @@ public static void main(final String[] argv) {
}
}

private static void printHelpExtras() {
System.out.println();
System.out.println("ARGUMENT STRUCTURE");
System.out.println(" Required arguments for a profiling run: --work-dir and --jckit.");
System.out.println(" --entry-point expects a fully-qualified class name: package.ClassName");
System.out.println(" --executable expects an unqualified method name: myMethod");
System.out.println(" Hex values (--cla, --ins, --p1, --p2, --reset-ins) accept either a plain");
System.out.println(" hex number (e.g. EE) or a 0x-prefixed value (e.g. 0xEE).");
System.out.println(" Either --data-regex or --data-file must be provided when profiling a method");
System.out.println(" (not needed for memory profiling of the constructor or stats mode).");
System.out.println();
System.out.println("EXAMPLES");
System.out.println();
System.out.println(" # Profile a specific method (time mode, real card):");
System.out.println(" JCProfilerNext --work-dir path/to/applet --jckit path/to/jc304_kit \\");
System.out.println(" --entry-point com.example.MyApplet --executable myMethod \\");
System.out.println(" --repeat-count 100 --data-regex \"[0-9A-F]{64}\" --mode time");
System.out.println();
System.out.println(" # Profile a method using the simulator, no entry-point needed (single applet):");
System.out.println(" JCProfilerNext --work-dir path/to/applet --jckit path/to/jc222_kit \\");
System.out.println(" --executable myMethod --ins 0xEE \\");
System.out.println(" --data-regex 00[0-9A-F]{2} --simulator");
System.out.println();
System.out.println(" # Measure memory usage during constructor (no --executable needed):");
System.out.println(" JCProfilerNext --work-dir path/to/applet --jckit path/to/jc304_kit --mode memory");
System.out.println();
System.out.println(" # Collect API usage statistics:");
System.out.println(" JCProfilerNext --work-dir path/to/applet --jckit path/to/jc222_kit --mode stats");
System.out.println();
System.out.println(" # Run only instrumentation and compilation, skip installation/profiling:");
System.out.println(" JCProfilerNext --work-dir path/to/applet --jckit path/to/jc222_kit \\");
System.out.println(" --stop-after compilation");
System.out.println();
System.out.println("REPORTING BUGS");
System.out.println(" If you encounter an unexpected error, re-run with --debug, save the output,");
System.out.println(" and open an issue at https://github.com/crocs-muni/JCProfilerNext");
}

/**
* Validates command line arguments.
*
Expand Down
Loading
Loading