I'm wondering what I'm doing wrong... with a sole wait it compiles and runs, but not with a timed_wait:
using boost::interprocess::scoped_lock;
using boost::interprocess::interprocess_mutex;
using boost::posix_time::milliseconds;
[...]
scoped_lock<interprocess_mutex> lock(obj->mutex);
while (...) {
obj->condition.timed_wait(lock, milliseconds(100));
}
where obj->mutex is a boost::interprocess::interprocess_mutex and obj->condition is a boost::interprocess::interprocess_condition. Here is the g++ error log:
code.cpp: In member function ‘[...]’:
code.cpp:42: error: no matching function for call to ‘boost::interprocess::interprocess_condition::timed_wait(boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex>&, boost::posix_time::milliseconds)
whereas this is the prototype of the condition class member function (boost/interprocess/sync/interprocess_condition.hpp):
template <typename L, typename Pr>
bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred)
(boost 1.40)
Thanks to a nice #boost IRC user (mjcaisse), I have now a clue: timed_wait needs an absolute time.
bool noTimeout = true;
boost::system_time timeout = boost::get_system_time() + milliseconds(10);
while (!noTimeout && [CONDITION NOT MET])
{
noTimeout = obj->condition.timed_wait(lock, timeout);
}
if (!noTimeout)
{
std::cout << "timeout!" << std::endl;
}
Related
I'm trying to hook functions of the OKHttp library by using then following Frida script:
setTimeout(function(){
Java.perform(function (){
console.log("-- Hook OKHttp library --");
try {
var Builder = Java.use('okhttp3.CertificatePinner$Builder');
var Pin = Java.use('okhttp3.CertificatePinner$Pin');
var OkHttpClient = Java.use('okhttp3.OkHttpClient$Builder');
console.log("OkHTTP classes found");
Builder.add.overload.implementation = function(a, b) {
console.log("TEST ADD");
}
Pin.matches.overload.implementation = function (a) {
console.log("TEST matches")
return true;
}
OkHttpClient.certificatePinner.overload.implementation = function (a) {
console.log("TEST certificatePinner");
}
console.log("OkHTTP functions found");
} catch (err) {
// If we dont have a ClassNotFoundException exception, raise the
// problem encountered.
console.log("OkHTTP 3.x classes/functions not Found");
}
});
},0);
And I am executing the following code in my Android application:
CertificatePinner certificatePinner = new CertificatePinner.Builder()
.add(certificateDNWildcard, certificateHash)
.build();
//Create http client with pinned certificate
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.certificatePinner(certificatePinner)
.build();
As you can see I am calling the function .add(certificateDNWildcard, certificateHash) which I am trying to hook. However, nothing is printed in the terminal when I execute this function. Furthermore, the output of my terminal is:
-- Hook OKHttp library --
OkHTTP classes found
OkHTTP functions found
Hence, it does find the classes and functions; however, the hook itself does not work effectively. Could someone help me?
I am using:
* Frida 12.8.11
* Android 10
* ARM64
You should either:
// works if add method has a single implementation
Builder.add.implementation = function(a, b) {
console.log("TEST ADD");
}
or
// always works
Builder.add.overload('java.lang.String', 'java.lang.String').implementation = function(a, b) {
console.log("TEST ADD");
}
I'm trying to pipe output from echo into a command using GLib's spawn_command_line_sync method. The problem I've run into is echo is interpreting the entire command as the argument.
To better explain, I run this in my code:
string command = "echo \"" + some_var + "\" | command";
Process.spawn_command_line_sync (command.escape (),
out r, out e, out s);
I would expect the variable to be echoed to the pipe and the command run with the data piped, however when I check on the result it's just echoing everything after echo like this:
"some_var's value" | command
I think I could just use the Posix class to run the command but I like having the result, error and status values to listen to that the spawn_command_line_sync method provides.
The problem is that you are providing shell syntax to what is essentially the kernel’s exec() syscall. The shell pipe operator redirects the stdout of one process to the stdin of the next. To implement that using Vala, you need to get the file descriptor for the stdin of the command process which you’re running, and write some_var to it manually.
You are combining two subprocesses into one. Instead echo and command should be treated separately and have a pipe set up between them. For some reason many examples on Stack Overflow and other sites use the Process.spawn_* functions, but using GSubprocess is an easier syntax.
This example pipes the output of find . to sort and then prints the output to the console. The example is a bit longer because it is a fully working example and makes use of a GMainContext for asynchronous calls. GMainContext is used by GMainLoop, GApplication and GtkApplication:
void main () {
var mainloop = new MainLoop ();
SourceFunc quit = ()=> {
mainloop.quit ();
return Source.REMOVE;
};
read_piped_commands.begin ("find .", "sort", quit);
mainloop.run ();
}
async void read_piped_commands (string first_command, string second_command, SourceFunc quit) {
var output = splice_subprocesses (first_command, second_command);
try {
string? line = null;
do {
line = yield output.read_line_async ();
print (#"$(line ?? "")\n");
}
while (line != null);
} catch (Error error) {
print (#"Error: $(error.message)\n");
}
quit ();
}
DataInputStream splice_subprocesses (string first_command, string second_command) {
InputStream end_pipe = null;
try {
var first = new Subprocess.newv (first_command.split (" "), STDOUT_PIPE);
var second = new Subprocess.newv (second_command.split (" "), STDIN_PIPE | STDOUT_PIPE);
second.get_stdin_pipe ().splice (first.get_stdout_pipe (), CLOSE_TARGET);
end_pipe = second.get_stdout_pipe ();
} catch (Error error) {
print (#"Error: $(error.message)\n");
}
return new DataInputStream (end_pipe);
}
It is the splice_subprocesses function that answers your question. It takes the STDOUT from the first command as an InputStream and splices it with the OutputStream (STDIN) for the second command.
The read_piped_commands function takes the output from the end of the pipe. This is an InputStream that has been wrapped in a DataInputStream to give access to the read_line_async convenience method.
Here's the full, working implementation:
try {
string[] command = {"command", "-options", "-etc"};
string[] env = Environ.get ();
Pid child_pid;
string some_string = "This is what gets piped to stdin"
int stdin;
int stdout;
int stderr;
Process.spawn_async_with_pipes ("/",
command,
env,
SpawnFlags.SEARCH_PATH | SpawnFlags.DO_NOT_REAP_CHILD,
null,
out child_pid,
out stdin,
out stdout,
out stderr);
FileStream input = FileStream.fdopen (stdin, "w");
input.write (some_string.data);
/* Make sure we close the process using it's pid */
ChildWatch.add (child_pid, (pid, status) => {
Process.close_pid (pid);
});
} catch (SpawnError e) {
/* Do something w the Error */
}
I guess playing with the FileStream is what really made it hard to figure this out. Turned out to be pretty straightforward.
Based on previous answers probably an interesting case is to use program arguments to have a general app to pipe any input on it:
pipe.vala:
void main (string[] args) {
try {
string command = args[1];
var subproc = new Subprocess(STDIN_PIPE | STDOUT_PIPE, command);
var data = args[2].data;
var input = new MemoryInputStream.from_data(data, GLib.free);
subproc.get_stdin_pipe ().splice (input, CLOSE_TARGET);
var end_pipe = subproc.get_stdout_pipe ();
var output = new DataInputStream (end_pipe);
string? line = null;
do {
line = output.read_line();
print (#"$(line ?? "")\n");
} while (line != null);
} catch (Error error) {
print (#"Error: $(error.message)\n");
}
}
build:
$ valac --pkg gio-2.0 pipe.vala
and run:
$ ./pipe sort "cc
ab
aa
b
"
Output:
aa
ab
b
cc
How can I get a function's signature (or at least the entire definition?) as a string using Clang/Libclang, assuming I have its CXCursor or so?
I think that the definition may be somehow obtainable by using the cursor's extents, but I don't really know how (what function to use).
You can use this simple code to get prototype of a function ( name, return type, count of arguments and arguments[name,data type]).
string Convert(const CXString& s)
{
string result = clang_getCString(s);
clang_disposeString(s);
return result;
}
void print_function_prototype(CXCursor cursor)
{
// TODO : Print data!
auto type = clang_getCursorType(cursor);
auto function_name = Convert(clang_getCursorSpelling(cursor));
auto return_type = Convert(clang_getTypeSpelling(clang_getResultType(type)));
int num_args = clang_Cursor_getNumArguments(cursor);
for (int i = 0; i < num_args; ++i)
{
auto arg_cursor = clang_Cursor_getArgument(cursor, i);
auto arg_name = Convert(clang_getCursorSpelling(arg_cursor));
if (arg_name.empty())
{
arg_name = "no name!";
}
auto arg_data_type = Convert(clang_getTypeSpelling(clang_getArgType(type, i)));
}
}
CXChildVisitResult functionVisitor(CXCursor cursor, CXCursor /* parent */, CXClientData /* clientData */)
{
if (clang_Location_isFromMainFile(clang_getCursorLocation(cursor)) == 0)
return CXChildVisit_Continue;
CXCursorKind kind = clang_getCursorKind(cursor);
if ((kind == CXCursorKind::CXCursor_FunctionDecl || kind == CXCursorKind::CXCursor_CXXMethod || kind == CXCursorKind::CXCursor_FunctionTemplate || \
kind == CXCursorKind::CXCursor_Constructor))
{
print_function_prototype(cursor);
}
return CXChildVisit_Continue;
}
You could try using clang_Cursor_getMangling() and demangle the result in order to get the complete definition.
I'm using the following for a project I am working on and it works great for the definition. TL&DR clang_getCursorPrettyPrinted with the policy TerseOutput set to true.
std::string getStdString(const CXString &s)
{
std::string rv = clang_getCString(s);
clang_disposeString(s);
return rv;
}
bool isFunctionImplementation(CXCursor &cursor,std::string &decl,std::string &filename,unsigned &lineno)
{
std::string cs = getStdString(clang_getCursorPrettyPrinted(cursor,nullptr));
if (cs.find('{') == std::string::npos) // Just a declaration, not the "meat" of the function, so we dont care
return false;
clang::LangOptions lo;
struct clang::PrintingPolicy pol(lo);
pol.adjustForCPlusPlus();
pol.TerseOutput = true;
pol.FullyQualifiedName = true;
decl = getStdString(clang_getCursorPrettyPrinted(cursor,&pol));
CXSourceLocation location = clang_getCursorLocation( cursor );
CXFile f;
lineno = 0;
filename = "(None)";
clang_getSpellingLocation(location,&f,&lineno,nullptr,nullptr);
if (lineno)
{
filename = getStdString(clang_File_tryGetRealPathName(f));
}
return isAllowedDirectory(filename);
}
This one checks if the function call is "meat" or just a definition. Obviously you can adjust as needed, including writing your own isAllowedDirectory function. Just pass the cursor, two strings and an unsigned into this as you walk your AST when you hit a declaration type.
I use the following, shorter way with clang 10 (though its using a matcher, not a cursor):
The 2 helper functions are general helpers to get the code snippet as a string.
// helper function 1: find position of end of token
SourceLocation
end_of_the_end(SourceLocation const & start_of_end, SourceManager & sm)
{
using namespace clang;
LangOptions lopt;
return Lexer::getLocForEndOfToken(start_of_end, 0, sm, lopt);
}
// helper function 2:
std::string getSymbolString(clang::SourceManager & sm,
const clang::SourceRange & range)
{
return std::string(sm.getCharacterData(range.getBegin()),
sm.getCharacterData(end_of_the_end(range.getEnd(), sm)));
}
The actual code snippet to get the function declaration string is:
// ... in run() of a matcher:
virtual void run(corct::result_t const & result) override
{
using namespace clang;
FunctionDecl * f_decl = const_cast<FunctionDecl *>(
result.Nodes.getNodeAs<FunctionDecl>(fd_bd_name_));
if(f_decl) {
SourceManager & sm(result.Context->getSourceManager());
FunctionDecl * f_decl = const_cast<FunctionDecl *>(
result.Nodes.getNodeAs<FunctionDecl>(fd_bd_name_));
auto full_decl_string =
getSymbolString(sm, f_decl->DeclaratorDecl::getSourceRange());
}
}
This will output inline bool test2(std::string const & str, std::vector<std::string> & sss) for the following function:
inline bool test2(std::string const & str, std::vector<std::string> & sss)
{
return true;
}
I have a JS function within a larger script that updates a progress bar in a web page:
function Funktion(t) {
'use strict';
var value,
max,
go;
go = setInterval(animate, t);
value = 0;
max = 100;
go = 0;
function animate() {
if (value >= max) {
clearInterval(go);
return;
}
value += 1;
document.getElementById('progress').value = value;
document.getElementById('percent').innerHTML = value;
if (value === max) {
clearInterval(go);
}
}
}
Disclaimer: Please assume all relevant variables are properly defined and initialized. The script as a whole functions properly. JSLint complains Unused 'animate'. function animate() {. I've tried suppressing this warning with a combination of /*global go: true */ and /*global animate */. Is there a way to suppress this warning without hacking into the JSLint rules?
Even easier than I initially thought. You just need to define the function before you use it.
/*jslint white:true, browser:true */
function Funktion(t) {
'use strict';
var value,
max,
go;
function animate() {
if (value >= max) {
clearInterval(go);
return;
}
value += 1;
document.getElementById('progress').value = value;
document.getElementById('percent').innerHTML = value;
if (value === max) {
clearInterval(go);
}
}
go = setInterval(animate, t);
value = 0;
max = 100;
go = 0;
}
JSLint is very particular about defining things before they're used. If you call a function you define later in the file, eg, it'll complain.
So you were using animate before JSLint knew what it was. It's very procedural in its evaluation.
So you were using an undefined animate initially, which JSLint probably should have yelled at instead of allowing you to end run around var declaration using a function declaration later.
Then you "re-defined" animate (from JSLint's pov) as a function, and never used it. Har har.
You get a much better error message if you try your code (with a few JSLint directives added) at the more recently updated engine at jslint.com:
'animate' is out of scope.
That error message points at the go = setInterval(animate, t); line, which is more helpful.
Try this one out for unused variables:
/*jshint unused: true, node: true */
Try this one out for unused variables that come as parameters (use this one with the above one):
/*jslint unparam: true, node: true */
I'm trying to make a program for parsing text protocol.
(I selected text protocol cause I heard that binary packet parsing is more difficult).
Currently, there are really few command and parameters.
each packet can be splited by delimiter(';')
[packet1];[packet2];
Let's break packet1 down.
[Action],[Param1],[Param2],...;
Action : [SET]
Params : [DELAY]
if you send "SET,DELAY,300;" to server,
server will change 'delay' parameter and send "SET,DELAY,300;" to client.
Action : [GET]
Params : [DELAY] [MODE]
if you send "GET,DELAY,MODE;" to server,
server will send "GET,DELAY,300,MODE,2;" to client.
Any way I suceed to make it.
(The code is here. because it is long, I couldn't add it here)
But even if there are only few params and actions, the code is very long and complicated.
I used 'boost::algorithm::split' to split packets.
And I only used 'if','else if','else' to invoke right task corresponding 'action' and 'parameter'.
But I will add more actions and parameters.
But at this rate, I cannot debug or modify code because the comlexity of the code will be more severe.
Is it wrong way to make protocol translation program?
If you know better way, please share with me.
Yes. The better way is to make a grammar, write a parser for it and parse into an AST (abstract syntax tree, or simply strong typed representation of the packets).
A Spirit grammar for this looks like:
I always start out with the AST types:
namespace ast {
struct nil {
friend std::ostream& operator<<(std::ostream& os, nil) { return os << "<nil>"; }
};
using value = boost::variant<nil, double, std::string>;
struct parameter {
std::string _key;
value _val;
};
enum class action {
get,
set,
};
using parameters = std::vector<parameter>;
struct packet {
action _action;
parameters _params;
};
using packets = std::vector<packet>;
}
For simplicity I've
assumed parameters (mode/delay) will have numeric or string values.
used the same packet definition for GET and SET requests (GET requests will just us nil values for the parameters listed)
Next we define a grammar using Boost Spirit Qi:
template <typename It, typename Skipper=qi::space_type>
struct grammar : qi::grammar<It, ast::packets(), Skipper> {
grammar():grammar::base_type(start) {
using qi::raw;
using qi::no_case;
param_key_.add
("delay")
("mode");
start = *(packet_ >> ';');
packet_ =
(no_case["get"] >> qi::attr(ast::action::get) >> *(',' >> get_param_))
| (no_case["set"] >> qi::attr(ast::action::set) >> *(',' >> set_param_))
;
get_param_ = raw[no_case[param_key_]] >> qi::attr(ast::nil());
set_param_ = raw[no_case[param_key_]] >> "," >> value_;
value_ = qi::double_ | string_;
string_ = '"' >> *~qi::char_('"') >> '"';
BOOST_SPIRIT_DEBUG_NODES((start)(packet_)(get_param_)(set_param_)(value_)(string_))
}
// ... field declarations
};
There's a little bit of a learning curve here, but the key point to observe is that it it's possible to create maintainable code that is also debuggable (see here for BOOST_SPIRIT_DEBUG enabled output).
Finally, because the AST is simple we can make a fake request processor that uses a request context (in this case a map to contain the current values of the parameters) to actually process the requests:
struct request_context {
std::map<std::string, ast::value> properties;
request_context()
: properties { { "MODE", 2 }, { "DELAY", 300 } } // defaults
{
}
boost::optional<ast::packet> process_request(ast::packet packet) {
switch (packet._action) {
case ast::action::get:
for(auto& param : packet._params) {
param._val = properties[param._key];
}
return packet;
case ast::action::set:
for(auto& param : packet._params) {
std::cout << "DEBUG: setting property '" << param._key << "' to value '" << param._val << "'\n";
properties[param._key] = param._val;
}
return boost::none;
default:
throw std::runtime_error("bad packet"); // TODO proper exception type
};
}
};
Imagine who much messier this was if you had it mixed with the parsing code, or everything stringly typed
Live On Coliru
//#define BOOST_SPIRIT_DEBUG
#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include <map>
namespace qi = boost::spirit::qi;
namespace ast {
struct nil {
friend std::ostream& operator<<(std::ostream& os, nil) { return os << "<nil>"; }
};
using value = boost::variant<nil, double, std::string>;
struct parameter {
std::string _key;
value _val;
};
enum class action {
get,
set,
};
using parameters = std::vector<parameter>;
struct packet {
action _action;
parameters _params;
};
using packets = std::vector<packet>;
static std::ostream& operator<<(std::ostream& os, action a) {
switch(a) {
case action::get: return os << "GET";
case action::set: return os << "SET";
}
return os << "(other)";
}
}
BOOST_FUSION_ADAPT_STRUCT(ast::parameter,(std::string,_key)(ast::value,_val))
BOOST_FUSION_ADAPT_STRUCT(ast::packet,(ast::action,_action)(ast::parameters,_params))
template <typename It, typename Skipper=qi::space_type>
struct grammar : qi::grammar<It, ast::packets(), Skipper> {
grammar():grammar::base_type(start) {
using qi::raw;
using qi::no_case;
param_key_.add
("delay")
("mode");
start = *(packet_ >> ';');
packet_ =
(no_case["get"] >> qi::attr(ast::action::get) >> *(',' >> get_param_))
| (no_case["set"] >> qi::attr(ast::action::set) >> *(',' >> set_param_))
;
get_param_ = raw[no_case[param_key_]] >> qi::attr(ast::nil());
set_param_ = raw[no_case[param_key_]] >> "," >> value_;
value_ = qi::double_ | string_;
string_ = '"' >> *~qi::char_('"') >> '"';
BOOST_SPIRIT_DEBUG_NODES((start)(packet_)(get_param_)(set_param_)(value_)(string_))
}
private:
qi::symbols<char, std::string> param_key_;
qi::rule<It, ast::parameter(), Skipper> set_param_, get_param_;
qi::rule<It, ast::packets(), Skipper> start;
qi::rule<It, ast::packet(), Skipper> packet_;
qi::rule<It, ast::value(), Skipper> value_;
qi::rule<It, std::string()> string_;
};
struct request_context {
std::map<std::string, ast::value> properties;
request_context()
: properties { { "MODE", 2 }, { "DELAY", 300 } } // defaults
{
}
boost::optional<ast::packet> process_request(ast::packet packet) {
switch (packet._action) {
case ast::action::get:
for(auto& param : packet._params) {
param._val = properties[param._key];
}
return packet;
case ast::action::set:
for(auto& param : packet._params) {
std::cout << "DEBUG: setting property '" << param._key << "' to value '" << param._val << "'\n";
properties[param._key] = param._val;
}
return boost::none;
default:
throw std::runtime_error("bad packet"); // TODO proper exception type
};
}
};
int main()
{
std::string const input =
"GET,DELAY,MODE;"
"SET,DELAY,0,MODE,\"we can have string values too\";GET,MODE;SET,MODE,42;GET,MODE,DELAY;";
using It = std::string::const_iterator;
It f(input.begin()), l(input.end());
grammar<It> p;
ast::packets parsed;
bool ok = qi::phrase_parse(f,l,p,qi::space,parsed);
if (ok) {
std::cout << parsed.size() << " packets successfully parsed\n";
request_context ctx;
for(auto& packet : parsed)
{
auto response = ctx.process_request(packet);
if (response) {
std::cout << "response: " << response->_action;
for(auto& kv : packet._params) {
std::cout << "," << kv._key << "," << kv._val;
}
std::cout << ";\n";
}
}
} else {
std::cout << "Parse error\n";
}
if (f!=l)
std::cout << "Remaining unparsed input: '" << std::string(f,l) << "'\n";
}
Prints:
5 packets successfully parsed
response: GET,DELAY,300,MODE,2;
DEBUG: setting property 'DELAY' to value '0'
DEBUG: setting property 'MODE' to value 'we can have string values too'
response: GET,MODE,we can have string values too;
DEBUG: setting property 'MODE' to value '42'
response: GET,MODE,42,DELAY,0;