How to put assembly markers to C++ code (x64) - visual-c++

I need to put markers to C++ code that should be visible in assembly or binary. It seems it’s straight forward to do it for 32 using inline assembly:
__asm {
NOP
NOP
NOP
}
or using DB assembly statement:
__asm {
DB 0x00, 0xFF, 0x10
}
But VisualStudio 2005 and better does not support inline assembly for x64. Is there any way to do it? Probably I can make a function in separate assembly module but how I can be sure that linker will put an actual assembly there instead of CALL?

Define a global volatile variable somewhere, say volatile __int64 blah = 0;. Then wherever you want some marker, use _InterlockedCompareExchange64(&blah, SOME_UNIQUE_CONSTANT1, SOME_UNIQUE_CONSTANT2);. You'll be guaranteed to find instructions loading ECX:EBX with SOME_UNIQUE_CONSTANT1 and EDX:EAX with SOME_UNIQUE_CONSTANT2 followed by LOCK CMPXCHG8B (0xF0, 0x0F, 0xC7, etc -- see instruction encoding details).

The MSDN says you can use intrinsic functions.

//MyAsmCode.asm
.code
MyFunction proc
...
MyFunction endp
end
compile it (ml64.exe).
You get object file (MS COFF 64): MyAsmCode.obj
In VS add MyAsmCode.obj to linker additional dep.
Now you can call this function. ;)

Related

Does WINE implement "_printf" and similar functions in MSVCRT?

Here is an example program that illustrates my problem, it can be compiled using FlatAssembler without using a linker:
format PE console
entry start
include 'win32a.inc'
section '.text' code executable
start:
mov dword [esp],_output1
call [printf]
mov dword [esp+4],first
mov dword [esp],_input
call [scanf]
mov dword [esp],_output2
call [printf]
mov dword [esp+4],second
mov dword [esp],_input
call [scanf]
finit
fld dword [first]
fabs
fld dword [second]
fxch
fld1
fxch
fyl2x
fldl2e
fdivp st1,st0
fmulp st1,st0
fldl2e
fmulp st1,st0
fld1
fscale
fxch
fld1
fxch
fprem
f2xm1
faddp st1,st0
fmulp st1,st0
fstp dword [result]
fld dword [result]
fst qword [esp+4]
mov dword [esp],_output
call [printf]
invoke system,_pause
invoke exit,0
_output1 db "Enter the first number: ",0
_output2 db "Enter the second number: ",0
_input db "%f",0
_pause db "PAUSE",0
_output db "The first number to the power of the second number is: %f.",10,0
section '.rdata' readable writable
result dd ?
first dd ?
second dd ?
section '.idata' data readable import
library msvcrt,'msvcrt.dll'
import msvcrt,printf,'printf',system,'system',exit,'exit',scanf,'scanf'
So, the expected output is, of course, something like this:
Enter the first number: -2.5
Enter the second number: -2
The first number to the power of the second number is: 0.16
And that's the output I indeed get if I run that program on Windows 10. However, if I try to run that program on WINE on Oracle Linux, the output I get is:
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"MountMgr" failed to start: 2
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"WineBus" failed to start: 2
wine: Bad EXE format for Z:\home\teo.samarzija\Documents\Assembly\debug.exe.
Any idea what's going on?
I've done a little research, and I can't find any reference confirming that _printf and _scanf are even implemented in WINE's MSVCRT. However, I am not sure that's the problem, and, if it is a problem, that that's the only problem.
However, if I try to run that program on WINE on Oracle Linux, the
output I get is:
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"MountMgr" failed to start: 2
000f:fixme:service:scmdatabase_autostart_services Auto-start service L"WineBus" failed to start: 2
wine: Bad EXE format for Z:\home\teo.samarzija\Documents\Assembly\debug.exe.
A "Bad EXE format" error is something different entirely. It doesn't imply that the problem is a missing imported function. The loader never got that far. It wasn't even able to read your binary. This is very likely caused by a bitness mismatch. For example, trying to run a 64-bit application on a 32-bit system.
Aside from this problem, it is worth pointing out that your attempted use of C runtime library functions is inherently non-portable. It might work, if Wine (or whatever other runtime environment) provides a function with an identical signature, but it very likely won't.
I suppose I should further clarify, since calling a standard C runtime library function "non-portable" may raise a few eyebrows. These functions are portable at the source-code level, but not at the binary level. Even without the added complexity of Wine, the C runtime library functions are non-portable, as Microsoft's CRT is versioned—you have to link to the appropriate version and have that DLL available at runtime, or your application will not work.
This exact problem is why Windows provides wrappers for these standard functions as part of the basic platform API, which is universally available. If you want to be fully portable to all implementations of the Win32 environment, and you aren't linking in your own copy of the C runtime library, then you should call these functions instead.
The Win32 version of the sprintf function is wsprintf. It has the same interface as sprintf, so you can call it the same way, as a drop-in replacement. In fact, although you shouldn't rely on this, it is implemented by Windows as a simple wrapper around the sprintf version provided by the local copy of the C runtime libraries.
If you want a version to which you can pass an argument list (a la vsprintf), then you can call wvsprintf.
Note that, unlike most of the Windows API functions, these functions use the __cdecl calling convention, not the __stdcall calling convention. Make sure that you are adhering to that in your assembly code. In short, that means passing arguments from right-to-left and cleaning up the stack at the call site.
Microsoft has, however, deprecated these functions, as they aren't entirely safe (buffer overflows and etc. are possible). As replacements, they offer the functions in the StrSafe.h header. These functions come in two variants: those which take a count of bytes (Cb) and those which take a count of characters (Cch). The relevant ones to this discussion would be either StringCbPrintfA or StringCchPrintfA. These are trickier to use from assembly language, however, because they're meant to be used inline by simply including the StrSafe.h header file. You can use them in library form, but then you'll need to pass the corresponding StrSafe.lib stubs to the linker. Note that linking to this library means your application will only run on Windows XP with SP2 or later.
This gets you halfway there. You are actually trying to call printf, rather than sprintf. The gap, of course, is getting the formatted string written to the console. Once you have the formatted string (generated by wsprintf, StringCchPrintfA, or whatever), that can be accomplished by calling the WriteConsole function, which is the Win32 API for writing output to the console window. If you want STDOUT, then you need to open that handle first with GetStdHandle(STD_OUTPUT_HANDLE).
Anyway, I got the answer:
https://www.linuxquestions.org/questions/linux-general-1/can%27t-install-wine-on-64-bit-oracle-linux-4175655895/page2.html#post6012838
In short, on 64-bit Oracle Linux, WINE needs to be compiled from source to work properly.

what's the meaning of ENTRY statement in entry.S in Linux kernel for i386

for example in entry.S
ENTRY(ret_from_fork)
pushl %eax
call schedule_tail
GET_THREAD_INFO(%ebp)
popl %eax
jmp syscall_exit
so what's the syntax of ENTRY in as language?
I think all the directive of as is start with . and the ENTRY also doesn't look like a macro
can anyone tell me about the ENTRY is what? if it is defined in Linux source code could anyone indicate the location or if it is a syntax in as can someone tell me where i can find the specific description of this use!
Thanks!
Not sure why you say it doesn't look like a macro, because that's exactly how macros look like. And indeed it is a macro defined in include/linux/linkage.h as follows:
#ifndef ENTRY
#define ENTRY(name) \
.globl name ASM_NL \
ALIGN ASM_NL \
name:
#endif
I think that's an assembler directive .
As per my knowledge ENTRY assembler directive is used when we use Keil assembler.
That's actually the entry point of a application.
The way we have _start or _main entry point in assembly code when we use GNU assembler.

Call asm from c++

I want to call define a function in asm file and call this function from a Cpp file/function. Also I have to compile the project on 64-bit platform.
Please help me in doing that as I don't have much idea about assembly code. Any help will be appreciated.
Thanks
This file is an ASM file from ffdshow that performs some work with CPUID. It's both x64 and x86. YASM is used to assemble it.
What most people do today is not write ASM code but use intrinsic functions. There are intrinsic functions for all SSE/AVX/etc. even for low level ring0 instructions. Intrinsic functions allow the compiler to do extra optimizations and are shared between 32 and 64bit builds.
A code snippet would help, but if you want to place inline assembly within a regular C++ function, you can do that by placing it in an asm block like this:
void myClass::myFunc() {
// cpp code
int a = 0;
// ...
// asm code
__asm {
mov eax, ebx;
// ...
};
// more cpp code
// ...
}

How to change the entry point of gcc generated asm code?

This experiment is on the 32 bit Linux.
I want to do a transformation on the asm level, and I am trying to implement
my transformation before the function main is called.
Currently I am trying to program a new entry point, implement my transformation code,
and hope this new entry point can successfully call main
Basically the default entry point of gcc generated assembly code is main, which I give an example as follow:
c code:
int main()
{
return 0;
}
I use this command to generate asm code:
gcc -masm=intel -fno-asynchronous-unwind-tables -S main.c
and this is what I got:
.file "main.c"
.intel_syntax noprefix
.text
.globl main
.type main, #function
main:
push ebp
mov ebp, esp
mov eax, 0
pop ebp
ret
.size main, .-main
.ident "GCC: (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3"
.section .note.GNU-stack,"",#progbits
Could anyone tell me how to implement a new entry point(probably a function similiar like _start) and call main at the end of this new entry point?
Thank you!
I doubt you should replace _start() because it's very platform- and libc-specific. Either you write all code in assembler and so you don't need libc-specific initialization, or you should copy all _start() activity including things you aren't aware. The latter looks simply bogus.
If you agree not to replace start() but use a mechanism to run some code before main(), declare a function with __attribute__((constructor)). This is documented GCC extension and it's actively used e.g. for static object initializing in C++. Such function can't get arguments or return a real value, nor shall it override control flow in another way. I can't catch what you mean for "transformation" so it can contradict to your intention; if so, you would have explained this more detailedly.

ASM to push function arguments to the stack

I'm trying to port a program to x64 using vs2008. The problem is, however, that the is some inline asm code that is not supported on x64. This asm code is used to push arguments with unknown type or number to functions from dll. It is an interpeter based program in which you can specify a function to use from a certain dll and the program pushes the arguments and calles the function at compile time.
Using various sources I've concluded that generating seperate .asm files that contain asm functions which can be compiled unsing masm and their obj files linked to vs2008. Using different files for x86 and x64 the program builds for both problems. The problem is however, that the functions do not replicate what the inline asm is doing.
I converted the following inline code, for example:
double a = Evaluate(arg[i]).num;
_asm push a + 4
_asm push a
j += 8;
To:
double a = Evaluate(arg[i]).num;
EvaluateFuncArgFloat(a);
j += 8;
With the follwoing .asm file:
TITLE EvaluateFuncArgFloat (evaluate_asm.asm)
.386
.model flat, C
.code
EvaluateFuncArgFloat PROC a:DWORD
push a + 4
push a
ret
EvaluateFuncArgFloat ENDP
END
This does not do what I'm expecting. The double simply does not end up in the function as it did when using inline asm.
My guess is that there is a small error or something I've left out, but after many tries I can't seem to get it to work. Hopefully someone can help me with this problem, it is very much appriciated.
A sneaky way to do this could be
EvaluateFuncArgFloat PROC a:DWORD
pop eax ;ret address popped to a safe register (if not ax/eax)
push a + 4
push a
push eax ;ret address back at top of stack
ret
EvaluateFuncArgFloat ENDP
The problem is you've pushed 2 numbers onto the stack and not removed them a+4 and a
Presumably another part of your original code deals with this in the original program

Resources