Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is RtlFillMemory/RtlCopyMemory defined as macro [closed]

From definition (winnt.h):

#define RtlCopyMemory(Destination,Source,Length) memcpy((Destination),(Source),(Length))
#define RtlFillMemory(Destination,Length,Fill) memset((Destination),(Fill),(Length))

we see this functions are actually macros, which calls memset/memcpy functions.

Questions is why?

Originaly this functions are exported by kernel32.dll (but only as stub to ntdll.dll), so what is the reason use them as CRT functions?

like image 932
Xearinox Avatar asked Dec 21 '22 07:12

Xearinox


1 Answers

The Windows api is implemented using layers. There's the well-documented winapi on top, the one that every Windows program should use to make operating system calls. Microsoft can never change it, doing so would break a lot of legacy programs. The one on the bottom is the native operating system api, functions whose name start with Nt or Zw. Undocumented beyond the ones that are required to write a driver. Microsoft changes it regularly with each Windows release, the basic way it can innovate on Windows without breaking too much code. Vista was the last version of Windows with really drastic changes in that bottom layer, the complaints that generated have been well published.

And there's a layer in between, the helper functions that translate from the published api to the undocumented one and back. Its names start with Rtl.

They were also meant to be undocumented, but programmers have reverse-engineered them and ended up taking a dependency on them. Some have been documented by Microsoft because they were generally useful for debugging or filled a gap in the winapi. That's painful for Microsoft, inevitably when the bottom layer changes, those Rtl functions need to change as well. RtlCopyMemory and RtlFillMemory have been particularly abused, lots of VB6 code used it because it didn't have a published function that did the same thing.

Well, that cat is out of the bag. So the declarations you found are an attempt by Microsoft to get programs to use a documented function and stop relying on functions that may need to change. The only reasonable thing it could do to address the problem.

like image 110
Hans Passant Avatar answered Feb 01 '23 23:02

Hans Passant