C++ program to get the current time - c++

I have to create a simple window service program which is to be executed in visual studio using C++ language. I have used ctime and localtime keywords but it returns an error saying:
This function or variable may be unsafe. Consider using any other ....
I am using Visual Studio 2019

You can use std::chrono::system_clock::now() function to get the current time point.

ctime and localtime are unsafe as these returns pointer to static data.
Therefore, ctime_s and localtime_s are provided in VS2019 (also in some earlier versions), which takes a pre allocated pointer in which value need to be returned and hence safe to use.

Related

Warning C4640 in ATL Macro END_CONNECTION_POINT_MAP

I am getting the warning
warning C4640: '_entries': construction of local static object is not thread-safe
from the ATL macro END_CONNECTION_POINT_MAP, for example
BEGIN_CONNECTION_POINT_MAP(CMBusInclinometerTemChannel)
CONNECTION_POINT_ENTRY(__uuidof(IChannelEvents))
END_CONNECTION_POINT_MAP()
in a C++ ATL/COM project.
I think that this has started happening since installing Visual Studio 2015 update 2.
Does anybody have a solution to this problem?
I thought it might be a new warning, but no - it was earlier just turned off by default. I suppose it is a long standing "problem", however it might be not so easy to convert it to a real bug (if at all possible and has side effects).
The problem is about the map of connection points using static local variable _entries internally, which is initialized on first use in a thread-unsafe manner. It is however an initialization of a pointer with fixed values the pointer refers to. The problem might possibly be that thread #1 treats map as initialized while thread #2 is just in the middle of initialization. Pretty rare condition, no wonder there has been no complaints so far.
Solution might be in surrounding the static variable initialization with global critical section lock, such as
ATLASSERT(_pAtlModule);
CComCritSecLock<CComCriticalSection> Lock(_pAtlModule->m_csStaticDataInitAndTypeInfo);
static ...
in the map macros, and suppression of the warning using #pragma. This should be a fix in ATL headers code (atlcom.h).

StrPtr not recognized in visual basic (VS 2012)?

I'm using VS 2012:
Here's my situation:
I'm writing some code in visual basic that calls a dll function that I've written in C++ (also written using vs 2012). One of my function's arguments takes the wchar_t* data type, so I need to format my string from vb accordingly using StrPtr.
Here's my problem:
Visual Basic does not recognize StrPtr as a function. I get: 'StrPtr' is not declared. It may be inaccessible due to its protection level.'
What does this mean?
StrPtr is a VB6 function, it does not exist in VB.Net
VarPtr, VarPtrArray, VarPtrStringArray, ObjPtr and StrPtr were
undocumented functions used to get the underlying memory address of
variables. These functions are not supported in Visual Basic .NET.
The equivalent .Net Framework method for wide strings is Marshal.StringToHGlobalUni().
Although likely you should be using P/Invoke to call a C++ funciton in which case the marshaling of a String to wchar_t is handled automatically.
This keyword has been removed from the language:
VarPtr, VarPtrArray, VarPtrStringArray, ObjPtr and StrPtr are
undocumented functions used to get the underlying memory address of
variables. These functions are not supported in Visual Basic 2008.

Problem found: Visual Studio CRT library : FLS_GETVALUE

Today, I was checking source code of the CRT library of Visual Studio 2008 and 2010 and I found a bug into the file mtdll.h. The problem is with the macro FLS_GETVALUE. On x86 systems, this macro call directly TlsGetValue instead of making a call to the function assigned to the variable gpFlsGetValue.
First of all, it's a problem because FlsAlloc, FlsGetValue, FlsFree and FlsSetValue are not available on all system( Windows Vista+ and Windows Server 2003+). These functions behave like TlsAlloc, TlsGetValue, TlsFree and TlsSetValue but support Fibers(kind of user thread). Because we should prefer using Fls* functions instead of Tls functions, the C runtime library of VS check if the Fls functions are availables when the process or the dll is loaded and initialise the gpFls* variables. If the Fls* are not available, the CRT initialise these variables with the equivalent Tls* functions.
You cannot use the macro FLS_GETVALUE directly into your code because it's used internally by the runtime library. The runtime use this macro to initialise per thread data of the runtime library.
My question is about the impact of this bug. I know that fiber are not widely used, but if you develop a DLL that is used inside an application that use fiber, what can be the impact? Does this bug can cause a crash of the application or only produce false results? Does this problem can cause problem with widely used application like SQL Server? What do you think? Does this bug can be a security risk? Does IIS or ASP.Net use fiber that can cause a crash?
For curious people, here the current source of the problematic line in mtdll.h:
#define FLS_GETVALUE ((PFLS_GETVALUE_FUNCTION)TlsGetValue(__getvalueindex))
Here a fixed version of the macro FLS_GETVALUE :
#define FLS_GETVALUE (((PFLS_GETVALUE_FUNCTION)DecodePointer(gpFlsGetValue))(__getvalueindex))
For now, I should find how to submit a bug to Microsoft.
I'm not sure about that. The CRT seems to handle FlsGetValue differently from the other FLS functions. It looks like the CRT is storing a pointer to the FlsGetValue function in TLS (pseudo-code):
void init_fls()
{
FLS_GET_VALUE_PROC proc = GetProcAddress(kernel32, "FlsGetValue");
if(!proc)
{
// FlsGetValue not implemented on this platform
// use alternative implementation provided by CRT
proc = __crtFlsGetValue;
}
// store pointer to FlsGetValue proc in TLS
TlsSetValue(fls_get_value_index, proc);
}
void* get_fls_value(int index)
{
// retrieve pointer to FlsGetValue proc from TLS
FLS_GET_VALUE_PROC proc = TlsGetValue(fls_get_value_index);
return proc(index);
}

Weird MSC 8.0 error: "The value of ESP was not properly saved across a function call..."

We recently attempted to break apart some of our Visual Studio projects into libraries, and everything seemed to compile and build fine in a test project with one of the library projects as a dependency. However, attempting to run the application gave us the following nasty run-time error message:
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function pointer declared with a different calling convention.
We have never even specified calling conventions (__cdecl etc.) for our functions, leaving all the compiler switches on the default. I checked and the project settings are consistent for calling convention across the library and test projects.
Update: One of our devs changed the "Basic Runtime Checks" project setting from "Both (/RTC1, equiv. to /RTCsu)" to "Default" and the run-time vanished, leaving the program running apparently correctly. I do not trust this at all. Was this a proper solution, or a dangerous hack?
This debug error means that the stack pointer register is not returned to its original value after the function call, i.e. that the number of pushes before the function call were not followed by the equal number of pops after the call.
There are 2 reasons for this that I know (both with dynamically loaded libraries). #1 is what VC++ is describing in the error message, but I don't think this is the most often cause of the error (see #2).
1) Mismatched calling conventions:
The caller and the callee do not have a proper agreement on who is going to do what. For example, if you're calling a DLL function that is _stdcall, but you for some reason have it declared as a _cdecl (default in VC++) in your call. This would happen a lot if you're using different languages in different modules etc.
You would have to inspect the declaration of the offending function, and make sure it is not declared twice, and differently.
2) Mismatched types:
The caller and the callee are not compiled with the same types. For example, a common header defines the types in the API and has recently changed, and one module was recompiled, but the other was not--i.e. some types may have a different size in the caller and in the callee.
In that case, the caller pushes the arguments of one size, but the callee (if you're using _stdcall where the callee cleans the stack) pops the different size. The ESP is not, thus, returned to the correct value.
(Of course, these arguments, and others below them, would seem garbled in the called function, but sometimes you can survive that without a visible crash.)
If you have access to all the code, simply recompile it.
I read this in other forum
I was having the same problem, but I just FIXED it. I was getting the same error from the following code:
HMODULE hPowerFunctions = LoadLibrary("Powrprof.dll");
typedef bool (*tSetSuspendStateSig)(BOOL, BOOL, BOOL);
tSetSuspendState SetSuspendState = (tSuspendStateSig)GetProcAddress(hPowerfunctions, "SetSuspendState");
result = SetSuspendState(false, false, false); <---- This line was where the error popped up.
After some investigation, I changed one of the lines to:
typedef bool (WINAPI*tSetSuspendStateSig)(BOOL, BOOL, BOOL);
which solved the problem. If you take a look in the header file where SetSuspendState is found (powrprof.h, part of the SDK), you will see the function prototype is defined as:
BOOLEAN WINAPI SetSuspendState(BOOLEAN, BOOLEAN, BOOLEAN);
So you guys are having a similar problem. When you are calling a given function from a .dll, its signature is probably off. (In my case it was the missing WINAPI keyword).
Hope that helps any future people! :-)
Cheers.
Silencing the check is not the right solution. You have to figure out what is messed up with your calling conventions.
There are quite a few ways to change the calling convetion of a function without explicitly specifying it. extern "C" will do it, STDMETHODIMP/IFACEMETHODIMP will also do it, other macros might do it as well.
I believe if run your program under WinDBG (http://www.microsoft.com/whdc/devtools/debugging/default.mspx), the runtime should break at the point where you hit that problem. You can look at the call stack and figure out which function has the problem and then look at its definition and the declaration that the caller uses.
I saw this error when the code tried to call a function on an object that was not of the expected type.
So, class hierarchy: Parent with children: Child1 and Child2
Child1* pMyChild = 0;
...
pMyChild = pSomeClass->GetTheObj();// This call actually returned a Child2 object
pMyChild->SomeFunction(); // "...value of ESP..." error occurs here
I was getting similar error for AutoIt APIs which i was calling from VC++ program.
typedef long (*AU3_RunFn)(LPCWSTR, LPCWSTR);
However, when I changed the declaration which includes WINAPI, as suggested earlier in the thread, problem vanished.
Code without any error looks like:
typedef long (WINAPI *AU3_RunFn)(LPCWSTR, LPCWSTR);
AU3_RunFn _AU3_RunFn;
HINSTANCE hInstLibrary = LoadLibrary("AutoItX3.dll");
if (hInstLibrary)
{
_AU3_RunFn = (AU3_RunFn)GetProcAddress(hInstLibrary, "AU3_WinActivate");
if (_AU3_RunFn)
_AU3_RunFn(L"Untitled - Notepad",L"");
FreeLibrary(hInstLibrary);
}
It's worth pointing out that this can also be a Visual Studio bug.
I got this issue on VS2017, Win10 x64. At first it made sense, since I was doing weird things casting this to a derived type and wrapping it in a lambda. However, I reverted the code to a previous commit and still got the error, even though it wasn't there before.
I tried restarting and then rebuilding the project, and then the error went away.
I was getting this error calling a function in a DLL which was compiled with a pre-2005 version of Visual C++ from a newer version of VC (2008).
The function had this signature:
LONG WINAPI myFunc( time_t, SYSTEMTIME*, BOOL* );
The problem was that time_t's size is 32 bits in pre-2005 version, but 64 bits since VS2005 (is defined as _time64_t). The call of the function expects a 32 bit variable but gets a 64 bit variable when called from VC >= 2005. As parameters of functions are passed via the stack when using WINAPI calling convention, this corrupts the stack and generates the above mentioned error message ("Run-Time Check Failure #0 ...").
To fix this, it is possible to
#define _USE_32BIT_TIME_T
before including the header file of the DLL or -- better -- change the signature of the function in the header file depending on the VS version (pre-2005 versions don't know _time32_t!):
#if _MSC_VER >= 1400
LONG WINAPI myFunc( _time32_t, SYSTEMTIME*, BOOL* );
#else
LONG WINAPI myFunc( time_t, SYSTEMTIME*, BOOL* );
#endif
Note that you need to use _time32_t instead of time_t in the calling program, of course.
I was having this exact same error after moving functions to a dll and dynamically loading the dll with LoadLibrary and GetProcAddress. I had declared extern "C" for the function in the dll because of the decoration. So that changed calling convention to __cdecl as well. I was declaring function pointers to be __stdcall in the loading code. Once I changed the function pointer from __stdcall to__cdecl in the loading code the runtime error went away.
Are you creating static libs or DLLs? If DLLs, how are the exports defined; how are the import libraries created?
Are the prototypes for the functions in the libs exactly the same as the function declarations where the functions are defined?
do you have any typedef'd function prototypes (eg int (*fn)(int a, int b) )
if you dom you might be have gotten the prototype wrong.
ESP is an error on the calling of a function (can you tell which one in the debugger?) that has a mismatch in the parameters - ie the stack has restored back to the state it started in when you called the function.
You can also get this if you're loading C++ functions that need to be declared extern C - C uses cdecl, C++ uses stdcall calling convention by default (IIRC). Put some extern C wrappers around the imported function prototypes and you may fix it.
If you can run it in the debugger, you'll see the function immediatey. If not, you can set DrWtsn32 to create a minidump that you can load into windbg to see the callstack at the time of the error (you'll need symbols or a mapfile to see the function names though).
Another case where esp can get messed up is with an inadvertent buffer overflow, usually through mistaken use of pointers to work past the boundary of an array. Say you have some C function that looks like
int a, b[2];
Writing to b[3] will probably change a, and anywhere past that is likely to hose the saved esp on the stack.
You would get this error if the function is invoked with a calling convention other than the one it is compiled to.
Visual Studio uses a default calling convention setting thats decalred in the project's options. Check if this value is the same in the orignal project settings and in the new libraries. An over ambitious dev could have set this to _stdcall/pascal in the original since it reduces the code size compared to the default cdecl. So the base process would be using this setting and the new libraries get the default cdecl which causes the problem
Since you have said that you do not use any special calling conventions this seems to be a good probability.
Also do a diff on the headers to see if the declarations / files that the process sees are the same ones that the libraries are compiled with .
ps : Making the warning go away is BAAAD. the underlying error still persists.
This happened to me when accessing a COM object (Visual Studio 2010). I passed the GUID for another interface A for in my call to QueryInterface, but then I cast the retrieved pointer as interface B. This resulted in making a function call to one with an entirely signature, which accounts for the stack (and ESP) being messed up.
Passing the GUID for interface B fixed the problem.
In my MFC C++ app I am experiencing the same problem as reported in Weird MSC 8.0 error: “The value of ESP was not properly saved across a function call…”. The posting has over 42K views and 16 answers/comments none of which blamed the compiler as the problem. At least in my case I can show that the VS2015 compiler is at fault.
My dev and test setup is the following: I have 3 PCs all of which run Win10 version 10.0.10586. All are compiling with VS2015, but here is the difference. Two of the VS2015s have Update 2 while the other has Update 3 applied. The PC with Update 3 works, but the other two with Update 2 fail with the same error as reported in the posting above. My MFC C++ app code is exactly the same on all three PCs.
Conclusion: at least in my case for my app the compiler version (Update 2) contained a bug that broke my code. My app makes heavy use of std::packaged_task so I expect the problem was in that fairly new compiler code.
ESP is the stack pointer. So according to the compiler, your stack pointer is getting messed up. It is hard to say how (or if) this could be happening without seeing some code.
What is the smallest code segment you can get to reproduce this?
If you're using any callback functions with the Windows API, they must be declared using CALLBACK and/or WINAPI. That will apply appropriate decorations to make the compiler generate code that cleans the stack correctly. For example, on Microsoft's compiler it adds __stdcall.
Windows has always used the __stdcall convention as it leads to (slightly) smaller code, with the cleanup happening in the called function rather than at every call site. It's not compatible with varargs functions, though (because only the caller knows how many arguments they pushed).
Here's a stripped down C++ program that produces that error. Compiled using (Microsoft Visual Studio 2003) produces the above mentioned error.
#include "stdafx.h"
char* blah(char *a){
char p[1];
strcat(p, a);
return (char*)p;
}
int main(){
std::cout << blah("a");
std::cin.get();
}
ERROR:
"Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention."
I had this same problem here at work. I was updating some very old code that was calling a FARPROC function pointer. If you don't know, FARPROC's are function pointers with ZERO type safety. It's the C equivalent of a typdef'd function pointer, without the compiler type checking.
So for instance, say you have a function that takes 3 parameters. You point a FARPROC to it, and then call it with 4 parameters instead of 3. The extra parameter pushed extra garbage onto the stack, and when it pops off, ESP is now different than when it started. So I solved it by removing the extra parameter to the invocation of the FARPROC function call.
Not the best answer but I just recompiled my code from scratch (rebuild in VS) and then the problem went away.

Modifying decorated names - VS6.0 to VS2005 migration

After a number of hours Googling, I think it's time to ask the experts. We have a legacy module (MS Visual C++ 6.0) that we are trying to port to VS 2005. A number of calling applications exist, so we're trying, if possible, to keep these backward-compatible.
Code-wise, this turned out pretty straightforward and a few hours of development eliminated all compiler errors and most warnings.
Then I came up against a few "unresolved external symbol" errors in the linking step, which seem to be subtle differences in the decorated name.
It turns out that one set of errors was related to time_t being a 64-bit structure in VS2005 -- defining _USE_32BIT_TIME_T fixed those three.
Now I am stuck with two remaining errors:
The function is defined as
int RC_STATE::my_function(UINT stateId, UINT period, UINT index, UINT paramtype, UINT dpindex, UINT managerId, UINT calctype, UINT status, double *p_val, long *p_isc, CTime *p_time)
It appears that under "old" Visual Studio, it was happy with the decorated name
?my_function#RC_STATE##QAEHIIIIIIIIPANPAJPAVCTime###Z
But now, VS2005 wants to include the ATL namespace for the "CTime" parameter:
?my_function#RC_STATE##QAEHIIIIIIIIPANPAJPAVCTime#ATL###Z
If I update my .DEF file with this new decorated name, it compiles & links... yay! Except as soon as I plop that DLL down with some code that used to work, it complains that it can't find the procedure entry point in the DLL (i.e. the one with the "old" structure, no namespace).
Any suggestions? Is there some sort of keyword, compiler directive that would allow me to tell the compiler not to put the namespace in the decorated name (I know that namespaces are good, but there is no conflict afaik with the CTime type that would need the namespace to resolve the conflict).
Are there any workarounds to get the decorated name to match the old format?
Many thanks in advance to any suggestions.
There are actually two problems here. First, CTime is now in the ATL namespace, as you've found, but also CTime in VS2005 uses __time64_t internally, which is 64 bits, not 32 bits, and that isn't changed by defining _USE_32BIT_TIME_T.
So, even if you were to fix the namespace problem, if your application is compiled with VC6 and the DLL is compiled with VS2005 (or vice versa), passing CTime objects between these modules would almost certainly lead to data corruption problems due to the difference in memory layout.
In my view, the solution is to recompile all your code with VS2005, and use the 64-bit time_t throughout, consistent with CTime in VS2005 (i.e, don't use _USE_32BIT_TIME_T).
I hope this helps!
Another possibility would be to copy the old definition of CTime into your VS2005 project and use it on the parameter list of the function where you're trying to keep compatibility. Then convert between your back-compatible CTime parameter into the new ATL::CTime before processing. Old VC6 clients can call your back-compatible method.