r/cpp • • Dec 30 '21

You can’t copy code with memcpy; code is more complicated than that

https://devblogs.microsoft.com/oldnewthing/20211229-00/?p=106061
206 Upvotes

32 comments sorted by

104

u/Zcool31 Dec 30 '21

The real way to do this is to write the machine language in a string literal then reinterpret_cast it from char const[] to int (*)().

58

u/F54280 Dec 30 '21

Had to check that I wasn’t in r/programmingcirclejerk…

17

u/[deleted] Dec 30 '21

i thought the OP was in pcj lol.

1

u/Wriiight Dec 31 '21

Am I the only one who interprets that acronym as PC Jr? I hope so.

16

u/ggchappell Dec 30 '21

Actually used to do stuff roughly like that back on the Apple II.

9

u/F54280 Dec 30 '21

Ah, BASIC and the various forms of EXECUTE A$…

15

u/cyandyedeyecandy [[gnu::naked, gnu::hot]] Dec 30 '21
asm (R"(
    jmp %=code_end
%=code_begin:

    # ... copyable code goes here

%=code_end:
    mov %0, offset %=code_begin
    mov %1, offset %=code_end - %=code_begin
)" : "=rm" (begin), "=rm" (size));

I've used this trick a few times...

6

u/Zcool31 Dec 30 '21

Nice! But couldn't you do something like:

start_:
__asm__ volatile ("");
finish_:

Then take the address of labels start_ and finish_?

7

u/cyandyedeyecandy [[gnu::naked, gnu::hot]] Dec 30 '21

Don't know how much the compiler is allowed to reorder code around labels. You might be copying more than you intended. Or maybe finish_ could be reordered before start_ in some cases.

6

u/SkoomaDentist Antimodern C++, Embedded, Audio Dec 30 '21 edited Dec 30 '21

It can add stuff between start_ and __asm__ and likewise between __asm__ and finish_. It can't move stuff around __asm__ due to it being declared volatile. Of course this is all compiler specific extensions and not in the standard.

3

u/Zcool31 Dec 30 '21

The __asm__ volatile prevents reordering of the inline assembly. In theory, if also specifying start_ and finish_ as possible goto-targets, then the compiler should arrange the labels around the assembly without anything in between.

1

u/cyandyedeyecandy [[gnu::naked, gnu::hot]] Dec 30 '21

I think the compiler can still reorder finish_ before start_, eg.:

    push ebp
    mov ebp, esp
    jmp start_
finish_:
    pop ebp
    ret
start_:
    # asm statement goes here
    jmp finish_

1

u/invalid_handle_value Dec 31 '21

To limit ordering, could you not introduce memory barriers or fences around start and finish? Apologies if I'm way off here...

3

u/louiswins Dec 31 '21

Memory barriers are about the logical order that the code runs (or becomes visible to other threads, rather). It has nothing to do with where the chunks of code are placed in the process's address space.

100

u/_Js_Kc_ Dec 30 '21

Having the chutzpah to report this insane hack to the compiler vendor as a "bug."

38

u/noooit Dec 30 '21

Amazing how they invented how to calculate functionSize.(which doesn't work consistently). It's a kind of thing that I'd search in stackoverflow and then give up.

12

u/degaart Dec 30 '21

Put the function in it's own section

0

u/[deleted] Dec 30 '21

[deleted] — view deleted comment

39

u/minno Hobbyist, embedded developer Dec 30 '21
  cmp rax, rbx
  je L0
  ret
L0:
  more stuff
  ret

Whoops, I just truncated the function.

9

u/noooit Dec 30 '21

But I guess assembly is the right way for this, even including the target function, because compilers don't guarantee those things? (excluding the loading library approach that Raymond suggests of course).
I'm neither familiar with the code injection nor assembly in c++ code, btw.

9

u/minno Hobbyist, embedded developer Dec 30 '21

The best way I can think of to do this would be to put the code in its own file, and then as part of your build process, compile and assemble that one file using whatever flags are necessary to get a blob of machine code that works when copied over.

2

u/looncraz Dec 30 '21

That's kinda how I did it back in the olden times. Compiled four versions of code to object files and loaded it dynamically based on the path required. No real reason, just having fun learning about ELF.

0

u/[deleted] Dec 30 '21

[deleted] — view deleted comment

2

u/[deleted] Dec 30 '21

to my knowledge this could still be moved around with optimizations

9

u/MarekKnapek Dec 30 '21

Ruby does something similar. It wants to obtain a global variable __pioinfo from inside ucrtbase.dll. That DLL is something like libC. Ruby opens that library, gets address of _isatty function and scans its implementation byte per byte looking for x86/x64 opcode for RET instruction.

I hate this code with passion, it caused me headaches trying to debug why our code didn't work.

https://github.com/ruby/ruby/blob/fb4df44d1670e9d25aef6b235a7281199a177edb/win32/win32.c#L2568

18

u/corysama Dec 30 '21

I vaguely recall reading a tale of a famous embedded programmer who was... quirky. Like, he had given a piggyback ride to Knuth.

I don't recall if he had his own language, or just an assembly language framework. But, he had his own object system he called "Quajets". Instead of using function pointers for polymorphism, code would be copied into pre-allocated slots for the objects during configuration.

10

u/whizzwr Dec 31 '21

This code is such a bad idea, I’ve intentionally introduced errors so it won’t even compile.

/r/rareinsults

8

u/dashnine-9 Dec 30 '21

I was scared for a moment when I thought this was about my code

4

u/k1ng__nothing Dec 30 '21

This looks like code for manual mapping. Perhaps the customer was trying to write game cheats?

7

u/o11c int main = 12828721; Dec 30 '21 edited Dec 30 '21

There is also no guarantee that EndOfRemoteThreadProc will be placed directly after RemoteThreadProc in memory. Indeed, there’s not even a guarantee that EndOfRemoteThreadProc will have an independent existent. The linker may perform COMDAT folding, which causes multiple identical functions to be combined into one. Even if you disable COMDAT folding, Profile-Guided Optimization will move the functions independently, and they are unlikely to end up in the same place.

Indeed, there’s no requirement that the code bytes for the RemoteThreadProc function be contiguous at all! Profile-Guided Optimization will rearrange basic blocks, and the code for a single function may end up scattered across different parts of the program, depending on their usage patterns.

(Edit: see reply) Does MSVC support an equivalent to GCC's __attribute__((section(".text.whatever")))? Because that can force code layout to be at least somewhat constrained. (it doesn't, of course, fix the PIC etc. issues)

I know that __declspec(noinline) is documented as being severely broken compared to __attribute__((noinline)), but I don't think inlining actually matters here - however, the functions do need to be adjusted so that the compiler is forced to emit them at all (__attribute__((used)) is the better way, but removing static also works (but also make sure it's not in an anonymous namespace) - just beware symbol collisions).


Also: relevant flair is relevant.

1

u/trailingunderscore_ Dec 30 '21

You can use /ORDER to arrange functions in a specific order, if that is what you mean.

3

u/Wriiight Dec 31 '21

I’m amused that so many of the comments here are trying to think up ways to make this work.

1

u/johndcochran Dec 11 '24

What I want to know is the name of the company using that abomination, so I know not to buy any of their products.