Are local objects destructed in the case of a leave on Symbian? - memory-leaks

On Symbian, if a function exits because of a leave, are the destructors of its local (automatic) variables called?
From what I've tried on the emulator, they are. But then, why use the Cleanup Stack rather then smart pointers?

Yes, automatic variables are properly destructed. Since (I think) version 9.1 of Symbian OS, leave is implemented using C++ exceptions.
Earlier versions of Symbian did not support exceptions at all, hence the whole cleanup stack mechanism. Automatic variables would not have had their destructors called when leaving.

Related

How do sandboxing environments recover from faults?

In JavaScript runtimes and other JIT-compiled environments where code needs to be sandboxed, how can the larger program recover when the dynamically loaded code faults?
For instance, the code that SpiderMonkey generates for WebAssembly contains instructions which throw SIGILL when they are executed (e.g., to do a bounds check). When such a fault is thrown, I suppose the exception handler of the JavaScript engine is called. But such a signal handler is very restricted in its abilities. To jump out of the bad dynamically generated code it would typically use siglongjmp, but if I understand the notes at the bottom of man signal-safety correctly, if that happens, then no other unsafe function may be used by the program ever again. Such a restriction is of course unreasonable for a JS runtime (e.g.).
So how do sandboxing environments recover from child faults without losing abilities (in particular, becoming restricted to only async-safe functions)?
One thought I had is that perhaps the sandboxed code is ran in another thread with its own signal handler, so that the main thread does not lose any abilities when the child thread receives a signal. But I don't know whether that is correct; I find it hard to find documentation on how signals and threads interact exactly.
As you will see this question is tagged posix, but I am in principle also interested in the Windows approach.

Why can I not blocking main thread in WinRT(Windows Store App)?

This question is not about "should I block my main thread" as it is generally a bad idea to block a main/STA/UI thread-for messaging and UI operations, but why WinRT C++/cx doesn't allow any blocking of the main thread compared to iOS, Android, and even C#(await doesn't actually block though).
Is there a fundamental difference in the way Android or iOS block the main thread? Why is WinRT the only platform that doesn't allow any form of blocking synchronization?
EDIT: I'm aware of co-await in VS2015, but due to backward compatibility my company still uses VS2013.
Big topic, at break-neck speed. This continues a tradition that started a long time ago in COM. WinRT inherits about all of the same concepts, it did get cleaned-up considerably. The fundamental design consideration is that thread-safety is one of the most difficult aspects of library design. And that any library has classes that are fundamentally thread-unsafe and if the consumer of the library is not aware of it then he'll easily create a nasty bug that is excessively difficult to diagnose.
This is an ugly problem for a company that relies on a closed-source business model and a 1-800 support phone number. Such phone calls can be very unpleasant, threading bugs invariably require telling a programmer "you can't do that, you'll have to rewrite your code". Rarely an acceptable answer, not at SO either :)
So thread-safety is not treated as an afterthought that the programmer needs to get right by himself. A WinRT class explicitly specifies whether or not it is thread-safe (the ThreadingModel attribute) and, if it is used in an unsafe way anyway, what should happen to make it thread-safe (the MarshallingBehavior attribute). Mostly a runtime detail, do note how compiler warning C4451 can even make these attributes produce a compile-time diagnostic.
The "used in an unsafe way anyway" clause is what you are asking about. WinRT can make a class that is not thread-safe safe by itself but there is one detail that it can't figure out by itself. To make it safe, it needs to know whether the thread that creates an object of the class can support the operating system provided way to make the object safe. And if the thread doesn't then the OS has to create a thread by itself to give the object a safe home. Solves the problem but that is pretty inefficient since every method call has to be marshalled.
You have to make a promise, cross-your-heart-hope-to-die style. The operating system can avoid creating a thread if your thread solves the producer-consumer problem. Better known as "pumping the message loop" in Windows vernacular. Something the OS can't figure out by itself since you typically don't start to pump until after you created a thread-unsafe object.
And just one more promise you make, you also promise that the consumer doesn't block and stops accepting messages from the message queue. Blocking is bad, implicit is that worker threads can't continue while the consumer is blocking. And worse, much worse, blocking is pretty likely to cause deadlock. The threading problem that's always a significant risk when there are two synchronization objects involved. One that you block on, the other that's hidden inside the OS that is waiting for the call to complete. Diagnosing a deadlock when you can't see the state of one of the sync objects that caused the deadlock is generally unpleasant.
Emphasis on promise, there isn't anything the OS can do if you break the promise and block anyway. It will let you, and it doesn't necessarily have to be fatal. It often isn't and doesn't cause anything more than an unresponsive UI. Different in managed code that runs on the CLR, if it blocks then the CLR will pump. Mostly works, but can cause some pretty bewildering re-entrancy bugs. That mechanism doesn't exist in native C++. Deadlock isn't actually that hard to diagnose, but you do have to find the thread back that's waiting for the STA thread to get back to business. Its stack trace tells the tale.
Do beware of these attributes when you use C++/CX. Unless you explicitly provide them, you'll create a class that's always considered thread-safe (ThreadingModel = Both, MarshallingType = Standard). An aspect that is not often actually tested, it will be the client code that ruins that expectation. Well, you'll get a phone call and you have to give an unpleasant answer :) Also note that OSX and Android are hardly the only examples of runtime systems that don't provide the WinRT guarantees, the .NET Framework does not either.
In a nutshell: because the policy for WinRT apps was "thou shalt not block the UI thread" and the C++ PPL runtime enforces this policy whilst the .NET runtime does not -- look at ppltasks.h and search for prevent Windows Runtime STA threads from blocking the UI. (Note that although .NET doesn't enforce this policy, it lets you accidentally deadlock yourself instead).
If you have to block the thread, there are ways to do it using Win32 IPC mechanisms (like waiting on an event that will be signaled by your completion handler) but the general guidance is still "don't do that" because it has a poor UX.

Must a DLL be multithread when called by a Delphi object?

I derived a TMyThread object from TThread in Delphi, and in TMyThread.Execute, it will invoke a DLL written by Visual C++. In that case, must the DLL also compiled with the Multi-thread library and support multi-thread as well?
Older versions of the MSVC runtime come in both multi-threaded and single-threaded variants. The difference is that the single-threaded variant does not protect against potential race conditions. So, if the code that calls into the MSVC runtime does so from more than one thread, the single-threaded runtime cannot be safely used.
The scenario that you describe has only a single thread executing code inside your MSVC DLL. In which case the single-threaded MSVC runtime is safe to use. It does not matter that the host executable is multi-threaded. All that counts is whether multiple threads call into the MSVC runtime attached to your MSVC DLL.
MSVC stopped shipping separate single-threaded and multi-threaded runtimes many releases ago. One wonders whether or not it makes a difference to your application. Can you detect any performance difference between the two runtime options. If not then it would make sense to me to use the multi-threaded runtime. Choosing the single-threaded runtime is just storing up a potential debugging headache when you forget about this in a future change to the code and introduce extra threads to your MSVC DLL.
The C++ DLL should be MT, if you intend to use it MT. If you intend to use it from only one single thread of your application, then you don't have to do that. But you should clearly document this as soon as you have the slightest doubt that there could be a thread conflict, e.g. with data structures internally managed within the DLL. Or use MT anyway, take care of proper locking and forget about it. (My previous Delphi statement still stands true).

If I don't call clRelease* ,will it cause memory leak?

I want to add some OpenCL support to Chromium, so I used APIs like clCreateCommandQueue(), but I can't find a proper place in Chromium to do cleanup.
So, if I don't call APIs like clReleaseCommandQueue(), will OS reclaim the memory after the process terminates? Or need I call it at the exit point of the process?
PS, The commandqueue is needed during the whole life of the process, so I just want to make sure it will not cause memory leak after process termination.
Thank you for help.
Since all the OpenCL objects are, ultimately, held by the device driver, you can't expect them to be automatically released once the application terminates. That is always your job.
If you use the OpenCL C++ wrapper (cl.hpp) then the compiler will figure out where to clean up your objects (when the referring object goes out of scope).

Win32 alternative for the destructor in pthread_keycreate (when I cannot control dllmain)

In pthreads, you can associate a destructor function with each per-thread storage slot. When a thread dies, if the slot is non-0, the destructor is called.
In a Win32 DLL, the DLLMain function, called at thread exit, can do the same thing.
What can I do in code that lives in a purely static library?
This is a hard problem, and requires sticking callbacks in special locations. Luckily for you, it is solved in Boost.Thread. Use boost::this_thread::at_thread_exit, or boost::thread_specific_ptr
Windows support Thread Local Storage (TLS) in a DLL. It can be very practical if you want have some memory blocks per thread with the unique value (unique per thread). Inside of any other function from the DLL you can get the value which correspond to the current thread in very easy way. It is very useful in some scenarios. Look at here for more details.
I dun't use pthreads myself, but I suppose that per-thread storage slot introduced to make the work with TLS more comfortable.
UPDATED: From your comment I see that you misunderstand my answer. I'm not a POSIX developer, I develop in Win32 only and your question is about WIn32 API possibilities of per-thread allocation and deallocations. I try to explain the possibilities and you can decide yourself which one are better for your specific scenarios.
The equivalent of pthread_XXX functions in Win32 are following:
pthread_key_create TlsAlloc
pthread_setspecific TlsSetValue
pthread_getspecific TlsGetValue
pthread_key_delete TlsFree
I not recommended you to use the construct __declspec(thread), which is more compiler specific.
The example Using Thread Local Storage shows how to use thread local storage (TLS) without DLLs, but I personally like and use TLS only in DLL.
The destructor parameter of the pthread_key_create function has no analog in Win32, but I don't see here any problem. All C/C++ compilers support __try {/**/} __finally {/**/} construct of the Structured Exception Handling so you can use it in the body of your thread function and implement in the way any Cleaning up Resources exacly like you can do this in the main thread.
I find pity that you not included in your question an example which shows how you typically use destructor of the pthread_key_create function. I find that examples can clear much things without a lot of words. So if my answer do not help you we can better explain all in examples: you write an example and probably short comment what it should do and I could write the same code using Win32 API only in C or C++.

Resources