1

I have a strange problem with a very basic task (I just want to print something in the console).
So I have a c++ program which runs an asm function, and this asm function should just print some text and return 3 to c++.
I tried to print the text in many different methods, one of them is the code from this link. C++ runs assembler code which correctly prints text but when it goes to ret it crashed with the following error:

Exception 0xc0000005 encountered at address 0x7ff654f01000: User-mode data execution prevention (DEP) violation at location 0x7ff654f01000

This is my actual code (with different printing method then the one from the link):

; asmTest.asm
[bits 64]       ; allow 64-bit register names

default rel
section .data
    msg db "Asm started", 0xd, 0xa, 0

section .text
    global _firstWatchdog
    extern printf

_firstWatchdog:
    lea rcx, [msg]
    call printf
    mov rax, 3
    ret
//main.h
#include <iostream>
#include <thread>
#include <stdio.h>
namespace testCore{
    extern "C"{
        int _firstWatchdog();
    }
}
//main.cpp
#include "main.h"
[[noreturn]] void asmTest(){
    std::cout << "asm thread started" << std::endl;
    while (true) {
        int tmp_func_val = testCore::_firstWatchdog();
    }
}

[[noreturn]]int main ()
{
    std::thread asm_test;
    asm_test = std::thread(asmTest);
    asm_test.detach();
    while (true){
        std::cout << "Do some stuff here" << std::endl;
    }
}
Sep Roland
  • 33,889
  • 7
  • 43
  • 76
Xmno
  • 11
  • 2
  • 3
    64 bit calling convention requires shadow space and stack alignment. Insert `sub rsp, 40` as first instruction of `_firstWatchdog` and `add rsp, 40` as last before `ret`. Report back if that fixed anything. PS: you don't need `mov rax, 3` you can use `mov eax, 3`. – Jester Jan 13 '21 at 23:19
  • Also note that printing from two threads simultaneously might not be supported. First test your asm function from the main thread to see if threading is an issue. – Jester Jan 13 '21 at 23:23
  • WOW you are amazing that's work. Where can i read more about it, and more stuff like this (for future)? – Xmno Jan 13 '21 at 23:37
  • 1
    [Microsoft documentation of calling convention](https://learn.microsoft.com/en-us/cpp/build/x64-calling-convention) – Jester Jan 13 '21 at 23:45
  • 1
    This answer ([How to write hello world in assembler under Windows?](https://stackoverflow.com/a/1032422)) has a decent example. – Peter Cordes Jan 14 '21 at 10:05

0 Answers0