This commit is contained in:
kod 2020-08-07 13:48:00 -07:00
parent 403a12fc50
commit 752cf24624
265 changed files with 17944 additions and 1 deletions

2
50
View File

@ -1 +1 @@
aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaama
aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaaga

View File

@ -0,0 +1,22 @@
pwndbg
cyclic
file parse
run
cyclic
cyclic -h
cyclic 50 > 50
cyclic 50
r < cyclic 50
r < 50
cyclic -l 0x0000555555555751
pwndbg
r2
cyclic 50 -n 8
r
r
r < aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaaga
r < "aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaaga"
r < echo "aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaaga"
r <(echo "aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaaga")
dashboard
refresh

1
funtools-1.4.7/fitsy/50 Normal file
View File

@ -0,0 +1 @@
aaaaaaaabaaaaaaacaaaaaaadaaaaaaaeaaaaaaafaaaaaaaga

0
master Normal file
View File

1
r2ghidra-dec Submodule

@ -0,0 +1 @@
Subproject commit 17ec3b3041e21f0492878e1d3147cdcd5830ae00

1
radare2-r2pipe/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__

31
radare2-r2pipe/Makefile Normal file
View File

@ -0,0 +1,31 @@
VERSION=4.3.0
REMOTE=ocaml go rust erlang
DISTDIR=radare2-r2pipe-$(VERSION)
ORIGIN=$(shell cat "$@/ORIGIN" 2> /dev/null)
all:
@echo Nothing to do.
clean:
for a in */Makefile ; do $(MAKE) -C $$a ; done
-rm -rf */node_modules
dist:
git clone . $(DISTDIR)
$(MAKE) -C $(DISTDIR) rsync
rm -rf $(DISTDIR)/.git
tar czvf $(DISTDIR).tar.gz $(DISTDIR)
rm -rf $(DISTDIR)
$(REMOTE):
git clone "$(ORIGIN)" "$@.git"
mv "$@/ORIGIN" .
rm -rf "$@/"*
cp -rf "$@.git/"* "$@/"
rm -rf $@.git
mv ORIGIN "$@"
sync: $(REMOTE)
.PHONY: sync rsync clean all $(REMOTE)

View File

@ -0,0 +1,31 @@
VERSION=@VERSION@
REMOTE=ocaml go rust erlang
DISTDIR=radare2-r2pipe-$(VERSION)
ORIGIN=$(shell cat "$@/ORIGIN" 2> /dev/null)
all:
@echo Nothing to do.
clean:
for a in */Makefile ; do $(MAKE) -C $$a ; done
-rm -rf */node_modules
dist:
git clone . $(DISTDIR)
$(MAKE) -C $(DISTDIR) rsync
rm -rf $(DISTDIR)/.git
tar czvf $(DISTDIR).tar.gz $(DISTDIR)
rm -rf $(DISTDIR)
$(REMOTE):
git clone "$(ORIGIN)" "$@.git"
mv "$@/ORIGIN" .
rm -rf "$@/"*
cp -rf "$@.git/"* "$@/"
rm -rf $@.git
mv ORIGIN "$@"
sync: $(REMOTE)
.PHONY: sync rsync clean all $(REMOTE)

76
radare2-r2pipe/README.md Normal file
View File

@ -0,0 +1,76 @@
r2pipe
======
![r2pipe logo](https://raw.githubusercontent.com/radare/radare2-r2pipe/master/r2pipe.png)
The r2pipe APIs are based on a single r2 primitive found behind `r_core_cmd_str()`
which is a function that accepts a string parameter describing the r2 command to
run and returns a string with the result.
The decision behind this design comes from a series of benchmarks with different
libffi implementations and resulted that using the native API is more complex and
slower than just using raw command strings and parsing the output.
As long as the output can be tricky to parse, it's recommended to use the JSON
output and deserializing them into native language objects which results much more
handy than handling and maintaining internal data structures and pointers.
Also, memory management results into a much simpler thing because you only have
to care about freeing the resulting string.
This directory contains different implementations of the r2pipe API for different
languages which could handle different communication backends:
* Grab R2PIPE{_IN|_OUT} environment variables
* Spawn r2 -q0 and communicate with pipe(2)
* Plain TCP connection
* HTTP queries (connecting to a remote webserver)
* RAP protocol (r2 own's remote protocol)
Most of the language enable asyncronous capabilities in order to handle the result
of the operation in a callback, allowing a single program to interact with multiple
instances or connections to different r2 sessions at the same time.
* Syncronous
* Asyncronous
In addition, r2pipe scripts can be used to write plugins for radare2 or extend current functionalities:
* Assembler/Disassembler plugin for RAsm
* RIO plugin to abstract read/write/system operations
* Syscall handler for the ESIL emulator
* ...
The most supported languages are:
* NodeJS
* Python
* Swift
* C/Nim/Vala/C++
But there is r2pipe for:
pipe spawn async http tcp rap json plug lib buff
C X X - X X X X X X X
C++/Qt X X - - - - X - X -
C# / F# X X X X - - - - X -
D X - - - - - X - - -
Erlang X X - - - - - - - -
Go X X - - - - X - - -
Haskell X X - X - - X - - -
Java/Groovy - X - X - - - - X -
Lisp - X - - - - X - - -
NewLisp X X - X - - X - X -
Nim - - - X - - X - X -
NodeJS X X X X X - X X - X
Ocaml - X - - - - X - - -
Perl X X - X X - X - - -
PHP - X - - - - - - - -
Python X X X X X X X X X -
Ruby X X - - - - X - - -
Rust X X - X X - X - - -
Swift X X X X - - X - X -
Vala - X X - - - - - - -
Clojure X X - - - - - - - -
--pancake

27
radare2-r2pipe/autogen.sh Executable file
View File

@ -0,0 +1,27 @@
#!/bin/sh
#
# Look for the 'acr' tool here: https://github.com/radare/acr
# Clone last version of ACR from here:
# git clone https://github.com/radare/acr
#
# -- pancake
r2pm -h >/dev/null 2>&1
if [ $? = 0 ]; then
echo "Installing the last version of 'acr'..."
r2pm -i acr > /dev/null
r2pm -r acr -h > /dev/null 2>&1
if [ $? = 0 ]; then
echo "Running 'acr -p'..."
r2pm -r acr -p
else
echo "Cannot find 'acr' in PATH"
fi
else
echo "Running acr..."
acr -p
fi
if [ -n "$1" ]; then
echo "./configure $*"
./configure $*
fi

26
radare2-r2pipe/c/Makefile Normal file
View File

@ -0,0 +1,26 @@
CFLAGS+=$(shell pkg-config --cflags r_socket)
LDFLAGS+=$(shell pkg-config --libs r_socket)
TESTS=test-pipe test-pipe2 test-spawn
all: $(TESTS)
test-pipe:
$(CC) -o test-pipe test-pipe.c $(CFLAGS) $(LDFLAGS)
r2 -q -c '#!pipe ./test-pipe' /bin/ls
test-pipe2:
$(CC) -o test-pipe2 test-pipe2.c $(CFLAGS) $(LDFLAGS)
#r2 -q -c '#!pipe ./test-pipe2' /bin/ls
./test-pipe2
test-spawn:
$(CC) -o test-spawn test-spawn.c $(CFLAGS) $(LDFLAGS)
./test-spawn
clean:
rm -f $(TESTS)
rm -f a.out
.PHONY: $(TESTS)

View File

@ -0,0 +1,31 @@
The C r2pipe API
================
It's implemented in `libr_socket`, so it depends on r2 libraries.
Here's a simple usage example:
```c
#include <r_socket.h>
static void r2cmd(R2Pipe *r2, const char *cmd) {
char *msg = r2pipe_cmd (r2, cmd);
if (msg) {
printf ("%s\n", msg);
free (msg);
}
}
int main() {
R2Pipe *r2 = r2pipe_open ("radare2 -q0 /bin/ls");
if (r2) {
r2cmd (r2, "?e Hello World");
r2cmd (r2, "x");
r2cmd (r2, "?e Hello World");
r2cmd (r2, "pd 20");
r2pipe_close (r2);
return 0;
}
return 1;
}
```

BIN
radare2-r2pipe/c/test-pipe Executable file

Binary file not shown.

View File

@ -0,0 +1,21 @@
#include <r_socket.h>
static void r2cmd(R2Pipe *r2, const char *cmd) {
char *msg = r2pipe_cmd (r2, cmd);
if (msg) {
printf ("%s\n", msg);
free (msg);
}
}
int main() {
R2Pipe *r2 = r2pipe_open (NULL);
if (r2) {
r2cmd (r2, "?e Hello World");
r2cmd (r2, "x");
r2cmd (r2, "?e Hello World");
r2pipe_close (r2);
return 0;
}
return 1;
}

BIN
radare2-r2pipe/c/test-pipe2 Executable file

Binary file not shown.

View File

@ -0,0 +1,23 @@
#include <r_socket.h>
static void r2cmd(R2Pipe *r2, const char *cmd) {
char *msg = r2pipe_cmd (r2, cmd);
if (msg) {
printf ("%s\n", msg);
free (msg);
}
}
int main() {
// R2Pipe *r2 = r2pipe_open ("/bin/ls");
R2Pipe *r2 = r2pipe_open ("radare2 -q0 /bin/ls");
if (r2) {
r2cmd (r2, "?e Hello World");
r2cmd (r2, "x");
r2cmd (r2, "?e Hello World");
r2cmd (r2, "pd 20");
r2pipe_close (r2);
return 0;
}
return 1;
}

BIN
radare2-r2pipe/c/test-spawn Executable file

Binary file not shown.

View File

@ -0,0 +1,23 @@
#include <r_socket.h>
static void r2cmd(R2Pipe *r2, const char *cmd) {
char *msg = r2pipe_cmd (r2, cmd);
if (msg) {
printf ("%s\n", msg);
free (msg);
}
}
int main() {
// XXX R2Pipe *r2 = r2pipe_open ("/bin/ls");
R2Pipe *r2 = r2pipe_open ("radare2 -q0 /bin/ls");
if (r2) {
r2cmd (r2, "?e Hello World");
r2cmd (r2, "x");
r2cmd (r2, "?e Hello World");
r2cmd (r2, "pd 20");
r2pipe_close (r2);
return 0;
}
return 1;
}

View File

@ -0,0 +1,33 @@
# r2pipe.clj
`"Know only Clojure and want to work with r2? I got you fam."`
r2pipe.clj is a Clojure library to interact with [radare2](https://github.com/radareorg/radare2). This requires you to have r2 installed on your system. It spawns a new process and communicates with it over pipes.
## Installation
In Leiningen:
[![Clojars Project](https://img.shields.io/clojars/v/org.clojars.chinmay_dd/r2pipe.svg)](https://clojars.org/org.clojars.chinmay_dd/r2pipe)
## Usage
```clojure
;; Start up the REPL and include r2 pipe lib
user=> (require '[r2pipe.core :refer :all])
;; Configure the r2 path. It will default to "/usr/bin/r2".
user=> (configure-path "/usr/bin/r2")
;; Open the file into r2
user=> (r2open "binary")
#'r2pipe.core/pipe
;; Execute a command in r2
user=> (r2cmd "pi 5")
"xor ebp, ebp\npop esi\nmov ecx, esp\nand esp, 0xfffffff0\npush eax\n"
```
### Todo
A lot of things!

View File

@ -0,0 +1,7 @@
(defproject org.clojars.chinmay_dd/r2pipe "0.0.2"
:description "Communicate to Radare2 via pipes"
:dependencies [[org.clojure/clojure "1.8.0"]
[me.raynes/conch "0.8.0"]]
:plugins [[lein-codox "0.9.5"]]
)

View File

@ -0,0 +1,42 @@
(ns r2pipe.core
(:refer-clojure :exclude [read-string])
(:require [me.raynes.conch.low-level :as sh]
[clojure.java.io :as io]))
;; Define the default path for r2 to load.
(def r2path "/usr/bin/r2")
(defn configure-path
"Confgiure the r2 path."
[path]
(def r2path path))
(defn r2open
"Opens a file in r2 and starts a process instance"
[input_file]
(def pipe (sh/proc r2path "-q0" (str input_file))))
(defn r2print
"Read from the r2 process(pipe) and print."
[]
(dotimes [i (.available (get pipe :out))] (print (str (char (.read (get pipe :out)))))))
(defn r2write
"Write to the r2 process"
[input]
(.write (get pipe :in) (.getBytes (str input "\n")))
(.flush (get pipe :in)))
(defn r2string
"Returns a string representation of the output shown by radare2"
[]
(apply str (repeatedly (.available (get pipe :out)) #(str (char (.read (get pipe :out)))))))
(defn r2cmd
"Runs an r2 command and returns the result as a string"
[input]
(do
(r2write input)
;; 1337 hax! This is to offset the latency created due to stream buffering.
(Thread/sleep 1)
(r2string)))

View File

@ -0,0 +1,5 @@
(ns r2pipe-test
(:require [clojure.test :refer :all]
[r2pipe.clj :refer :all]))
;; WRITE TESTS!

314
radare2-r2pipe/configure vendored Executable file
View File

@ -0,0 +1,314 @@
#!/bin/sh
# This script was automatically generated by ACR v1.8.1
# @author: pancake <nopcode.org>
# @url: http://www.nopcode.org
# @repo: git clone https://github.com/radare/acr
[ -z "${AWK}" ] && AWK=awk
do_remove() {
if [ "${ACR_RMFILES}" ]; then
printf "cleaning temporally files... "
rm -f ${ACR_RMFILES}
echo "done"
fi
}
control_c() {
printf "\n\n^C control-c : script execution interrupted.\n"
do_remove
exit 1
}
trap control_c 2
split_host() {
S="$"
while : ; do
ENVWORDS="${ENVWORDS} $1_CPU $1_OS"
STR=`eval "echo ${S}$1"`
SPLIT_CPU="`echo "$STR" | cut -d - -f 1`"
SPLIT_OS="`echo "$STR" | $AWK -F - '{
if ($2=="unknown"){
if (NF<3) { print $2; } else { print $3; }
} else {
if ($2=="linux") { print $2; } else
if (NF<3) { print $2; } else { print $3; }
}
}'`"
eval "$1_CPU=\"$SPLIT_CPU\""
eval "$1_OS=\"$SPLIT_OS\""
shift
[ -z "$1" ] && break
done
}
VPATH=`dirname ${0}`
if [ "${VPATH}" = "." ]; then
WODIS=current
else
if [ "${VPATH}" = "${PWD}" ]; then
VPATH=.
WODIS=current
else
WODIS=crosspath
CURDIR=$PWD
cd $VPATH
VPATH="${PWD}/"
cd $CURDIR
fi
fi
guess_os() {
if [ -e "${VPATH}/config.guess" ]; then
sh ${VPATH}/config.guess
return
fi
CPU="`uname -m|sed -e 's, ,,g'|cut -d - -f 1`"
OS="`uname -s|tr A-Z a-z`"
uname -r | grep -qE "(Microsoft|WSL)" 2>/dev/null && OS="wsl"
GNU="`uname --help 2>&1 | grep gnu`"
[ "${GNU}" ] && OS="${OS}-gnu"
[ "${CPU}" = ppc ] && CPU="powerpc"
echo "${CPU}-unknown-${OS}"
}
SEARCHPATH="/usr /usr/local /usr/pkg /sw"
: ${PREFIX:=/usr/local}
CROSSBUILD=0
BUILD=`guess_os`
HOST="${BUILD}"
TARGET="${HOST}"
SYSCONFDIR=""
create_environ() {
: ${EPREFIX:="${PREFIX}"}
: ${SPREFIX:="${PREFIX}"}
: ${BINDIR:="${SPREFIX}/bin"}
: ${SBINDIR:="${PREFIX}/sbin"}
: ${SYSCONFDIR:="${SPREFIX}/etc"}
: ${LIBDIR:="${SPREFIX}/lib"}
: ${LIBEXECDIR:="${SPREFIX}/libexec"}
: ${INCLUDEDIR:="${SPREFIX}/include"}
: ${DATADIR:="${SPREFIX}/share"}
: ${INFODIR:="${DATADIR}/info"}
: ${MANDIR:="${DATADIR}/man"}
: ${DOCDIR:="${DATADIR}/doc/radare2-r2pipe"}
: ${LOCALSTATEDIR:="${SPREFIX}/var"}
for A in `echo ${PATH} | sed -e 's,:, ,g'` ; do
[ -e "$A"/ginstall ] && : ${INSTALL:="$A"/ginstall} && break
[ -e "$A"/install ] && : ${INSTALL:="$A"/install} && break
done
: ${INSTALL_DIR:=${INSTALL} -d}
: ${INSTALL_DATA:=${INSTALL} -m 644}
: ${INSTALL_SCRIPT:=${INSTALL} -m 755}
: ${INSTALL_PROGRAM:=${INSTALL} -m 755}
: ${INSTALL_PROGRAM_STRIP:=${INSTALL} -m 755 -s}
: ${INSTALL_MAN:=${INSTALL} -m 444}
: ${INSTALL_LIB:=${INSTALL} -m 755 -c}
PKGNAME='radare2-r2pipe' ; VERSION='4.3.0' ; VERSION_MAJOR=4; VERSION_MINOR=3; VERSION_PATCH=0; VERSION_NUMBER=40300; CONTACT_MAIL="pancake@nopcode.org" ; CONTACT_NAME="pancake" ; CONTACT="pancake <pancake@nopcode.org>" ;
}
show_usage() {
cat <<EOF2
'configure' configures radare2-r2pipe-4.3.0 to adapt to many kinds of systems.
Usage: ./configure [OPTION]... [VAR=VALUE]...
To assign environment variables (e.g., CC, CFLAGS...), specify them as
VAR=VALUE. See below for descriptions of some of the useful variables.
Defaults for the options are specified in brackets.
Configuration:
-h, --help display this help and exit
-r, --report show what libs/programs require to work
-V, --version display version information and exit
Installation directories:
--exec-prefix=EPREFIX install arch-dependent files in EPREFIX [PREFIX]
--prefix=PREFIX install arch-independent files in PREFIX [/usr/local]
--sandbox=SPREFIX sandbox prefix directory: SPREFIX [PREFIX]
Fine tuning of the installation directories:
--bindir=DIR user executables [EPREFIX/bin]
--datadir=DIR read-only architecture-independent data [PREFIX/share]
--docdir=DIR documentation directory [DATADIR/doc/radare2-r2pipe]
--includedir=DIR C header files [PREFIX/include]
--infodir=DIR info documentation [DATADIR/info]
--libexecdir=DIR program executables [EPREFIX/libexec]
--libdir=DIR object code libraries [EPREFIX/lib]
--libpath=DIR set rpath/libname-path to linker
--localstatedir=DIR modifiable single-machine data [PREFIX/var]
--mandir=DIR man documentation [DATADIR/man]
--sbindir=DIR system admin executables [EPREFIX/sbin]
--sysconfdir=DIR read-only single-machine data [PREFIX/etc]
--sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com]
System types:
--build=BUILD configure for building on BUILD [guessed]
--host=HOST cross-compile to build programs to run on HOST [BUILD]
--target=TARGET configure for building compilers for TARGET [HOST]
EOF2
printf "
Report bugs to: pancake <pancake@nopcode.org>"
echo ""
exit 0
}
take_environ() {
: ${SH:=/bin/sh}
: ${PREFIX:=/usr/local/}
}
show_version() {
echo "radare2-r2pipe-4.3.0 configuration script done with acr v1.8.1.
The 'Free Software Foundation' message is only for autodetection.
Originally written by pancake <nopcode.org>."
exit 0
}
parse_options() {
flag=`echo $1| cut -d = -f 1`
value=`echo $1| $AWK 'BEGIN{FS="=";}{print $2}'`
flag2=`echo $flag|cut -f2- -d -| sed -e 's,-,_,g' -e 's,^_,,g'|tr '[a-z]' '[A-Z]'`
if [ "${TARGET_OS}" = "darwin" ]; then
LIBPATH=-Wl,-install_name,
else
LIBPATH=-Wl,-R
fi
case $flag in
-h|--help|--hel|--h|--he|-help)
show_usage ; ;;
-V|-version|--version)
show_version ; ;;
-r|--r|--report)
echo "PKGNAME: radare2-r2pipe"
echo "VERSION: 4.3.0"
exit 0
;;
--cache-file)
# ignored: acr have no cache
;;
--build)
BUILD="$value"; split_host BUILD ; ;;
--host)
CROSSBUILD=1 # XXX
HOST="$value"; split_host HOST ; ;;
--target)
TARGET="$value"; split_host TARGET ; ;;
--prefix)
PREFIX="$value"; ;;
--exec-prefix)
EPREFIX="$value"; ;;
--sandbox|--sprefix)
SPREFIX="$value"; ;;
--bindir)
BINDIR="$value"; ;;
--sbindir)
SBINDIR="$value"; ;;
--libexecdir)
LIBEXECDIR="$value"; ;;
--docdir)
DOCDIR="$value"; ;;
--datadir)
DATADIR="$value"; ;;
--sysconfdir)
SYSCONFDIR="$value"; ;;
--sharedstatedir)
SHAREDSTATEDIR="$value"; ;;
--localstatedir)
LOCALSTATEDIR="$value"; ;;
--libdir)
LIBDIR="$value"; ;;
--libpath)
LDFLAGS="${LDFLAGS} ${LIBPATH}$value"; ;;
--includedir)
INCLUDEDIR="$value"; CFLAGS="${CFLAGS} -I$value"; ;;
--infodir)
INFODIR="$value"; ;;
--mandir)
MANDIR="$value"; ;;
*) if [ "$value" ]; then eval "`echo $flag2=$value`" ;
else echo ; echo "WARNING: Unknown flag '$flag'." >&2 ; echo ; fi ;;
esac
}
# MAIN #
take_environ
split_host BUILD HOST TARGET
[ -z "$ACRHOOK" ] && ACRHOOK=./configure.hook
[ -e "$ACRHOOK" ] && . ${ACRHOOK}
while : ; do
[ -z "$1" ] && break
parse_options "$1"
shift
done
ENVWORDS="MANDIR INFODIR LIBDIR INCLUDEDIR LOCALSTATEDIR SYSCONFDIR DATADIR DOCDIR LIBEXECDIR SBINDIR BINDIR EPREFIX PREFIX SPREFIX TARGET HOST BUILD INSTALL INSTALL_LIB INSTALL_MAN INSTALL_PROGRAM INSTALL_PROGRAM_STRIP INSTALL_DIR INSTALL_SCRIPT INSTALL_DATA HOST_OS HOST_CPU BUILD_OS BUILD_CPU TARGET_OS TARGET_CPU VERSION VERSION_MAJOR VERSION_MINOR VERSION_PATCH VERSION_NUMBER PKGNAME VPATH CONTACT CONTACT_NAME CONTACT_MAIL"
create_environ
echo "checking build system type... ${BUILD}"
echo "checking host system type... ${HOST}"
echo "checking target system type... ${TARGET}"
[ "${CROSSBUILD}" = 1 ] && echo "using crosscompilation mode."
#split_host BUILD HOST TARGET
[ -n "${prefix}" ] && PREFIX="${prefix}"
echo "checking for working directories... ${WODIS}"
echo "using prefix '${PREFIX}'"
ACR_RMFILES=""
SEDFLAGS=" -e '"
COUNT=0
for A in ${ENVWORDS} ; do
[ "${A}" = VPATH ] && continue
[ "${A}" = srcdir ] && continue
eval "VAR=\$${A}"
VAR="`echo ${VAR} | sed -e 's/\,/\\\,/g'`"
[ $COUNT = 10 ] && COUNT=0 && SEDFLAGS="${SEDFLAGS}' -e '"
COUNT=$(($COUNT+1))
SEDFLAGS="${SEDFLAGS}s,@${A}@,${VAR},g;"
done
SEDFLAGS="${SEDFLAGS}'"
for A in ./Makefile ; do # SUBDIRS
if [ -f "${VPATH}/${A}.acr" ]; then
SD_TARGET=${A}
else
if [ -d "${VPATH}/${A}" ]; then
SD_TARGET=${A}/Makefile
mkdir -p ${A}
else
echo "ERROR: Cannot find ${VPATH}/${A}.acr" >&2
exit 1
fi
fi
echo "creating ${SD_TARGET}"
mkdir -p $(echo ${A} | sed -e "s,/`basename ${A}`$,,g")
cat ${VPATH}/${SD_TARGET}.acr | \
eval sed -e "s,@VPATH@,${VPATH}/${A},g" ${SEDFLAGS} > ${SD_TARGET}.tmp
for A in ${ENVWORDS}; do
VALUE=`eval echo "$"${A}`
if [ "$VALUE" = 0 ]; then ## FALSE
MARK="##${A}##"
if [ -n "`grep \"${MARK}\" ${SD_TARGET}.tmp`" ]; then
mv ${SD_TARGET}.tmp ${SD_TARGET}.tmp2
cat ${SD_TARGET}.tmp2 | MARK=$MARK $AWK 'BEGIN{a=0;}{if($1==ENVIRON["MARK"]){if(a)a=0;else a=1}else{if(!a)print;}}' > ${SD_TARGET}.tmp
fi
fi
done
mv ${SD_TARGET}.tmp ${SD_TARGET} && rm -f ${SD_TARGET}.tmp2
if [ ! $? = 0 ]; then echo Cannot write target file ; control_c ; fi
done
echo
echo "Final report:"
for A in PREFIX ; do # REPORT
eval VAL="\$${A}"
[ -z "${VAL}" ] && VAL="(null)"
echo " - ${A} = ${VAL}"
done

View File

@ -0,0 +1,7 @@
PKGNAME radare2-r2pipe
VERSION 4.3.0
CONTACT pancake ; pancake@nopcode.org
SUBDIRS ./Makefile ;
REPORT PREFIX ;

2
radare2-r2pipe/cxx-qt/check.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/sh
r2 -qc '#!pipe ./r2pipe' /bin/ls

View File

@ -0,0 +1,31 @@
#include "r2pipe.h"
#if HAVE_R2_API
R2PipeAPI::R2PipeAPI(QString filepath) {
this->core = r_core_new ();
if (filepath != NULL) {
this->cmd(QString("\"o %1\"").arg(filepath));
}
}
QString R2PipeAPI::cmd(const QString str) {
std::string tmpstr = str.toStdString();
const char* cmd = tmpstr.c_str();
char *res = r_core_cmd_str (this->core, cmd);
QString o = (res && *res)? QString::fromUtf8(res): QString();
free (res);
return o;
}
/* Can be implemented in R2Pipe API */
QJsonObject R2PipeAPI::cmdj(QString x) {
QString r = cmd(x);
QJsonDocument d = QJsonDocument::fromJson(r.toUtf8());
return d.object();
}
void R2PipeAPI::close() {
r_core_free (this->core);
}
#endif

View File

@ -0,0 +1,41 @@
#include "r2pipe.h"
R2Pipe::R2Pipe(QString filepath) {
parent = NULL;
r2p_fd[0] = r2p_fd[1] = -1;
if (filepath.isEmpty()) {
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
proc = NULL;
QString r2p_in = env.value("R2PIPE_IN");
QString r2p_out = env.value("R2PIPE_OUT");
if (r2p_in.isEmpty() || r2p_out.isEmpty()) {
throw QString("Cannot find R2PIPE_IN or R2PIPE_OUT environment");
}
r2p_fd[0] = r2p_in.toInt();
r2p_fd[1] = r2p_out.toInt();
// Check R2PIPE_IN and R2PIPE_OUT env vars
} else {
proc = new QProcess(parent);
QStringList args;
args << "-q0" << filepath;
proc->start("/usr/bin/r2", args);
// TODO: support spawn method
}
}
QString R2Pipe::cmd(QString x) {
Write (x + "\n");
return Read();
}
QJsonObject R2Pipe::cmdj(QString x) {
QString r = cmd(x);
QJsonDocument d = QJsonDocument::fromJson(r.toUtf8());
return d.object();
}
void R2Pipe::close() {
if (proc != NULL) {
proc->terminate();
}
}

View File

@ -0,0 +1,52 @@
#include <QtNetwork>
#include <QProcess>
#include <unistd.h>
#define HAVE_R2_API 1
/* interface must be R2Pipe */
class R2Pipe {
private:
QObject *parent;
QProcess *proc;
int r2p_fd[2];
QString Read() {
QString r = QString();
char ch;
if (r2p_fd[0] == -1) {
return NULL;
}
while (read (r2p_fd[0], &ch, 1) == 1) {
if (ch == 0) break;
r += ch;
}
return r;
}
bool Write(QString cmd) {
const char *str = (const char *)cmd.toLatin1();
const int len = strlen (str);
return write (r2p_fd[1], str, len + 1) != -1;
}
public:
R2Pipe(QString filepath = NULL);
QString cmd(QString x);
QJsonObject cmdj(QString x);
void close();
};
#if HAVE_R2_API
#include <r2naked.h>
class R2PipeAPI {
private:
void *core;
public:
R2PipeAPI(QString filepath = NULL);
QString cmd(QString x);
QJsonObject cmdj(QString x);
void close();
};
#endif

View File

@ -0,0 +1,17 @@
CONFIG += qt
SOURCES += r2pipe.cxx \
r2pipe-api.cxx
SOURCES += test.cxx
QT += network
QT += core
QMAKE_CXXFLAGS_RELEASE += -g
QMAKE_CFLAGS += -g
QMAKE_LFLAGS_RELEASE += -g
HEADERS += \
r2pipe.h
INCLUDEPATH += /usr/local/radare2/include/libr
LIBS += -L/usr/local/radare2/lib -lr_core -lr_util

View File

@ -0,0 +1,21 @@
#include "r2pipe.h"
static QTextStream& cout() {
static QTextStream ts(stdout);
return ts;
}
int main() {
R2Pipe *r2;
try {
r2 = new R2Pipe();
} catch (QString err) {
cout() << err << "\n";
r2 = new R2Pipe("/bin/ls");
}
cout() << r2->cmd ("?e hello world");
cout() << r2->cmd ("x");
cout() << r2->cmd ("pd 3");
r2->close();
return 0;
}

View File

@ -0,0 +1,3 @@
all:
dmd test.d r2pipe.d
r2 -qc '#!pipe ./test' -

View File

@ -0,0 +1,43 @@
module r2pipe;
import std.conv;
import std.json;
import std.stdio;
import std.string;
import std.process;
import core.sys.posix.unistd;
class R2Pipe {
private alias sysread = core.sys.posix.unistd.read;
private alias syswrite = core.sys.posix.unistd.write;
private int fdIn;
private int fdOut;
this() {
fdIn = to!int(environment["R2PIPE_IN"]);
fdOut = to!int(environment["R2PIPE_OUT"]);
}
public string cmd(string c) {
char[] cbuf = (c~"\n").dup;
syswrite(fdOut, cast(void*)cbuf, cbuf.length);
string res = "";
while (true) {
byte[1] buf;
auto n = sysread(fdIn, &buf, 1);
if (buf[0] == '\0') {
break;
}
res ~= buf[0];
}
return res.chomp();
}
public JSONValue cmdj(string s) {
return parseJSON(cmd(s));
}
}
public static R2Pipe open() {
return new R2Pipe();
}

View File

@ -0,0 +1,10 @@
import std.stdio;
import r2pipe;
void main() {
auto r2 = r2pipe.open ();
writeln ("Hello "~ r2.cmd("?e World"));
writeln ("Hello "~ r2.cmd("?e Works"));
string file = r2.cmdj("ij")["core"]["file"].str;
writeln ("File: ", file);
}

196
radare2-r2pipe/dotnet/.gitignore vendored Executable file
View File

@ -0,0 +1,196 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
# Visual Studo 2015 cache/options directory
.vs/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding addin-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
*.[Cc]ache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
</configuration>

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AAD0715E-0E37-4904-B54C-61DBC24BCD3A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LocalExample</RootNamespace>
<AssemblyName>LocalExample</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\r2pipe\r2pipe.csproj">
<Project>{d5b3f257-e13e-42b5-a77e-aa0f809311fd}</Project>
<Name>r2pipe</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,24 @@
using System;
using r2pipe;
namespace DllExample
{
class Program
{
static void Main(string[] args)
{
string osName = System.Environment.OSVersion.ToString().Split(' ')[0];
const string fileName = "r2pipe.dll";
using (IR2Pipe pipe = new DllR2Pipe())
{
Console.WriteLine("Hello r2! " + pipe.RunCommand("?V"));
pipe.RunCommand("o " + fileName);
Console.WriteLine("Hello r2! " + pipe.RunCommand("pd 20"));
/* no async support yet */
}
}
}
}

View File

@ -0,0 +1,2 @@
all:
fsharpc -r ../r2pipe.dll test.fs

View File

@ -0,0 +1,9 @@
open System
open r2pipe
[<EntryPoint>]
let main argv =
let a = new R2Pipe "/bin/ls"
let v: string = a.RunCommand "?V"
printfn "Hello r2pipe version %s" v
0

View File

@ -0,0 +1,4 @@
all:
ln -fs ../r2pipe/bin/Release/r2pipe.dll r2pipe.dll
mcs -pkg:dotnet rasm2net.cs /r:r2pipe.dll
mono rasm2net.exe

View File

@ -0,0 +1,207 @@
using r2pipe;
using System;
using System.Windows.Forms;
namespace R2Net {
public class Rasm2 : Form {
private IR2Pipe r2 = null;
public string GetVersion() {
return Cmd("?V").Trim();
}
public string Cmd(string cmd) {
if (r2 != null) {
return r2.RunCommand(cmd);
}
return "";
}
public string Disasm() {
return r2.RunCommand("af;pdf").Trim();
}
public void Kill() {
this.r2 = null;
}
private void Button_Click (object sender, EventArgs e) {
var item = (string)arch.SelectedItem;
Console.WriteLine(item);
Application.Exit();
}
RichTextBox input;
RichTextBox output;
TextBox offs;
ComboBox bits;
ComboBox arch;
private string assemble(string arch, string bits, string code) {
string source = code.Replace("\n", ";");
Cmd("s " + offs.Text + ";e asm.arch=" + arch + ";e asm.bits=" + bits);
return Cmd("\"pa "+ source + "\"").Trim();
}
private string disasm(string arch, string bits, string code) {
string hexpairs = code
.Replace(" ","")
.Replace(";", "")
.Replace("\n","")
.Replace("\r", "");
Cmd("s " + offs.Text + ";e asm.arch=" + arch + ";e asm.bits=" + bits);
return Cmd("\"pad " + hexpairs + "\"");
}
private void updateArchComboBox() {
var archs = Cmd("e asm.arch=?q").Trim().Split('\n');
Array.Sort(archs, StringComparer.InvariantCulture);
foreach (var a in archs) {
arch.Items.Add(a);
}
}
private string pathToR2 = null;
private void loadR2Pipe() {
if (pathToR2 != null) {
this.r2 = new R2Pipe("-", pathToR2);
} else {
this.r2 = new R2Pipe("-");
}
}
public static bool IsWindows {
get {
int p = (int) Environment.OSVersion.Platform;
return (p < 4);
}
}
public Rasm2(string file) {
loadR2Pipe();
/* UI */
this.Text = "rasm2.net";
this.Width += 200;
Button b = new Button ();
b.Text = "Close";
b.Left = this.Width - b.Width - 20;
b.Top = this.Height - b.Height - 40;
b.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
b.Click += new EventHandler (Button_Click);
Controls.Add (b);
Label v = new Label ();
v.Text = GetVersion();
v.Left = 5;
v.Top = this.Height - b.Height - 35;
v.Width = this.Width;
v.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
Controls.Add (v);
input = new RichTextBox();
input.Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom);
input.Top = 32;
input.Height = (this.Height - input.Top) / 3;
input.Width = this.Width - 20;
input.Left = 5;
Controls.Add (input);
output = new RichTextBox();
output.Anchor = (AnchorStyles.Bottom| AnchorStyles.Left | AnchorStyles.Right );
output.Top = 32 + input.Height + 5 + 32;
output.Height = (this.Height - output.Top) / 2;
output.Width = this.Width - 20;
output.Left = 5;
Controls.Add (output);
arch = new ComboBox();
arch.DropDownStyle = ComboBoxStyle.DropDownList;
arch.Top = 5;
arch.Left = 5;
updateArchComboBox();
arch.SelectedItem = "x86";
Controls.Add (arch);
bits = new ComboBox();
bits.DropDownStyle = ComboBoxStyle.DropDownList;
bits.Top = 5;
bits.Left = arch.Width + arch.Left + 10;
bits.Items.Add("64");
bits.Items.Add("32");
bits.Items.Add("16");
bits.Items.Add("8");
bits.SelectedItem = "64";
Controls.Add (bits);
offs = new TextBox();
offs.Text = "0";
offs.Top = 5;
offs.Left = bits.Width + bits.Left + 10;
Controls.Add (offs);
var ba = new Button ();
ba.Text = "Assemble v";
ba.Left = 50;
ba.Top = input.Top + input.Height + 5;
ba.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
ba.Click += new EventHandler ((s, e) => {
output.Text = assemble ((string)arch.SelectedItem,
(string)bits.SelectedItem, input.Text);
});
Controls.Add (ba);
var bd = new Button ();
bd.Text = "Disasm ^";
bd.Left = this.Width - bd.Width - 50;
bd.Top = input.Top + input.Height + 5;
bd.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
bd.Click += new EventHandler ((s, e) => {
input.Text = disasm ((string)arch.SelectedItem,
(string)bits.SelectedItem, output.Text);
//MessageBox.Show("disassemble");
});
Controls.Add (bd);
var br = new Button ();
br.Text = "radare2";
br.Left = this.Width - br.Width - 20;
br.Top = 5;
br.Anchor = AnchorStyles.Top | AnchorStyles.Right;
br.Click += new EventHandler ((s, e) => {
if (IsWindows) {
var fileDialog = new OpenFileDialog();
fileDialog.Title = "Path to radare2.exe";
fileDialog.Filter = "Windows Executables (*.exe)|*.exe";
DialogResult result = fileDialog.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) {
pathToR2 = fileDialog.FileName;
loadR2Pipe ();
updateArchComboBox();
}
fileDialog = null;
} else {
if (this.r2 != null) {
MessageBox.Show(GetVersion());
} else {
MessageBox.Show("Cannot find radare2 in PATH");
}
}
});
Controls.Add (br);
}
public static void Main(string[] args) {
try {
Rasm2 e = new Rasm2("-");
Application.Run (e);
e.Kill();
} catch (Exception e) {
MessageBox.Show(e.ToString());
}
}
}
}

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
</configuration>

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{46CDE875-0070-4E62-B38D-267375321570}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>HttpExample</RootNamespace>
<AssemblyName>HttpExample</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\r2pipe\r2pipe.csproj">
<Project>{d5b3f257-e13e-42b5-a77e-aa0f809311fd}</Project>
<Name>r2pipe</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using r2pipe;
namespace HttpExample
{
class Program
{
static void Main(string[] args)
{
using(IR2Pipe pipe = new HttpR2Pipe("http://cloud.rada.re/cmd/"))
{
Console.WriteLine(pipe.RunCommand("p8 32"));
// you can use the queue here too:
QueuedR2Pipe qr2 = new QueuedR2Pipe(pipe);
qr2.Enqueue(new R2Command("?V", (string result) => {
Console.WriteLine("Version: {0}", result);
}));
qr2.Enqueue(new R2Command("pdf @ entry0", (string result) =>
{
Console.WriteLine("Entrypoint: \n{0}", result);
}));
qr2.ExecuteCommands();
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("HttpExample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HttpExample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("fcf43cea-8e09-47e3-88fe-d60381c7d120")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,11 @@
all: Newtonsoft.Json.dll
ln -fs ../r2pipe/bin/Release/r2pipe.dll r2pipe.dll
mcs -pkg:dotnet main.cs /r:r2pipe.dll /r:Newtonsoft.Json.dll
mono main.exe main.exe
Newtonsoft.Json.dll:
rm -rf Bin
wget -c https://github.com/JamesNK/Newtonsoft.Json/releases/download/8.0.3/Json80r3.zip
unzip Json80r3.zip Bin/Net40/Newtonsoft.Json.dll
mv Bin/Net40/* .
rm -rf Json80r3.zip Bin

View File

@ -0,0 +1,71 @@
using r2pipe;
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace R2Net {
public class Rasm2 {
private IR2Pipe r2 = null;
public string GetVersion() {
return Cmd("?V").Trim();
}
public JObject CmdJ(string cmd) {
string result = Cmd(cmd);
return JObject.Parse(result);
}
public JArray CmdA(string cmd) {
string result = Cmd(cmd);
return JArray.Parse(result);
}
public string Cmd(string cmd) {
if (r2 != null) {
return r2.RunCommand(cmd);
}
return "";
}
public string GetInfo() {
var info = CmdJ("ij");
var a = info["core"]["type"];
return info.ToString();;
}
public JArray Disasm() {
return CmdA("pdj 4");
}
public void Kill() {
this.r2 = null;
}
public Rasm2(string file) {
this.r2 = new R2Pipe(file);
}
public static void Main(string[] args) {
try {
Rasm2 e = new Rasm2(args[0]);
Console.WriteLine("r2 version: "+ e.GetVersion());
Console.WriteLine("--> " + e.GetInfo());
Console.WriteLine("--> " + e.Disasm().ToString());
do {
Console.Write("> ");
var line = Console.ReadLine();
if (line == "q") {
break;
}
Console.WriteLine(e.Cmd(line));
} while (true);
e.Kill();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
}

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 radare project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
</configuration>

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AAD0715E-0E37-4904-B54C-61DBC24BCD3A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LocalExample</RootNamespace>
<AssemblyName>LocalExample</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\r2pipe\r2pipe.csproj">
<Project>{d5b3f257-e13e-42b5-a77e-aa0f809311fd}</Project>
<Name>r2pipe</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using r2pipe;
namespace LocalExample
{
class Program
{
static void Main(string[] args)
{
#if __MonoCS__
using (IR2Pipe pipe = new R2Pipe("/bin/ls"))
#else
using (IR2Pipe pipe = new R2Pipe(@"C:\Windows\notepad.exe", @"C:\radare2\radare2.exe"))
#endif
{
Console.WriteLine("Hello r2! " + pipe.RunCommand("?V"));
Task<string> async = pipe.RunCommandAsync("?V");
// To use non-blocking async stuff in console applications, you need an async context. Google helps you.
// calling Result will block ulitmately.
Console.WriteLine("Hello async r2!" + async.Result);
// We can also issue multiple command sequentially, using a QueuedR2Pipe.
// Note however that if we supply the pipe to use we must not call dispose on the pipe.
QueuedR2Pipe qr2 = new QueuedR2Pipe(pipe);
qr2.Enqueue(new R2Command("x", (string result) => { Console.WriteLine("Result of x:\n {0}", result); }));
qr2.Enqueue(new R2Command("pi 10", (string result) => { Console.WriteLine("Result of pi 10:\n {0}", result); }));
// note that this can also be done asynchronously via qr2.ExecuteCommandsAsync();
qr2.ExecuteCommands();
}
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("LocalExample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LocalExample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("5db0b7da-8cfa-4e7b-988d-8b7bdffd1858")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,47 @@
R2P_LIB=r2pipe.dll
MCS=mcs
MONO=mono
XBUILD=xbuild /p:Configuration=Release
NUGET=nuget
# See http://sourceforge.net/projects/narrange/files/narrange/NArrange%20Beta%20Version%200.2.9/NArrange-0.2.9-net-2.0.zip/download
NARRANGE_WD=~/Downloads/NArrange/bin
NARRANGE=$(NARRANGE_WD)/narrange-console.exe
MCS_LIB=$(MCS) -optimize -target:library -out:$(R2P_LIB)
MCS_LINK=$(MCS) -optimize -reference:$(R2P_LIB)
ifneq ($(KEYFILE),)
MCS_LIB+=-keyfile:$(KEYFILE)
MCS_LINK+=-keyfile:$(KEYFILE)
endif
all: $(R2P_LIB) examples
ln -fs r2pipe/bin/Release/r2pipe.dll r2pipe.dll
ln -fs r2pipe/bin/Debug/r2pipe.dll r2pipeDebug.dll
$(R2P_LIB):
ifneq ($(KEYFILE),)
$(XBUILD) /p:SignAssembly=true /p:AssemblyOriginatorKeyFile=$(KEYFILE) r2pipe/r2pipe.csproj
else
$(XBUILD) r2pipe/r2pipe.csproj
endif
examples:
$(XBUILD) LocalExample/LocalExample.csproj
$(XBUILD) HttpExample/HttpExample.csproj
run:
$(MONO) LocalExample/bin/Release/LocalExample.exe
clean:
rm -f main.exe http.exe $(R2P_LIB)
rm -rf r2pipe/obj r2pipe/bin
rm -rf HttpExample/obj HttpExample/bin
rm -rf LocalExample/obj LocalExample/bin
nuget:
$(NUGET) pack r2pipe/r2pipe.csproj.nuspec
indent:
for a in *.cs ; do $(MONO) $(NARRANGE) $$a ; done
.PHONY: run all clean indent examples $(R2P_LIB)

View File

@ -0,0 +1,30 @@
using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über folgende
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("r2pipe-portable")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("r2pipe-portable")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("de")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<MinimumVisualStudioVersion>11.0</MinimumVisualStudioVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{73640705-0261-4565-9170-8D413E881B41}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>r2pipe_portable</RootNamespace>
<AssemblyName>r2pipe-portable</AssemblyName>
<DefaultLanguage>de-DE</DefaultLanguage>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{786C830F-07A1-408B-BD7F-6EE04809D6DB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkProfile>Profile111</TargetFrameworkProfile>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;PORTABLE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;PORTABLE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<!--
<AssemblyOriginatorKeyFile>r2pipe.snk</AssemblyOriginatorKeyFile>
-->
</PropertyGroup>
<ItemGroup>
<!-- A reference to the entire .NET Framework is automatically included -->
<None Include="r2pipe.snk" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\r2pipe\CmdQueue.cs">
<Link>CmdQueue.cs</Link>
</Compile>
<Compile Include="..\r2pipe\HttpR2Pipe.cs">
<Link>HttpR2Pipe.cs</Link>
</Compile>
<Compile Include="..\r2pipe\IR2Pipe.cs">
<Link>IR2Pipe.cs</Link>
</Compile>
<Compile Include="..\r2pipe\QueuedR2Pipe.cs">
<Link>QueuedR2Pipe.cs</Link>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,29 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>r2pipe</id>
<version>1.1.0</version>
<authors>radare2</authors>
<owners>radare2</owners>
<licenseUrl>https://github.com/radareorg/radare2-bindings/blob/master/COPYING</licenseUrl>
<projectUrl>https://github.com/radareorg/radare2-bindings</projectUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>
<description>r2pipe</description>
<releaseNotes></releaseNotes>
<copyright>Copyright 2015-2020</copyright>
<tags>radare2 r2pipe</tags>
<dependencies>
<!-- Everything but... -->
<group targetFramework="net40">
<dependency id="Mono.Posix" version="4.0.0" />
</group>
<!-- ... profile 111 for xamarin -->
<group targetFramework="netstandard1.1">
</group>
</dependencies>
</metadata>
<files>
<file src="r2pipe-portable/bin/Release/r2pipe-portable.dll" target="lib\netstandard1.1" />
<file src="r2pipe/bin/Release/r2pipe.dll" target="lib\net40\r2pipe.dll" />
</files>
</package>

View File

@ -0,0 +1,39 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.24720.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "r2pipe", "r2pipe\r2pipe.csproj", "{D5B3F257-E13E-42B5-A77E-AA0F809311FD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HttpExample", "HttpExample\HttpExample.csproj", "{46CDE875-0070-4E62-B38D-267375321570}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LocalExample", "LocalExample\LocalExample.csproj", "{AAD0715E-0E37-4904-B54C-61DBC24BCD3A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "r2pipe-portable", "r2pipe-portable\r2pipe-portable.csproj", "{73640705-0261-4565-9170-8D413E881B41}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D5B3F257-E13E-42B5-A77E-AA0F809311FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D5B3F257-E13E-42B5-A77E-AA0F809311FD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D5B3F257-E13E-42B5-A77E-AA0F809311FD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D5B3F257-E13E-42B5-A77E-AA0F809311FD}.Release|Any CPU.Build.0 = Release|Any CPU
{46CDE875-0070-4E62-B38D-267375321570}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{46CDE875-0070-4E62-B38D-267375321570}.Debug|Any CPU.Build.0 = Debug|Any CPU
{46CDE875-0070-4E62-B38D-267375321570}.Release|Any CPU.ActiveCfg = Release|Any CPU
{46CDE875-0070-4E62-B38D-267375321570}.Release|Any CPU.Build.0 = Release|Any CPU
{AAD0715E-0E37-4904-B54C-61DBC24BCD3A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AAD0715E-0E37-4904-B54C-61DBC24BCD3A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AAD0715E-0E37-4904-B54C-61DBC24BCD3A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AAD0715E-0E37-4904-B54C-61DBC24BCD3A}.Release|Any CPU.Build.0 = Release|Any CPU
{73640705-0261-4565-9170-8D413E881B41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{73640705-0261-4565-9170-8D413E881B41}.Debug|Any CPU.Build.0 = Debug|Any CPU
{73640705-0261-4565-9170-8D413E881B41}.Release|Any CPU.ActiveCfg = Release|Any CPU
{73640705-0261-4565-9170-8D413E881B41}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace r2pipe
{
public class R2Command
{
#region Fields
/// <summary>
/// Gets or sets the callback.
/// </summary>
/// <value>
/// The callback.
/// </value>
public Action<string> Callback { get; set; }
/// <summary>
/// Gets or sets the command.
/// </summary>
/// <value>
/// The command.
/// </value>
public string Command { get; set; }
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="R2Command"/> class.
/// </summary>
/// <param name="cmd">The command.</param>
/// <param name="cb">The cb.</param>
public R2Command(string cmd, Action<string> cb)
{
this.Command = cmd;
this.Callback = cb;
}
#endregion Constructors
#region Methods
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return Command;
}
#endregion Methods
}
}

View File

@ -0,0 +1,64 @@
/* --pancake */
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace r2pipe
{
public class DllR2Pipe : IR2Pipe
{
[DllImport("libr_core")]
private static extern UIntPtr r_core_new();
[DllImport("libr_core")]
private static extern string r_core_cmd_str(UIntPtr core, string cmd);
[DllImport("libr_core")]
private static extern void r_core_free(UIntPtr core);
/// <summary>
/// The URI
/// </summary>
internal UIntPtr core;
/// <summary>
/// Initializes a new instance of the <see cref="DllR2Pipe"/> class.
/// </summary>
public DllR2Pipe()
{
this.core = r_core_new();
}
/// <summary>
/// Executes given RunCommand in radare2
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public string RunCommand(string command)
{
return r_core_cmd_str(this.core, command);
}
#if !OLDNETFX
/// <summary>
/// Executes given RunCommand in radare2 asynchronously
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public async Task<string> RunCommandAsync(string command)
{
// this is not async at all. use threads? :D
return r_core_cmd_str(this.core, command);
}
#endif
public void Dispose()
{
r_core_free(this.core);
this.core = new UIntPtr(0);
}
}
}

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace r2pipe
{
public class HttpR2Pipe : IR2Pipe
{
/// <summary>
/// The URI
/// </summary>
internal Uri uri;
protected HttpClient client = new HttpClient();
/// <summary>
/// Initializes a new instance of the <see cref="HttpR2Pipe"/> class.
/// </summary>
/// <param name="uri">The URI (with trailing slash).</param>
/// <exception cref="System.ArgumentException">URI must be HTTP(S)</exception>
public HttpR2Pipe(string uri) :this (new Uri(uri))
{ }
/// <summary>
/// Initializes a new instance of the <see cref="HttpR2Pipe"/> class.
/// </summary>
/// <param name="uri">The URI (with trailing slash).</param>
/// <exception cref="System.ArgumentException">URI must be HTTP(S)</exception>
public HttpR2Pipe(Uri uri)
{
if(!uri.Scheme.StartsWith("http"))
{
throw new ArgumentException("URI must be HTTP(S)");
}
this.uri = uri;
}
/// <summary>
/// Executes given RunCommand in radare2
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public string RunCommand(string command)
{
return client.GetStringAsync(new Uri(uri, command)).Result;
}
#if !OLDNETFX
/// <summary>
/// Executes given RunCommand in radare2 asynchronously
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public async Task<string> RunCommandAsync(string command)
{
return await client.GetStringAsync(new Uri(uri, "/" + command));
}
#endif
public void Dispose()
{
client.Dispose();
}
}
}

View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace r2pipe
{
public interface IR2Pipe : IDisposable
{
/// <summary>
/// Executes given RunCommand in radare2
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>Returns a string </returns>
string RunCommand(string command);
#if !OLDNETFX
/// <summary>
/// Executes given RunCommand in radare2 asynchronously
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
Task<string> RunCommandAsync(string command);
#endif
}
}

View File

@ -0,0 +1,7 @@
all:
rm -f project.lock.json
xbuild
dotnet:
dotnet run
# dotnet build

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace r2pipe.OldApi
{
[Obsolete("Please use the newer HttpR2Pipe Class.")]
public class R2PipeHttp : HttpR2Pipe
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpR2Pipe"/> class.
/// </summary>
/// <param name="uri">The URI.</param>
/// <exception cref="System.ArgumentException">URI must be HTTP(S)</exception>
public R2PipeHttp(string uri) : base(new Uri(uri + "/"))
{ }
[Obsolete("Please use QueuedR2Pipe, which supports Callbacks or the async method which does not need one.")]
public void Cmd(string cmd, Action<string> cb)
{
cb(this.RunCommand(cmd));
}
[Obsolete("Please use the interface Member Command() instead.")]
public string CmdSync(string cmd)
{
return this.RunCommand(cmd);
}
}
}

View File

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace r2pipe.OldApi
{
public static class R2PipeOldExtensions
{
/// <summary>
/// Quits this instance.
/// </summary>
/// <remarks>Obsolete.</remarks>
[Obsolete("R2Pipe implements IDisposable, please use Dispose() instead or consider using a using block.")]
public static void Quit(this R2Pipe pipe)
{
if (pipe.doAsync)
{
pipe.RunCommandAsync("q!").GetAwaiter().OnCompleted(() =>
{
pipe.Dispose();
return;
});
}
pipe.Dispose();
}
/// <summary>
/// Quits the instance.
/// </summary>
/// <remarks>Obsolete.</remarks>
[Obsolete("R2Pipe implements IDisposable, please use Dispose() instead or consider using a using block.")]
public static void QuitSync(this R2Pipe pipe)
{
pipe.Dispose();
}
/// <summary>
/// Executes a Command synchronized
/// </summary>
/// <param name="pipe">r2pipe</param>
/// <param name="cmd">The command to execute.</param>
/// <returns>result of the command</returns>
[Obsolete("Please use the Interface Member RunCommand(string command) instead")]
public static string CmdSync(this R2Pipe pipe, string cmd)
{
return pipe.RunCommand(cmd);
}
/// <summary>
/// Commands the specified c.
/// </summary>
/// <param name="c">The c.</param>
/// <param name="cb">The cb.</param>
/// <returns></returns>
[Obsolete("Please use the Interface Member RunCommand() or RunCommandAsync() instead")]
public static async Task<string> Cmd(this R2Pipe pipe, string c, Action<string> cb)
{
if (pipe.doAsync)
{
string s = await pipe.RunCommandAsync(c);
cb(s);
return null;
}
string str = pipe.CmdSync(c);
cb(str);
return str;
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using r2pipe;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var a = new DllR2Pipe();
Console.WriteLine("-> {0}", a.RunCommand("?V"));
a.Dispose();
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("r2pipe")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("r2pipe")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("4690d592-f09f-4331-afba-87e023576cfc")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace r2pipe
{
public class QueuedR2Pipe : Queue<R2Command>, IDisposable
{
private IR2Pipe pipe;
private bool iOpenedPipe = false;
#if !PORTABLE
/// <summary>
/// Initializes a new instance of the <see cref="QueuedR2Pipe"/> class.
/// </summary>
/// <param name="file">The file to examine.</param>
/// <param name="executable">Path to the radare2 executable.</param>
public QueuedR2Pipe(string file, string executable) : this(new R2Pipe(file, executable))
{
iOpenedPipe = true;
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="QueuedR2Pipe"/> class, using a HttpR2Pipe.
/// </summary>
/// <param name="uri">The URI for the HttpR2Pipe.</param>
public QueuedR2Pipe(Uri uri) : this(new HttpR2Pipe(uri))
{
iOpenedPipe = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="QueuedR2Pipe"/> class.
/// </summary>
/// <param name="pipe">The r2pipe to use.</param>
public QueuedR2Pipe(IR2Pipe pipe)
{
this.pipe = pipe;
}
#if !PORTABLE
/// <summary>
/// Initializes a new instance of the <see cref="QueuedR2Pipe"/> class.
/// </summary>
/// <param name="file">The file to examine.</param>
public QueuedR2Pipe(string file) : this(new R2Pipe(file))
{
iOpenedPipe = true;
}
#endif
/// <summary>
/// Executes the commands.
/// </summary>
public void ExecuteCommands()
{
while (this.Count > 0)
{
R2Command cmd = this.Dequeue();
string result = pipe.RunCommand(cmd.Command);
cmd.Callback(result);
}
}
#if !OLDNETFX
/// <summary>
/// Executes the commands asynchronous.
/// </summary>
public async void ExecuteCommandsAsync()
{
while(this.Count > 0)
{
R2Command cmd = this.Dequeue();
string result = await pipe.RunCommandAsync(cmd.Command);
cmd.Callback(result);
}
}
#endif
public void Dispose()
{
if (iOpenedPipe)
pipe.Dispose();
}
}
}

View File

@ -0,0 +1,149 @@
namespace r2pipe
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
//using r2pipe.OldApi;
public class R2Pipe : IR2Pipe, IDisposable
{
/// <summary>
/// Gets the radare2 path.
/// </summary>
/// <value>
/// The radare2 path.
/// </value>
public string Radare2Path { get; private set; }
[Obsolete("Please use RunCommandAsync() or the QueuedR2Pipe class")]
public bool doAsync { get; set; }
/// <summary>
/// The r2 process
/// </summary>
internal Process r2Process;
/// <summary>
/// Initializes a new instance of the <see cref="R2Pipe"/> class.
/// </summary>
/// <param name="file">The file.</param>
public R2Pipe()
: this("-", "radare2") {
}
/// <summary>
/// Initializes a new instance of the <see cref="R2Pipe"/> class.
/// </summary>
/// <param name="file">The file.</param>
public R2Pipe(string file)
: this(file, "radare2")
{ }
/// <summary>
/// Initializes a new instance of the <see cref="R2Pipe"/> class.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="r2executable">The r2executable.</param>
public R2Pipe(string file, string r2executable)
{
if (file == null)
file = "-";
r2Process = new Process();
r2Process.StartInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
Arguments = "-q0 " + file,
FileName = r2executable
};
r2Process.Start();
r2Process.StandardInput.AutoFlush = true;
r2Process.StandardInput.NewLine = "\n";
// ignore first run
r2Process.StandardOutput.Read();
// Console.WriteLine(r2Process.StandardOutput.Read());
}
/// <summary>
/// Disposes this object. Exits r2 (if not already done) and disposes the process object too.
/// </summary>
public void Dispose()
{
if (!r2Process.HasExited)
{
this.RunCommand("q!");
r2Process.WaitForExit();
}
r2Process.Dispose();
}
/// <summary>
/// Executes given RunCommand in radare2
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public string RunCommand(string command)
{
var sb = new StringBuilder();
r2Process.StandardInput.WriteLine(command);
r2Process.StandardInput.Flush();
while (true)
{
char buffer = (char)r2Process.StandardOutput.Read();
if (buffer == 0x00)
break;
sb.Append(buffer);
}
return sb.ToString();
}
#if !OLDNETFX
/// <summary>
/// Executes given RunCommand in radare2 asynchronously
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public async Task<string> RunCommandAsync(string command)
{
StringBuilder builder = new StringBuilder();
await r2Process.StandardInput.WriteLineAsync(command);
await r2Process.StandardInput.FlushAsync();
while (true)
{
char[] buffer = new char[1024];
int length = await r2Process.StandardOutput.ReadAsync(buffer, 0, 1024);
for (int i = 0; i < length; i++)
{
if (buffer[i] == 0x00)
goto outer;
builder.Append(buffer[i]);
}
}
outer:
return builder.ToString();
}
#endif
}
}

View File

@ -0,0 +1,156 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#if HAVE_PIPES
using System.IO.Pipes;
#if __MonoCS__
using Mono.Unix;
#endif
namespace r2pipe
{
public class RlangPipe : IR2Pipe
{
#if __MonoCS__
public UnixStream ureadStream;
public UnixStream uwriteStream;
#endif
public NamedPipeClientStream inclient;
public StreamReader reader;
public StreamWriter writer;
/// <summary>
/// Initializes a new instance of the <see cref="RlangPipe"/> class.
/// </summary>
public RlangPipe()
{
#if __MonoCS__
if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) {
ureadStream = new UnixStream(int.Parse(Environment.GetEnvironmentVariable("R2PIPE_IN")));
reader = new StreamReader(ureadStream);
uwriteStream = new UnixStream(int.Parse(Environment.GetEnvironmentVariable("R2PIPE_OUT")));
writer = new StreamWriter(uwriteStream);
} else {
#endif
// Using named pipes on windows. I like this.
inclient = new NamedPipeClientStream("R2PIPE_PATH");
reader = new StreamReader(inclient);
writer = new StreamWriter(inclient);
#if __MonoCS__
}
#endif
}
/// <summary>
/// Executes given RunCommand in radare2
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public string RunCommand(string command)
{
var sb = new StringBuilder();
writer.WriteLine(command);
writer.Flush();
while (true)
{
char buffer = (char)reader.Read();
if (buffer == 0x00) {
break;
}
sb.Append(buffer);
}
return sb.ToString().Trim();
}
/// <summary>
/// Executes given RunCommand in radare2 asynchronously
/// </summary>
/// <param name="command">The command to execute.</param>
/// <returns>
/// Returns a string
/// </returns>
public async Task<string> RunCommandAsync(string command)
{
StringBuilder builder = new StringBuilder();
await writer.WriteLineAsync(command);
await writer.FlushAsync();
while (true)
{
char[] buffer = new char[1024];
int length = await reader.ReadAsync(buffer, 0, 1024);
for (int i = 0; i < length; i++)
{
if (buffer[i] == 0x00)
goto outer;
builder.Append(buffer[i]);
}
}
outer:
return builder.ToString().Trim();
}
public void Dispose()
{
reader.Dispose();
writer.Dispose();
#if __MonoCS__
if(Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) {
ureadStream.Dispose();
uwriteStream.Dispose();
}
else {
#endif
inclient.Dispose();
#if __MonoCS__
}
#endif
}
}
}
#else // HAVE_PIPES
namespace r2pipe
{
public class RlangPipe : IR2Pipe
{
/// <summary>
/// Initializes a new instance of the <see cref="RlangPipe"/> class.
/// </summary>
public RlangPipe()
{
throw new ArgumentException("RLangPipe: Unsupported r2pipe backend");
}
public string RunCommand(string command)
{
return null;
}
public async Task<string> RunCommandAsync(string command)
{
return null;
}
public void Dispose()
{
/* do nothing */
}
}
}
#endif

View File

@ -0,0 +1,21 @@
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {},
"frameworks": {
"net45":{},
"dnxcore50": { },
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
},
"imports": "dnxcore50"
}
}
}

View File

@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D5B3F257-E13E-42B5-A77E-AA0F809311FD}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>r2pipe</RootNamespace>
<AssemblyName>r2pipe</AssemblyName>
<TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SignAssembly>true</SignAssembly>
<!--
<AssemblyOriginatorKeyFile>r2pipe.snk</AssemblyOriginatorKeyFile>
-->
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;HAVE_PIPES</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;HAVE_PIPES</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Net" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Mono.Posix" />
</ItemGroup>
<ItemGroup>
<Compile Include="CmdQueue.cs" />
<Compile Include="HttpR2Pipe.cs" />
<Compile Include="IR2Pipe.cs" />
<Compile Include="OldApi\HttpR2Pipe.cs" />
<Compile Include="OldApi\R2Pipe.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="QueuedR2Pipe.cs" />
<Compile Include="R2Pipe.cs" />
<Compile Include="DllR2Pipe.cs" />
<Compile Include="RlangPipe.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,23 @@
The MIT License (MIT)
Copyright (c) 2015 by Alexander 'dark_k3y' Bolshev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,19 @@
all: deps
deps:
rebar get-deps
rebar compile
app:
rebar compile
tests:
rebar eunit
clean:
rebar clean
distclean: clean
rebar delete-deps
.PHONY: all deps app tests clean distclean

View File

@ -0,0 +1 @@
https://github.com/radare/r2pipe_erl

View File

@ -0,0 +1,36 @@
r2pipe for erlang
=================
Works with r2 over the ports interface or by calling escript direclty from r2.
Build:
```
$ rebar get-deps
$ rebar co
```
Example pipe usage:
```
$ rebar sh
erl> H = r2pipe:init(pipe, "/bin/ls").
erl> io:format("~s", [r2pipe:cmd(H, "i")]).
erl> r2pipe:cmdj(H, "ij").
```
See testr2pipe.erl as local pipe call example escript. Call it from r2 by using:
```
r2> #!pipe escript testr2pipe.erl
```
Or
```
$ chmod +x testr2pipe.erl
```
And then from r2:
```
r2> #!pipe testr2pipe.erl
```

View File

@ -0,0 +1,4 @@
{deps, [
{jsx, ".*", {git, "https://github.com/talentdeficit/jsx.git"}}
]
}.

View File

@ -0,0 +1,41 @@
-module(r2pipe).
-author(dark_k3y).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-endif.
-export([init/1, init/2, init/3, cmd/2, cmdj/2, quit/0]).
init(pipe, File) ->
init(pipe, File, "radare2").
init(pipe, File, R2Bin) ->
Path = R2Bin ++ " -q0 " ++ File,
r2pipe_handler:start(Path),
{pipe, r2pipe_handler}.
init(lpipe) ->
r2pipe_handler:start(lpipe),
timer:sleep(50), %% ugly sleep to let i/o initialize
{pipe, r2pipe_handler}.
cmd({pipe, _}, Cmd) ->
{ok, Data} = r2pipe_handler:call(prepare_cmd(Cmd)),
binary_to_list(Data).
cmdj({pipe, _}, Cmd) ->
{ok, Data} = r2pipe_handler:call(prepare_cmd(Cmd)),
parse_json(Data).
quit() ->
r2pipe_handler:stop().
prepare_cmd(Cmd) ->
Cmd ++ [10].
parse_json(Res) when is_binary(Res) ->
Size = (byte_size(Res) - 2 ) * 8,
<<Bin:Size, _Temp/binary>> = Res,
jsx:decode(<<Bin:Size>>).

View File

@ -0,0 +1,11 @@
{application, r2pipe_erl,
[
{description, "Erlang radare2 pipe bindings"},
{vsn, "0.0.1"},
{registered, []},
{applications, [
kernel,
stdlib
]},
{env, []}
]}.

View File

@ -0,0 +1,57 @@
-module(r2pipe_handler).
%% standard port handler interface
-export([start/1, stop/0, init/1, call/1]).
start(R2Path) ->
spawn(?MODULE, init, [R2Path]).
stop() ->
r2pipe_handler ! stop.
init_port(lpipe) ->
open_port({fd, list_to_integer(os:getenv("R2PIPE_IN")), list_to_integer(os:getenv("R2PIPE_OUT"))}, [stream, binary]);
init_port(R2Path) ->
open_port({spawn, R2Path}, [stream, binary]).
init(Mode) ->
register(r2pipe_handler, self()),
process_flag(trap_exit, true),
Port = init_port(Mode),
loop(Port).
call(Msg) ->
r2pipe_handler ! {call, self(), Msg},
receive
{r2pipe_handler, Result} ->
Result
end.
%% TODO: Dirty code: timeout should be externally configurable
get_timeout() ->
10000.
loop(Port) ->
receive
{Port, {data, _Data}} ->
%% data without query, do nothing
loop(Port);
{call, Caller, Msg} ->
Port ! {self(), {command, Msg}},
receive
{Port, {data, Data}} ->
Caller ! {r2pipe_handler, {ok, Data}}
after get_timeout() ->
Caller ! {r2pipe_handler, {fail, expired}}
end,
loop(Port);
stop ->
Port ! {self(), close},
receive
{Port, closed} ->
exit(normal)
end;
{'EXIT', Port, _Reason} ->
exit(port_terminated)
end.

View File

@ -0,0 +1,20 @@
#!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable
%% -sname hr
-mode(compile).
-export([main/1]).
main(_Args) ->
%% adding r2pipe to modulepath, set it to your r2pipe_erl location
R2pipePATH = filename:dirname(escript:script_name()) ++ "/ebin",
true = code:add_pathz(R2pipePATH),
%% initializing the link with r2
H = r2pipe:init(lpipe),
%% all work goes here
io:format("~s", [r2pipe:cmd(H, "i")]).

View File

@ -0,0 +1,10 @@
all:
go test
cd example ; go run example.go
sync:
rm -rf tmp
git clone `cat ORIGIN` tmp
cp -f tmp/*.go .
.PHONY: all sync

1
radare2-r2pipe/go/ORIGIN Normal file
View File

@ -0,0 +1 @@
https://github.com/radare/r2pipe.go

View File

@ -0,0 +1,6 @@
r2pipe.go
=========
[![GoDoc](https://godoc.org/github.com/radare/r2pipe-go?status.svg)](https://godoc.org/github.com/radare/r2pipe-go)
Go module to interact with radare2

View File

@ -0,0 +1,21 @@
// radare - LGPL - Copyright 2017 - pancake
package main
import ".."
func main() {
r2p, err := r2pipe.NewPipe("/bin/ls")
if err != nil {
print("ERROR: ", err)
return
}
defer r2p.Close()
disasm, err := r2p.Cmd("pd 20")
if err != nil {
print("ERROR: ", err)
} else {
print(disasm, "\n")
}
}

View File

@ -0,0 +1,69 @@
// radare - LGPL - Copyright 2017 - pancake
package r2pipe
import "github.com/rainycape/dl"
import "errors"
type Ptr = *struct{}
var lib Ptr = nil
var r_core_new func() Ptr
var r_core_free func(Ptr)
var r_mem_free func(interface{})
var r_core_cmd_str func(Ptr, string) string
func NativeLoad() error {
if lib != nil {
return nil
}
lib, err := dl.Open("libr_core", 0)
if err != nil {
return err
}
if lib.Sym("r_core_new", &r_core_new) != nil {
return errors.New("Missing r_core_new")
}
if lib.Sym("r_core_cmd_str", &r_core_cmd_str) != nil {
return errors.New("Missing r_core_cmd_str")
}
if lib.Sym("r_core_free", &r_core_free) != nil {
return errors.New("Missing r_core_free")
}
if lib.Sym("r_mem_free", &r_mem_free) != nil {
return errors.New("Missing r_mem_free")
}
return nil
}
func (r2p *Pipe) NativeCmd(cmd string) (string, error) {
res := r_core_cmd_str(r2p.Core, cmd)
return res, nil
}
func (r2p *Pipe) NativeClose() error {
r_core_free(r2p.Core)
r2p.Core = nil
return nil
}
func NewNativePipe(file string) (*Pipe, error) {
if err := NativeLoad(); err != nil {
return nil, err
}
r2 := r_core_new()
r2p := &Pipe{
File: file,
Core: r2,
cmd: func(r2p *Pipe, cmd string) (string, error) {
return r2p.NativeCmd(cmd)
},
close: func(r2p *Pipe) error {
return r2p.NativeClose()
},
}
if file != "" {
r2p.NativeCmd("o " + file)
}
return r2p, nil
}

187
radare2-r2pipe/go/r2pipe.go Normal file
View File

@ -0,0 +1,187 @@
// radare - LGPL - Copyright 2015 - nibble
/*
Package r2pipe allows to call r2 commands from Go. A simple hello world would
look like the following snippet:
package main
import (
"fmt"
"github.com/radare/r2pipe-go"
)
func main() {
r2p, err := r2pipe.NewPipe("malloc://256")
if err != nil {
panic(err)
}
defer r2p.Close()
_, err = r2p.Cmd("w Hello World")
if err != nil {
panic(err)
}
buf, err := r2p.Cmd("ps")
if err != nil {
panic(err)
}
fmt.Println(buf)
}
*/
package r2pipe
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"strings"
)
// A Pipe represents a communication interface with r2 that will be used to
// execute commands and obtain their results.
type Pipe struct {
File string
r2cmd *exec.Cmd
stdin io.WriteCloser
stdout io.ReadCloser
Core *struct{}
cmd CmdDelegate
close CloseDelegate
}
type CmdDelegate func(*Pipe, string) (string, error)
type CloseDelegate func(*Pipe) error
// NewPipe returns a new r2 pipe and initializes an r2 core that will try to
// load the provided file or URI. If file is an empty string, the env vars
// R2PIPE_{IN,OUT} will be used as file descriptors for input and output, this
// is the case when r2pipe is called within r2.
func NewPipe(file string) (*Pipe, error) {
if file == "" {
return newPipeFd()
}
return newPipeCmd(file)
}
func newPipeFd() (*Pipe, error) {
r2pipeIn := os.Getenv("R2PIPE_IN")
r2pipeOut := os.Getenv("R2PIPE_OUT")
if r2pipeIn == "" || r2pipeOut == "" {
return nil, errors.New("missing R2PIPE_{IN,OUT} vars")
}
r2pipeInFd, err := strconv.Atoi(r2pipeIn)
if err != nil {
return nil, err
}
r2pipeOutFd, err := strconv.Atoi(r2pipeOut)
if err != nil {
return nil, err
}
stdout := os.NewFile(uintptr(r2pipeInFd), "R2PIPE_IN")
stdin := os.NewFile(uintptr(r2pipeOutFd), "R2PIPE_OUT")
r2p := &Pipe{
File: "",
r2cmd: nil,
stdin: stdin,
stdout: stdout,
}
return r2p, nil
}
func newPipeCmd(file string) (*Pipe, error) {
r2cmd := exec.Command("radare2", "-q0", file)
stdin, err := r2cmd.StdinPipe()
if err != nil {
return nil, err
}
stdout, err := r2cmd.StdoutPipe()
if err != nil {
return nil, err
}
if err := r2cmd.Start(); err != nil {
return nil, err
}
// Read initial data
if _, err := bufio.NewReader(stdout).ReadString('\x00'); err != nil {
return nil, err
}
r2p := &Pipe{
File: file,
r2cmd: r2cmd,
stdin: stdin,
stdout: stdout,
}
return r2p, nil
}
// Write implements the standard Write interface: it writes data to the r2
// pipe, blocking until r2 have consumed all the data.
func (r2p *Pipe) Write(p []byte) (n int, err error) {
return r2p.stdin.Write(p)
}
// Read implements the standard Read interface: it reads data from the r2
// pipe, blocking until the previously issued commands have finished.
func (r2p *Pipe) Read(p []byte) (n int, err error) {
return r2p.stdout.Read(p)
}
// Cmd is a helper that allows to run r2 commands and receive their output.
func (r2p *Pipe) Cmd(cmd string) (string, error) {
if r2p.Core != nil {
if r2p.cmd != nil {
return r2p.cmd(r2p, cmd)
}
return "", nil
}
if _, err := fmt.Fprintln(r2p, cmd); err != nil {
return "", err
}
buf, err := bufio.NewReader(r2p).ReadString('\x00')
if err != nil {
return "", err
}
return strings.TrimRight(buf, "\n\x00"), nil
}
// Cmdj acts like Cmd but interprets the output of the command as json. It
// returns the parsed json keys and values.
func (r2p *Pipe) Cmdj(cmd string) (interface{}, error) {
if _, err := fmt.Fprintln(r2p, cmd); err != nil {
return nil, err
}
buf, err := bufio.NewReader(r2p).ReadBytes('\x00')
if err != nil {
return nil, err
}
buf = bytes.TrimRight(buf, "\n\x00")
var output interface{}
if err := json.Unmarshal(buf, &output); err != nil {
return nil, err
}
return output, nil
}
// Close shuts down r2, closing the created pipe.
func (r2p *Pipe) Close() error {
if r2p.close != nil {
return r2p.close(r2p)
}
if r2p.File == "" {
return nil
}
if _, err := r2p.Cmd("q!"); err != nil {
return err
}
return r2p.r2cmd.Wait()
}

View File

@ -0,0 +1,19 @@
// radare - LGPL - Copyright 2017 - pancake
package r2pipe
import "testing"
func TestNativeCmd(t *testing.T) {
r2p, err := NewNativePipe("/bin/ls")
// r2p, err := NewPipe("/bin/ls")
if err != nil {
t.Fatal(err)
}
defer r2p.Close()
version, err := r2p.Cmd("pd 10 @ entry0")
if err != nil {
t.Fatal(err)
}
print(version + "\n")
}

View File

@ -0,0 +1,27 @@
// radare - LGPL - Copyright 2015 - nibble
package r2pipe
import "testing"
func TestCmd(t *testing.T) {
r2p, err := NewPipe("malloc://256")
if err != nil {
t.Fatal(err)
}
defer r2p.Close()
check := "Hello World"
_, err = r2p.Cmd("w " + check)
if err != nil {
t.Fatal(err)
}
buf, err := r2p.Cmd("ps")
if err != nil {
t.Fatal(err)
}
if buf != check {
t.Errorf("buf=%v; want=%v", buf, check)
}
}

3
radare2-r2pipe/haskell/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.ghc.*
*.local
dist-*

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2020 radareorg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,47 @@
module R2Pipe (R2Context(), open, cmd, cmdj) where
import Data.Char
import Data.Word
import Network.HTTP
import System.IO
import System.Process
import System.Environment (getEnv)
import GHC.IO.Handle.FD
import System.Posix.Internals (FD)
import qualified Data.Aeson as JSON
import qualified Data.ByteString.Lazy as L
withPipes p = p { std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }
createProcess' args = fmap f $ createProcess (withPipes args) where
f (Just i, Just o, Just e, h) = (i, o, e, h)
f _ = error "createProcess': Failed to open pipes to the subprocess."
stringToLBS = L.pack . map (fromIntegral . ord)
lHTakeWhile :: (Word8 -> Bool) -> Handle -> IO L.ByteString
lHTakeWhile p h = do
c <- fmap L.head $ L.hGet h 1
if p c
then fmap (c `L.cons`) $ lHTakeWhile p h
else return L.empty
data R2Context = HttpCtx String
| PipeCtx Handle Handle
open :: Maybe String -> IO R2Context
open (Just url@('h':'t':'t':'p':_)) = return $ HttpCtx (url ++ "/cmd/")
open (Just filename) = do
(hIn, hOut, _, _) <- createProcess' $ proc "radare2" ["-q0", filename]
lHTakeWhile (/= 0) hOut -- drop the inital null that r2 emits
return $ PipeCtx hIn hOut
open Nothing = do
hIn <- fdToHandle =<< (read::(String -> FD)) <$> getEnv "R2PIPE_OUT"
hOut <- fdToHandle =<< (read::(String -> FD)) <$> getEnv "R2PIPE_IN"
return $ PipeCtx hIn hOut
cmd :: R2Context -> String -> IO L.ByteString
cmd (HttpCtx url) cmd = fmap stringToLBS $ getResponseBody =<< simpleHTTP (getRequest (url ++ urlEncode cmd))
cmd (PipeCtx hIn hOut) cmd = hPutStrLn hIn cmd >> hFlush hIn >> lHTakeWhile (/= 0) hOut
cmdj :: JSON.FromJSON a => R2Context -> String -> IO (Maybe a)
cmdj = (fmap JSON.decode .) . cmd

View File

@ -0,0 +1,2 @@
import Distribution.Simple
main = defaultMain

View File

@ -0,0 +1,14 @@
import R2Pipe
import qualified Data.ByteString.Lazy as L
showMainFunction ctx = do
cmd ctx "s main"
L.putStr =<< cmd ctx "pD `fl $$`"
main = do
-- Run r2 locally
open (Just "/bin/ls") >>= showMainFunction
-- Pick up pipes from parent r2 process
open Nothing >>= showMainFunction
-- Connect to r2 via HTTP (e.g. if "r2 -qc=h /bin/ls" is running)
open (Just "http://127.0.0.1:9090") >>= showMainFunction

View File

@ -0,0 +1,22 @@
cabal-version: >=1.10
name: r2pipe
version: 0.1.0.0
synopsis: Pipe interface for radare2
license-file: LICENSE
author: radareorg
build-type: Simple
library
exposed-modules: R2Pipe
other-modules:
build-depends: base >=4.12 && <5,
HTTP, aeson, process, bytestring
default-language: Haskell2010
executable example
main-is: example_r2pipe.hs
other-modules: R2Pipe
build-depends: base >= 4.12 && <5,
r2pipe, HTTP, aeson, process, bytestring

View File

@ -0,0 +1,15 @@
JARPATH=$(shell pwd)
include config.mk
all:
javac $(JAVACFLAGS) org/radare/r2pipe/*.java examples/Test.java
jar cvf r2pipe.jar org
$(MAKE) -C jni
$(MAKE) -C examples
run:
$(MAKE) -C examples run
clean:
rm -f *.class org/radare/r2pipe/*.class
rm -f r2pipe.jar

View File

@ -0,0 +1,3 @@
#JAVACFLAGS=-source 1.7 -target 1.7
JAVACFLAGS+=-classpath $(JARPATH)/javax.json-api-1.0.jar:$(JARPATH)/r2pipe.jar:examples:.
JAVACFLAGS+=-classpath $(JARPATH)/javax.json-1.1.jar:$(JARPATH)/javax.json-api-1.0.jar:$(JARPATH)/r2pipe.jar:examples:.

View File

@ -0,0 +1,15 @@
JARPATH=$(shell pwd)/..
include ../config.mk
# used to test that r2pipe.java works without the javax.json apis loaded
JCF+=-classpath $(JARPATH)/r2pipe.jar:$(JARPATH)/examples
all:
javac $(JAVACFLAGS) TestJNI.java
javac $(JAVACFLAGS) TestJSON.java
javac $(JAVACFLAGS) Test.java
run:
java $(JCF) Test
java $(JAVACFLAGS) TestJSON
java -Djava.library.path=../jni/ $(JCF) TestJNI

View File

@ -0,0 +1,16 @@
import org.radare.r2pipe.R2Pipe;
public class Test {
public static void main (String[] args) {
try {
R2Pipe r2p = new R2Pipe ("/bin/ls");
//R2Pipe r2p = new R2Pipe ("http://cloud.rada.re/cmd/", true);
System.out.println (r2p.cmd ("pd 10"));
System.out.println ("==============");
System.out.println (r2p.cmd ("px 32"));
r2p.quit();
} catch (Exception e) {
System.err.println (e);
}
}
}

View File

@ -0,0 +1,16 @@
import org.radare.r2pipe.R2PipeJNI;
public class TestJNI {
public static void main (String[] args) {
try {
R2PipeJNI r2 = new R2PipeJNI ();
r2.cmd ("o /bin/ls");
System.out.println (r2.cmd ("pd 10"));
System.out.println ("==============");
System.out.println (r2.cmd ("px 32"));
r2.quit();
} catch (Exception e) {
System.err.println (e);
}
}
}

View File

@ -0,0 +1,37 @@
import org.radare.r2pipe.R2Pipe;
import java.util.Map;
import java.util.HashMap;
import javax.json.*;
import javax.json.stream.*;
import java.io.StringWriter;
public class TestJSON {
public static String jsonStringify(JsonObject obj) {
Map<String, Boolean> config = new HashMap<>();
config.put(JsonGenerator.PRETTY_PRINTING, true);
JsonWriterFactory jwf = Json.createWriterFactory(config);
StringWriter sw = new StringWriter();
try (JsonWriter jsonWriter = jwf.createWriter(sw)) {
jsonWriter.writeObject(obj);
}
return sw.toString();
}
public static void main (String[] args) {
try {
R2Pipe r2p = new R2Pipe ("/bin/ls");
//R2Pipe r2p = new R2Pipe ("http://cloud.rada.re/cmd/", true);
System.out.println (r2p.cmd ("pd 10"));
System.out.println ("==============");
System.out.println (r2p.cmd ("px 32"));
JsonObject obj = r2p.cmdj ("ij");
String intrp = obj.getJsonObject("bin").getString("intrp");
String pretty = jsonStringify(obj);
System.out.println (pretty);
System.out.println (intrp);
r2p.quit();
} catch (Exception e) {
System.err.println (e);
}
}
}

Some files were not shown because too many files have changed in this diff Show More