I don't use exception handling in any of my libraries or applications. Everything is built with Exception handling off and Windows applications using MS Visual Studio are linked with nothrownew.obj. The code handles any failures itself. The fact that the CRT is out behind my back throwing exceptions and terminating the program instead of returning an error result is a problem.
For example, this crashed when provided a drive letter that no longer existed instead of just returning the errcode.
if (_tgetdcwd(driveltr ? DriveLtrToDOSDriveNum(driveltr) : 0, dirout, diroutbufsize)==NULL) {
errcode=GetErrorFromErrno();
}
For now on Windows I've used the _set_invalid_parameter_handler() to prevent the nasty issue above. Goes something like this:
void invalid_parameter_function(const wchar_t * expression, const wchar_t * function, const wchar_t * file, unsigned int line, uintptr_t pReserved)
{
}
int _tmain(int argc, const TCHAR *argv[])
{
_set_invalid_parameter_handler(invalid_parameter_function);
}
Is there a way to ensure the CRT doesn't throw exceptions for both MS Visual Studio 2017 and the CRT used with g++? If not and must setup a handler like I did above for Windows, does g++ have one?
TIA!!
Related
So I'm trying to start on GPU programming and using the Thrust library to simplify things.
I have created a test program to work with it and see how it works, however whenever I try to create a thrust::device_vector with non-zero size the program crashes with "Run-time Check Failure #3 - The variable 'result' is being used without being initialized.' (this comes from the allocator_traits.inl file) And... I have no idea how to fix this.
The following is all that is needed to cause this error.
#include <thrust/device_vector.h>
int main()
{
int N = 100;
thrust::device_vector<int> d_a(N);
return 0;
}
I suspect it may be a problem with how the environment is set up so the details on that are...
Created using visual studio 2019, in a CUDA 11.0 Runtime project (the example program given when opening this project works fine, however), Thrust version 1.9, and the given GPU is a GTX 970.
This issue only seems to manifest with the thrust version (1.9.x) associated with CUDA 11.0, and only in debug projects on windows/Visual Studio.
Some workarounds would be to switch to building a release project, or just click "Ignore" on the dialogs that appear at runtime. According to my testing this allows ordinary run or debug at that point.
I have not confirmed it, but I believe this issue is fixed in the latest thrust (1.10.x) just released (although not part of any formal CUDA release at this moment, I would expect it to be part of some future CUDA release).
Following the Answer of Robert Crovella, I fixed this issue by changing the corresponding lines of code in the thrust library with the code from GitHub. More precisely, in the file ...\CUDA\v11.1\include\thrust\detail\allocator\allocator_traits.inl I replaced the following function
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_system<Alloc>::value,
typename allocator_system<Alloc>::type
>::type
system(Alloc &)
{
// return a copy of a default-constructed system
typename allocator_system<Alloc>::type result;
return result;
}
by
template<typename Alloc>
__host__ __device__
typename disable_if<
has_member_system<Alloc>::value,
typename allocator_system<Alloc>::type
>::type
system(Alloc &)
{
// return a copy of a default-constructed system
return typename allocator_system<Alloc>::type();
}
I want to make a command line tool by Flash Air, but there is not any api of AS3 to output content to standard output.
Then, I try to use ANE to solve my problem(By making a windows ane and use C's printf function to output content), but it doesn't work.
Is there any methods to use the standard output by Flash air, or to make a command line tool by Flash Air?
The code of dll written by c++ is:
FREObject add(FREContext ctx, void* functionData, uint32_t argc, FREObject argv[])
{
int32_t x,y;
FREGetObjectAsInt32(argv[0], &x);
FREGetObjectAsInt32(argv[1], &y);
int32_t result = x + y;
FREObject resObj;
FRENewObjectFromInt32(result, &resObj);
//I want to use the "printf" to print content to the console
printf("print by dll: the result is %d\n", result);
return resObj;
}
but there is not any api of AS3 to output content to standard output.
Only a running OS process can give back Standard Output (also called stdio in C).
The best you can do is create an app that looks like commandline tool but in reality it just runs & passes data to the actual (native) OS commandline tool. Meaning in your tool you capture the user command to a string and then run a nativeProcess involving that (parsed) string as your process arguments.
Example in your app user types : calc. Your AIR runs: c:\Windows\System32\calc.exe
Anyways, on to your real question...
I try to use C's printf function to output content, but it doesn't
work.
If you mean you made some test.exe with C and when you get AIR to run it you want to capture the printf output then you can try:
process.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, CTest_OutputData);
or
process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, CTest_ErrorData);
To catch the output (it will be sent as bytes) make sure you have some public byteArray and String created. Here's an example for STANDARD_ERROR_DATA (it's likely the output goes here too, since you claim that STANDARD_OUTPUT_DATA is not working).
The code shown below inside that function works same whichever type of progressEvent you choose. Just put in the "right" one. temp_BA is the byteArray variable you setup earlier.
public function CTest_ErrorData (event:ProgressEvent):void
{
process.standardOutput.readBytes( temp_BA, temp_BA.length, process.standardOutput.bytesAvailable );
if ( temp_BA.length > 0 )
{
temp_String = temp_BA.readUTFBytes(temp_BA.length);
trace( "temp_String is : " + temp_String ); //if you want to check it
}
}
Final TIP: You can get traces inside Flash IDE by disabling "desktop" and keeping "extended desktop" ticked. Both must be ticked later when you make installing app.
I recently encountered a problem with asynchronous operations in MSMQ. In .NET 2.0, 3.0 and 3.5, if there is a pending asynchronous receive, and the queue is deleted, the callback is invoked and upon calling EndReceive, the exception is thrown.
In .NET 4.0, the callback is never invoked, but the exception can be caught by the AppDomain.UnhandledException event handler. When running in the debugger, the application will simply terminate with no notification from Visual Studio that an exception occurred.
This code is executing on Windows 7 Professional, 64-bit. However the behavior is the same whether the application is targeting x86 or x64. (Edit: verified this behavior on XP SP3 32-bit as well - this appears to be a framework bug, not OS-related)
I am assuming this new behavior is related to .NET 4.0 being a completely new runtime. I'm not sure what to do at this point, but essentially I am looking to get the pre-.NET 4.0 behavior back, while still targeting the .NET 4.0 runtime. Any help or advice would be greatly appreciated. Here is sample code to reproduce the problem:
class Program
{
static void Main( string[] args )
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
string path = #".\private$\mytestqueue";
// Create queue only if it doesn't already exist.
var queue = MessageQueue.Exists( path ) ? new MessageQueue( path ) : MessageQueue.Create( path );
queue.BeginReceive( TimeSpan.FromSeconds( 15 ), queue, new AsyncCallback( ReceiveComplete ) );
Thread.Sleep( 5000 );
MessageQueue.Delete( path );
}
static void CurrentDomain_UnhandledException( object sender, UnhandledExceptionEventArgs e )
{
var mqEx = (MessageQueueException) e.ExceptionObject;
// .NET 4.0:
// "The queue does not exist or you do not have sufficient
// permissions to perform the operation."
Console.WriteLine( mqEx.Message );
// "QueueNotFound"
Console.WriteLine( mqEx.MessageQueueErrorCode );
}
static void ReceiveComplete( IAsyncResult ar )
{
// This callback is never invoked under .NET 4.0.
Console.WriteLine( "Finishing Receive." );
var queue = (MessageQueue) ar.AsyncState;
try
{
queue.EndReceive( ar );
}
catch ( MessageQueueException mqEx )
{
// .NET 2.0 through 3.5:
// "Queue handle can no longer be used to receive messages
// because the queue was deleted. The handle should be closed."
Console.WriteLine( mqEx.Message );
// "QueueDeleted"
Console.WriteLine( mqEx.MessageQueueErrorCode );
}
}
}
Addendum:
After spending way too much time trying to use source stepping (System.Messaging source is available for 4.0 but not for 2.0/3.5, it appears), and hunting through the two different System.Messaging assemblies with Reflector, I finally found the problem.
In the 2.0 assembly, some try/catch blocks are used in the MessageQueue.AsynchronousRequest.RaiseCompletionEvent method to catch exceptions and store an error code so that the exception can be raised when .EndReceive() is called. However, in the 4.0 assembly, these try/catches are gone, so when an exception occurs the process must terminate since they are un-caught on a background thread.
Unfortunately this doesn't help me fix the problem. I am considering switching to a synchronous Receive, but I liked the idea of taking advantage of I/O completion ports for this.
Well, I am going to answer this and accept it, since I think it's the best answer for the near future. It could be months (or more) before there is a proper solution.
As mentioned above, I filed a bug report on Microsoft Connect, so it is pretty much up to them to revert the behavior to how it worked in CLR 2.0.
Microsoft Connect: http://connect.microsoft.com/VisualStudio/feedback/details/626177/messagequeue-beginreceive-asynchronous-exception-behavior
As far as how this affects my application, I am not willing to switch to a synchronous Receive method, as that would consume all of the available worker threads on the thread pool. My application frequently creates and removes a lot of queues, and this issue arose when a command to remove a queue was issued, but an outstanding read operation was pending. Instead, I will just mark that a queue needs to be removed, and once a safe period of time has elapsed (two times the BeginReceive timeout, for instance), I will actually remove the queue.
Or switch to a different queuing system than MSMQ, though I've been happy with it so far.
I've written a cuda plugin (dynamic library), and I have a program written in C which uses dlopen() to load this plugin. I am using dlsym() to get the functions from this plugin. For my application it is very important that any time of loading plugin the program gets a new handle with dlopen() calling (the library file may modified subsequently).
Therefore after the using of functions from my plugin I invoke the dlclose(). The invocations dlopen() - dlsym() - dlclose() are occur during my program execution (in the loop).
If I working on the computer with NVIDIA driver 256.35 (CUDA 3.0 or 3.1) I have a memory leak (I use in my plugin cudaMemGetInfo() calling for the diagnostics).
If I working on the computer with NVIDIA driver 195.36.15 (CUDA 3.0) I have an error after some time of the program execution: “NVIDIA: could not open the device file /dev/nvidia0 (Too many open files).”
If I don't use the dlclose() invocation the program is working fine, but in this case I can't replace the plugin on a new one's during my program execution.
Anyone encountered this problem?
Thanks.
Nobody wrote plugins on CUDA?
I've found the similar example on CUDA SDK: matrixMulDynlinkJIT. I've done small correction in the code. In particular, in the file cuda_drvapi_dynlink.c I've corrected cuInit() function:
CUDADRIVER CudaDrvLib = NULL;
CUresult CUDAAPI cuInit(unsigned int Flags)
{
//CUDADRIVER CudaDrvLib;
CUresult result;
int driverVer;
if (CudaDrvLib != NULL) {
dlclose (CudaDrvLib);
CudaDrvLib = NULL;
}
.......
}
And in the file matrixMulDynlinkJIT.cpp I've added loop in the main() function:
int main(int argc, char** argv)
{
printf("[ %s ]\n", sSDKsample);
while (1) {
// initialize CUDA
CUfunction matrixMul = NULL;
cutilDrvSafeCallNoSync(initCUDA(&matrixMul, argc, argv));
.....
}//while (1)
cutilExit();
}
So, I have the same problem like in my program (after some time execution): “NVIDIA: could not open the device file /dev/nvidia0 (Too many open files).”
But when I comment out the dlclose() in the cuda_drvapi_dynlink.c file – all works fine
I can't understand this behavior...
Any ideas?
I have a (rather large) application that I have written in C++ and until recently it has been running fine outside of visual studio from the release build. However, now, whenever I run it it says "Unhandled exception at 0x77cf205b in myprog.exe: 0xC0000005: Access violation writing location 0x45000200.", and leads me to "crtexe.c" at line 582 ("mainret = main(argc, argv, envp);") if I attempt to debug it. Note that this problem never shows if I run my debug executable outside of visual studio, or if I run my debug or release build within visual studio. It only happens when running the release build outside of visual studio.
I have been through and put plenty of printfs and a couple of while(1)s in it to see when it actually crashed, and found that the access violation occurs at exactly the point that the value is returned from the function (I'm returning a pointer to an object). I don't fully understand why I would get an access violation at the point it returns, and it doesn't seem to matter what I'm returning as it still occurs when I return 0.
The point it started crashing was when I added a function which does a lot of reading from a file using ifstream. I am opening the stream every time I attempt to read a new file and close it when I finish reading it.
If I keep attempting to run it, it will run once in about 20 tries. It seems a lot more reliable if I run it off my pen drive (it seems to crash the first 3 or 4 times then run fine after that - maybe it's due to its slower read speed).
Thanks for your help, and if I've missed anything let me know.
EDIT: New info
Well I removed the entirity of the function and replaced it with:
IndexedMesh * loadObj(char * objName)
{
ifstream fp_in;
fp_in.open("lol.bmp", ios::in);
fp_in.clear();
fp_in.close();
IndexedMesh * mesh = new IndexedMesh();
printf("finished");
return mesh;
}
I also tried it with "return 0" and "return new IndexedMesh()". It's all fine until you put the ifstream stuff in. I do have 2 other ifstreams open in different functions (accessing completely different files). Could this be the problem?
It actually errors on the return mesh line, (I got the debugger working with the separate release file). It completely nulls the mesh object when it attempts to return it.
The point it started crashing was when I added a function which does a lot of reading from a file using ifstream. I am opening the stream every time I attempt to read a new file and close it when I finish reading it.
Given your description of the code only failing in release mode outside the debugger I'd examine this function for any unset variables. Compiling debug sets variables (or at least it used to) as did running release code in the debugger.
You are probably running over something stored deep in the stack.
I'll bet that if you were to put this at near the top of your code:
int my_main(int argc, char * argv[], char * envp[]);
int main(int argc, char * argv[], char * envp) {
char ** a;
char ** e;
a = malloc(argc+1); // note: you should test the results for NULL
e = malloc(1+count(envp) ) ;// I'm not writing code to count it, but it's easy
int i = 0;
while (argv[i++]) {
a[i] = strdup(argv[i]);
}
a[i] = argv[i]; // argv[i] is NULL and already in a register
// do the same thing for envp
return my_main(argc, a, e);
}
#define main my_main
then whatever it is that is smashing your stack would instead end up smashing this duplicated environment. It's not garenteed, and it is no fix for your problem, but not that difficult.
Thanks very much for your help, I haven't exactly solved the problem but I have managed to evade it. Basically, if I even mentioned an ifsteam (in that function and that function only), the program crashed.
I actually went as far as altering the function to simply declare an ifstream then return 0. I "fixed" it by declaring the ifstreams as pointers and new-ing them. If I deleted the pointer it crashed out again so I had to set it to 0 (leeeeak).
If anyone could enlighten me as to why this occurs, that would be great. While I'm just happy it works now, I'd rather know why..