QuickJS: Possible memory leak due to modifying function prototype - quickjs

I've encountered what seems like a bug in the QuickJS JavaScript engine. I've submitted a GitHub issue, but am also asking here to see if it might be user error, and/or to find out if others have encountered similar issues.
The following test code:
#include <string>
#include "quickjs.h"
int main() {
auto runtime = JS_NewRuntime();
auto context = JS_NewContext(runtime);
std::string source =
"function foo() {}\n"
"foo.prototype.bar = function() {};";
JS_Eval(context, source.c_str(), source.size(), "", JS_EVAL_TYPE_GLOBAL);
JS_FreeContext(context);
JS_FreeRuntime(runtime);
}
Produces the assertion:
Assertion failed: (list_empty(&rt->gc_obj_list)), function JS_FreeRuntime
Using the 'dump leaks' feature outputs the following:
Object leaks:
ADDRESS REFS SHRF PROTO CLASS PROPS
0x1071d4bc0 1 0* 0x1071c5510 Function { length: 0, name: 14'', prototype: [autoinit 0x1071c4e80 0 0x0] }
Which seems to suggest that modifying the function prototype is causing a memory leak. (This doesn't happen if the function prototype is left unmodified.)
Is there anything obviously wrong with my test code? Perhaps misuse of the API? If not, has anyone else run into this issue or similar issues with QuickJS?

For anyone who might stumble on this in the future, this was due to incorrect API usage. The leak wasn't due to the JavaScript code itself, but rather because JS_Eval() returns a JSValue, which needs to be freed using JS_FreeValue().

Related

AccessViolationException calling native C++ code from managed C++ (wrapper for ASP.NET)

I have a ASP.NET web application that needs access to a function in a native C++ DLL. To do this, I wrapped the native C++ code using a managed C++ DLL. Calling the native function from the managed code, however, results in a System.AccessViolationException. I do not have to the native code, but it will write to the file system (logs), which was my first guess, but according to other SO answers the AccessViolationException is caused by memory issues.
The code is pretty simple, this is the unshortened version:
#include <msclr\marshal_cppstd.h>
#define AS_NATIVE_STRING(managed_string) msclr::interop::marshal_as<std::string>(managed_string)
#define AS_MANAGED_STRING(native_string) msclr::interop::marshal_as<String^>(native_string)
ReturnStruct ManagedClass::execute_managed(String ^param1, String ^param2)
{
auto param1_native = AS_NATIVE_STRING(param1);
auto param2_native = AS_NATIVE_STRING(param2);
// here I get the exception:
auto result = _wrapped_api->execute_native(param1_native, param2_native);
if (is_error_string(result.first))
throw gcnew System::Exception(AS_MANAGED_STRING(result.second));
auto result1 = AS_MANAGED_STRING(result.first);
auto result2 = AS_MANAGED_STRING(result.second);
return ReturnStruct(result1, result2);
}
Any hints on what could be causing it? I did indeed look at similar questions, but no answer seemed to really fit my problem.
Edit:
Using HandleProcessCorruptedStateExceptionsAttribute I was able to determine the error message of the AccessViolationException: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
After further investigation, I have come to the conclusion, that I basically cannot fix this on my end. I created a mock version of the DLL myself to be able to step in and see if the type conversion is correct and the parameters contain the correct strings. This was the case. This does not really help me, but maybe someone else might find a problem in his/her code with this approach.
I will just contact the authors of the wrapped api.

c++ Intel inspector shows many errors with boost - do I need to worry?

I have a problem with my current program. For some reason it always crashed after the final line of code on windows. I got a "application is no longer responding" error or something like this.
So I tried the Intel inspector. And Luckily it told me some bad errors in my project where I accessed some uninitialized memory.
Besides this obvious problems that I understand I get also some:
Incorrect memcpy calls in: boost::algorithm::trim()
Uninitialized partial memory access in: myptree.get<boost::posix_time::ptime>("path.to.node") where myptree is of type boost::property_tree::ptree
Uninitialized memory access in: cout << myptime where myptime is of type boost::posix_time::ptime
...
does this mean that I use the boost library functions not properly? Or are this false positives?
I'm just confused because the functions work, they do what I want them to do and I get no error message.
I also get a Memory not deallocated warning at the end (from [Unknown] source).
example for trim:
#include <iostream>
#include <boost/algorithm/string.hpp>
int main() {
std::string test = " test ";
boost::algorithm::trim(test);
std::cout << test << std::endl;
return 0;
}
gives me a incorrect memcpy call...
Boost will happily forward bad arguments; it often has no way to check them. If boost::algorithm::trim passes a bad argument to memcpy, it will be because you passes a bad argument to trim.
So, yes, you should worry. There are almost certainly multiple bugs in your program. Check your calls to the functions reported.

How to remediate Microsoft typeinfo.name() memory leaks?

Microsoft has a decades old bug when using its leak check gear in debug builds. The leak is reported from the allocation made by the runtime library when using C++ type information, like typeinfo.name(). Also see Memory leaks reported by debug CRT inside typeinfo.name() on Microsoft Connect.
We've been getting error reports and user list discussions because of the leaks for about the same amount of time. The Microsoft bug could also mask real leaks from user programs. The latter point is especially worrisome to me because we may not tending to real problems because of the masking.
I'd like to try to squash the leaks due to use of typeid(T) and typeinfo.name(). My question is, how can we work around Microsoft's bug? Is there a work around available?
On the line of my suggestion in the Q's comments.
For if (valueType == typeid(int)) you can use the type_index (at least since C++11)
For type_info.name() leaking memory:
Since totally eliminating the leak doesn't seem possible, the next best thing would be reduce their number (to only one leaked per type interrogation) and, secondary, to tag them for reporting purposes. Being inside some templated classes, one can hope that the 'mem leaking' report will use the class names (or at least the source file where the allocation happened) - you can subsequently use this information to filter them out from the 'all leaked memory' reports.
So instead of using typeid(<typename>), you use something like:
"file typeid_name_workaround.hpp"
template <typename T> struct get_type_name {
static const char* name() const {
static const char* ret=typeid(T).name();
return ret;
}
};
Other .cpp/.hpp file
#include "typeid_name_workaround.hpp"
struct dummy {
};
int main() {
// instead of typeid(dummy).name() you use
get_type_name<dummy>::name();
}

llvm InitializeNativeTarget() is undefined

All of the samples I'm seeing show llvm::InitializeNativeTarget() being called on the first line.
I just finished building llvm and clang and am trying to get my first sample running and this function appears to be undefined. I'm not sure if it is actually undefined and these examples are stale, or if I did something wrong in a previous step.
Where would I find the definition of this function if it is supposed to exist? Is there something else I should be calling instead?
InitializeNativeTarget(); /* error, undefined */
llvm_start_multithreaded();
LLVMContext context;
string error;
llvm::OwningPtr<MemoryBuffer> buffer;
auto result = MemoryBuffer::getFile("test.bc", buffer);
auto m = ParseBitcodeFile(buffer.get(), context, &error);
auto ee = ExecutionEngine::create(m, true, &error);
With the code above, and a test.bc file compiled via clang I am getting a null ExecutionEngine so I'm assuming I'm not initializing something correctly.
Surprisingly hard to find but the function appears to have been renamed to:
LLVMInitializeNativeTarget()
Simply calling that function solved my problem.
(also I needed to call ExecutionEngine::create(m, false, &error) instead of true)
This is just a clarification. Actually, function llvm::InitializeNativeTarget can be found in
#include "llvm/Support/TargetSelect.h"
Your called function llvm::LLVMInitializeNativeTarget exists in
#include "llvm-c/Target.h"
The latter header file is already included by ExecutionEngine.h. Therefore you found it. Both functions seem identical (until v3.9.1 at least) except for their return value. However, the former is the one used in LLVM examples and I'd recommend sticking with it especially if you are using C++.

invalid cruntime parameter _itoa_s

I have experienced a strange behavior when using _itoa_s and _ultoa_s if I try to get a char array from an DWORD. The function returns zero(success) and my application continues, but I'm getting an exception window with error code 0xc0000417 (STATUS_INVALID_CRUNTIME_PARAMETER).
ULONG pid = ProcessHandleToId(hProcess);
int size = getIntSize(pid);
char *pidStr = new char[size+1];
_ultoa_s(pid, pidStr, size+1, 10);
//do sth with pidStr...
delete[] (pidStr);`
ProcessHandleToId returns the PID (DWORD) for a given ProcessHandle.
getIntSize returns the number of numbers to the corresponding int/char array (5555 => 4).
Yes, the safe CRT functions will abort your program with status code 0xc0000417 when they detect a problem. However, they will do this immediately, the function will not return.
Which means that you are looking at the wrong source code for this problem. It isn't the _ultoa_s() call that's bombing your program. It's another function call, somewhere else in your code. I can't help you find it of course. But the debugger should give you a good idea, look at the call stack when it breaks.
I just compiled your code and it runs fine. The int to string conversion is correct. I assume you bump into security issues due to missing permission when trying to access process handles you don't own.