Execute Instructions From The Heap2019 Community Moderator ElectionHow can I copy and run a functions in CIs it possible to execute a machine code stored in a variable?How to execute code from heapWhat are the differences between a pointer variable and a reference variable in C++?How to allocate aligned memory only using the standard library?What REALLY happens when you don't free after malloc?Does delete call the destructor?Improve INSERT-per-second performance of SQLite?Why should C++ programmers minimize use of 'new'?How do I achieve the theoretical maximum of 4 FLOPs per cycle?Why are elementwise additions much faster in separate loops than in a combined loop?Why is reading lines from stdin much slower in C++ than Python?Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

Computing the volume of a simplex-like object with constraints

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

Replacing tantalum capacitor with ceramic capacitor for Op Amps

Problems with rounding giving too many digits

Can you run a ground wire from stove directly to ground pole in the ground

Can a Mexican citizen living in US under DACA drive to Canada?

Do natural melee weapons (from racial traits) trigger Improved Divine Smite?

Gemara word for QED

Did Amazon pay $0 in taxes last year?

Why is there an extra space when I type "ls" on the Desktop?

Convert an array of objects to array of the objects' values

Practical reasons to have both a large police force and bounty hunting network?

Deal the cards to the players

School performs periodic password audits. Is my password compromised?

Is there a way to find out the age of climbing ropes?

Can a space-faring robot still function over a billion years?

Called into a meeting and told we are being made redundant (laid off) and "not to share outside". Can I tell my partner?

What does "rhumatis" mean?

Create chunks from an array

Has a sovereign Communist government ever run, and conceded loss, on a fair election?

Was it really inappropriate to write a pull request for the company I interviewed with?

What's the best tool for cutting holes into duct work?

If nine coins are tossed, what is the probability that the number of heads is even?

How spaceships determine each other's mass in space?



Execute Instructions From The Heap



2019 Community Moderator ElectionHow can I copy and run a functions in CIs it possible to execute a machine code stored in a variable?How to execute code from heapWhat are the differences between a pointer variable and a reference variable in C++?How to allocate aligned memory only using the standard library?What REALLY happens when you don't free after malloc?Does delete call the destructor?Improve INSERT-per-second performance of SQLite?Why should C++ programmers minimize use of 'new'?How do I achieve the theoretical maximum of 4 FLOPs per cycle?Why are elementwise additions much faster in separate loops than in a combined loop?Why is reading lines from stdin much slower in C++ than Python?Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition










3















Can I allocate a block on the heap, set its bytes to values that correspond to a function call and its parameters, then use the function call and dereference operators to execute that sequence?










share|improve this question






















  • This is what a compiler does all the time - what makes you think that you would not be able to do it?

    – Floris
    Nov 27 '13 at 3:25











  • this is possible in Von Neumann arch but not Harvard arch, generally.

    – Grady Player
    Nov 27 '13 at 3:44











  • the Harvard architecture is exceptionally rare - although this is exactly the level where you might encounter it. the vast majority of computers, phones, game consoles etc. use Von Neumann... at least conceptually, regardless as to caches, ROMs or etc.

    – jheriko
    Nov 27 '13 at 12:38
















3















Can I allocate a block on the heap, set its bytes to values that correspond to a function call and its parameters, then use the function call and dereference operators to execute that sequence?










share|improve this question






















  • This is what a compiler does all the time - what makes you think that you would not be able to do it?

    – Floris
    Nov 27 '13 at 3:25











  • this is possible in Von Neumann arch but not Harvard arch, generally.

    – Grady Player
    Nov 27 '13 at 3:44











  • the Harvard architecture is exceptionally rare - although this is exactly the level where you might encounter it. the vast majority of computers, phones, game consoles etc. use Von Neumann... at least conceptually, regardless as to caches, ROMs or etc.

    – jheriko
    Nov 27 '13 at 12:38














3












3








3


1






Can I allocate a block on the heap, set its bytes to values that correspond to a function call and its parameters, then use the function call and dereference operators to execute that sequence?










share|improve this question














Can I allocate a block on the heap, set its bytes to values that correspond to a function call and its parameters, then use the function call and dereference operators to execute that sequence?







c++ c






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 27 '13 at 3:22









DavidDavid

353115




353115












  • This is what a compiler does all the time - what makes you think that you would not be able to do it?

    – Floris
    Nov 27 '13 at 3:25











  • this is possible in Von Neumann arch but not Harvard arch, generally.

    – Grady Player
    Nov 27 '13 at 3:44











  • the Harvard architecture is exceptionally rare - although this is exactly the level where you might encounter it. the vast majority of computers, phones, game consoles etc. use Von Neumann... at least conceptually, regardless as to caches, ROMs or etc.

    – jheriko
    Nov 27 '13 at 12:38


















  • This is what a compiler does all the time - what makes you think that you would not be able to do it?

    – Floris
    Nov 27 '13 at 3:25











  • this is possible in Von Neumann arch but not Harvard arch, generally.

    – Grady Player
    Nov 27 '13 at 3:44











  • the Harvard architecture is exceptionally rare - although this is exactly the level where you might encounter it. the vast majority of computers, phones, game consoles etc. use Von Neumann... at least conceptually, regardless as to caches, ROMs or etc.

    – jheriko
    Nov 27 '13 at 12:38

















This is what a compiler does all the time - what makes you think that you would not be able to do it?

– Floris
Nov 27 '13 at 3:25





This is what a compiler does all the time - what makes you think that you would not be able to do it?

– Floris
Nov 27 '13 at 3:25













this is possible in Von Neumann arch but not Harvard arch, generally.

– Grady Player
Nov 27 '13 at 3:44





this is possible in Von Neumann arch but not Harvard arch, generally.

– Grady Player
Nov 27 '13 at 3:44













the Harvard architecture is exceptionally rare - although this is exactly the level where you might encounter it. the vast majority of computers, phones, game consoles etc. use Von Neumann... at least conceptually, regardless as to caches, ROMs or etc.

– jheriko
Nov 27 '13 at 12:38






the Harvard architecture is exceptionally rare - although this is exactly the level where you might encounter it. the vast majority of computers, phones, game consoles etc. use Von Neumann... at least conceptually, regardless as to caches, ROMs or etc.

– jheriko
Nov 27 '13 at 12:38













4 Answers
4






active

oldest

votes


















4














So if I read you right you want to dynamically create CPU assembly instructions on the heap and execute them. A bit like self-modifying code. In theory that's possible, but in practice maybe not.



The problem is that the heap is in a data segment, and CPU's/operating systems nowadays have measures to prevent exactly this kind of behavior (it's called the NX bit, or No-eXecute bit for x86 CPUs). If a segement is marked as NX, you can't execute code from it. This was invented to stop computer virusses from using buffer overflows to place exectuable code in data/heap/stack memory and then try the calling program to execute such code.



Note that DLL's and libraries are loaded in the code segment, which of course allows code execution.






share|improve this answer


















  • 1





    You understand what I am getting at.

    – David
    Nov 27 '13 at 4:01











  • This answer is a little confused. The heap lives in the data segment? The segments in a PE file are simply not used this way. The heap does not live in a data segment... more generally the 'code segment' will be loaded into executable memory and most OSs provide a mechanism to allocate such memory - although it might be hidden and buried it must exist.

    – jheriko
    Nov 27 '13 at 12:35







  • 2





    You have to make a distinction between how the CPU defines segments and your linker. For modern x86 processors, there are 6 segment descriptors (usually shortened to 'segment'), labelled CS for code, SS for stack, and DS, ES, FS and GS for data. Your program's heap lives in of the data segments. Compiled object files also have 'segments', but they are simply used to define parts that are code (a.k.a. the 'text segment'), static initialized data ('data') and unitialized data (BSS segment). There is no heap in your object files or executable.

    – JvO
    Nov 27 '13 at 16:44











  • isn't this stuff massively deprecated since the time of 286, 386 and COM? my memory of this is that its a mechanism to extend the address range beyond 16-bits and provide some protection as you describe - but that it has been completely abandoned for the x64 architecture... let me see if i can find some intel document. :)

    – jheriko
    Dec 6 '13 at 11:22












  • tbh, the documentation is quite deep. i should definitely read that ia32/64 manual more so that I know precisely what i am talking about with reference. there are many links that suggest what i say from googling 'x64 segments', but they aren't intel manuals... :)

    – jheriko
    Dec 6 '13 at 11:50


















3














Yes. How else could Dynamic loading and Linking work? Remembering that some (most?) Operating Systems, and some (most?) Linkers are also written in C/C++. For example,



#include <dlfcn.h>
void* initializer = dlsym(sdl_library,"SDL_Init");
if (initializer == NULL)
// report error ...
else
// cast initializer to its proper type and use



Also, I believe that a JIT (e.g. GNU lightning and others) in general performs those operations.






share|improve this answer

























  • Note that operating systems may impose restrictions on what you can do. For example, you may need to register your code with the OS so it knows what to do if an interrupt or exception or signal occurs while the code is running.

    – Raymond Chen
    Nov 27 '13 at 3:36











  • @RaymondChen Perhaps.

    – Elliott Frisch
    Nov 27 '13 at 3:38











  • Not sure what you're getting at by saying "Perhaps." Are you saying that you doubt such restrictions exist?

    – Raymond Chen
    Nov 27 '13 at 3:49











  • @RaymondChen I'm saying it depends on the OS, and if you're writing an OS, or a dynamic linker, or a dynamic loader, or a dynamic translator (e.g. JIT) then you'll be doing this regardless of the "host" OS. Perhaps there are other circumstances as well.

    – Elliott Frisch
    Nov 27 '13 at 3:52











  • clearly they do exist, and are highly specific to the situation. ranging from completely impossible in a Harvard Arch to very easy in a system that has a built in dynamic loader.

    – Grady Player
    Nov 27 '13 at 3:53


















2














In windows, for example, this is now very hard to do when it was once very easy. I used to be able to take an array of bytes in C and then cast it to a function pointer type to execute it... but not any more.



Now, you can do this if you can call Global or VirtualAlloc functions and specifically ask for executable memory. On most platforms its either completely open or massively locked down. Doing this sort of thing on iOS, for example, is a massive headache and it will cause a submission fail on the app store if discovered.



here is some fantastically out of date and crusty code where i did the original thing you described:



https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Code/Platform_FSCompiledCode.cpp



using bytes from https://code.google.com/p/fsassembler



you may notice in there that i need to provide platform (windows) specific allocation functions to get some executable memory:



https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Core/Platform_FSExecutableAlloc.cpp






share|improve this answer






























    0














    Yes, but you must ensure that the memory is marked executable. How you do that depends on the architecture.






    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20233289%2fexecute-instructions-from-the-heap%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      So if I read you right you want to dynamically create CPU assembly instructions on the heap and execute them. A bit like self-modifying code. In theory that's possible, but in practice maybe not.



      The problem is that the heap is in a data segment, and CPU's/operating systems nowadays have measures to prevent exactly this kind of behavior (it's called the NX bit, or No-eXecute bit for x86 CPUs). If a segement is marked as NX, you can't execute code from it. This was invented to stop computer virusses from using buffer overflows to place exectuable code in data/heap/stack memory and then try the calling program to execute such code.



      Note that DLL's and libraries are loaded in the code segment, which of course allows code execution.






      share|improve this answer


















      • 1





        You understand what I am getting at.

        – David
        Nov 27 '13 at 4:01











      • This answer is a little confused. The heap lives in the data segment? The segments in a PE file are simply not used this way. The heap does not live in a data segment... more generally the 'code segment' will be loaded into executable memory and most OSs provide a mechanism to allocate such memory - although it might be hidden and buried it must exist.

        – jheriko
        Nov 27 '13 at 12:35







      • 2





        You have to make a distinction between how the CPU defines segments and your linker. For modern x86 processors, there are 6 segment descriptors (usually shortened to 'segment'), labelled CS for code, SS for stack, and DS, ES, FS and GS for data. Your program's heap lives in of the data segments. Compiled object files also have 'segments', but they are simply used to define parts that are code (a.k.a. the 'text segment'), static initialized data ('data') and unitialized data (BSS segment). There is no heap in your object files or executable.

        – JvO
        Nov 27 '13 at 16:44











      • isn't this stuff massively deprecated since the time of 286, 386 and COM? my memory of this is that its a mechanism to extend the address range beyond 16-bits and provide some protection as you describe - but that it has been completely abandoned for the x64 architecture... let me see if i can find some intel document. :)

        – jheriko
        Dec 6 '13 at 11:22












      • tbh, the documentation is quite deep. i should definitely read that ia32/64 manual more so that I know precisely what i am talking about with reference. there are many links that suggest what i say from googling 'x64 segments', but they aren't intel manuals... :)

        – jheriko
        Dec 6 '13 at 11:50















      4














      So if I read you right you want to dynamically create CPU assembly instructions on the heap and execute them. A bit like self-modifying code. In theory that's possible, but in practice maybe not.



      The problem is that the heap is in a data segment, and CPU's/operating systems nowadays have measures to prevent exactly this kind of behavior (it's called the NX bit, or No-eXecute bit for x86 CPUs). If a segement is marked as NX, you can't execute code from it. This was invented to stop computer virusses from using buffer overflows to place exectuable code in data/heap/stack memory and then try the calling program to execute such code.



      Note that DLL's and libraries are loaded in the code segment, which of course allows code execution.






      share|improve this answer


















      • 1





        You understand what I am getting at.

        – David
        Nov 27 '13 at 4:01











      • This answer is a little confused. The heap lives in the data segment? The segments in a PE file are simply not used this way. The heap does not live in a data segment... more generally the 'code segment' will be loaded into executable memory and most OSs provide a mechanism to allocate such memory - although it might be hidden and buried it must exist.

        – jheriko
        Nov 27 '13 at 12:35







      • 2





        You have to make a distinction between how the CPU defines segments and your linker. For modern x86 processors, there are 6 segment descriptors (usually shortened to 'segment'), labelled CS for code, SS for stack, and DS, ES, FS and GS for data. Your program's heap lives in of the data segments. Compiled object files also have 'segments', but they are simply used to define parts that are code (a.k.a. the 'text segment'), static initialized data ('data') and unitialized data (BSS segment). There is no heap in your object files or executable.

        – JvO
        Nov 27 '13 at 16:44











      • isn't this stuff massively deprecated since the time of 286, 386 and COM? my memory of this is that its a mechanism to extend the address range beyond 16-bits and provide some protection as you describe - but that it has been completely abandoned for the x64 architecture... let me see if i can find some intel document. :)

        – jheriko
        Dec 6 '13 at 11:22












      • tbh, the documentation is quite deep. i should definitely read that ia32/64 manual more so that I know precisely what i am talking about with reference. there are many links that suggest what i say from googling 'x64 segments', but they aren't intel manuals... :)

        – jheriko
        Dec 6 '13 at 11:50













      4












      4








      4







      So if I read you right you want to dynamically create CPU assembly instructions on the heap and execute them. A bit like self-modifying code. In theory that's possible, but in practice maybe not.



      The problem is that the heap is in a data segment, and CPU's/operating systems nowadays have measures to prevent exactly this kind of behavior (it's called the NX bit, or No-eXecute bit for x86 CPUs). If a segement is marked as NX, you can't execute code from it. This was invented to stop computer virusses from using buffer overflows to place exectuable code in data/heap/stack memory and then try the calling program to execute such code.



      Note that DLL's and libraries are loaded in the code segment, which of course allows code execution.






      share|improve this answer













      So if I read you right you want to dynamically create CPU assembly instructions on the heap and execute them. A bit like self-modifying code. In theory that's possible, but in practice maybe not.



      The problem is that the heap is in a data segment, and CPU's/operating systems nowadays have measures to prevent exactly this kind of behavior (it's called the NX bit, or No-eXecute bit for x86 CPUs). If a segement is marked as NX, you can't execute code from it. This was invented to stop computer virusses from using buffer overflows to place exectuable code in data/heap/stack memory and then try the calling program to execute such code.



      Note that DLL's and libraries are loaded in the code segment, which of course allows code execution.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 27 '13 at 3:37









      JvOJvO

      2,41621328




      2,41621328







      • 1





        You understand what I am getting at.

        – David
        Nov 27 '13 at 4:01











      • This answer is a little confused. The heap lives in the data segment? The segments in a PE file are simply not used this way. The heap does not live in a data segment... more generally the 'code segment' will be loaded into executable memory and most OSs provide a mechanism to allocate such memory - although it might be hidden and buried it must exist.

        – jheriko
        Nov 27 '13 at 12:35







      • 2





        You have to make a distinction between how the CPU defines segments and your linker. For modern x86 processors, there are 6 segment descriptors (usually shortened to 'segment'), labelled CS for code, SS for stack, and DS, ES, FS and GS for data. Your program's heap lives in of the data segments. Compiled object files also have 'segments', but they are simply used to define parts that are code (a.k.a. the 'text segment'), static initialized data ('data') and unitialized data (BSS segment). There is no heap in your object files or executable.

        – JvO
        Nov 27 '13 at 16:44











      • isn't this stuff massively deprecated since the time of 286, 386 and COM? my memory of this is that its a mechanism to extend the address range beyond 16-bits and provide some protection as you describe - but that it has been completely abandoned for the x64 architecture... let me see if i can find some intel document. :)

        – jheriko
        Dec 6 '13 at 11:22












      • tbh, the documentation is quite deep. i should definitely read that ia32/64 manual more so that I know precisely what i am talking about with reference. there are many links that suggest what i say from googling 'x64 segments', but they aren't intel manuals... :)

        – jheriko
        Dec 6 '13 at 11:50












      • 1





        You understand what I am getting at.

        – David
        Nov 27 '13 at 4:01











      • This answer is a little confused. The heap lives in the data segment? The segments in a PE file are simply not used this way. The heap does not live in a data segment... more generally the 'code segment' will be loaded into executable memory and most OSs provide a mechanism to allocate such memory - although it might be hidden and buried it must exist.

        – jheriko
        Nov 27 '13 at 12:35







      • 2





        You have to make a distinction between how the CPU defines segments and your linker. For modern x86 processors, there are 6 segment descriptors (usually shortened to 'segment'), labelled CS for code, SS for stack, and DS, ES, FS and GS for data. Your program's heap lives in of the data segments. Compiled object files also have 'segments', but they are simply used to define parts that are code (a.k.a. the 'text segment'), static initialized data ('data') and unitialized data (BSS segment). There is no heap in your object files or executable.

        – JvO
        Nov 27 '13 at 16:44











      • isn't this stuff massively deprecated since the time of 286, 386 and COM? my memory of this is that its a mechanism to extend the address range beyond 16-bits and provide some protection as you describe - but that it has been completely abandoned for the x64 architecture... let me see if i can find some intel document. :)

        – jheriko
        Dec 6 '13 at 11:22












      • tbh, the documentation is quite deep. i should definitely read that ia32/64 manual more so that I know precisely what i am talking about with reference. there are many links that suggest what i say from googling 'x64 segments', but they aren't intel manuals... :)

        – jheriko
        Dec 6 '13 at 11:50







      1




      1





      You understand what I am getting at.

      – David
      Nov 27 '13 at 4:01





      You understand what I am getting at.

      – David
      Nov 27 '13 at 4:01













      This answer is a little confused. The heap lives in the data segment? The segments in a PE file are simply not used this way. The heap does not live in a data segment... more generally the 'code segment' will be loaded into executable memory and most OSs provide a mechanism to allocate such memory - although it might be hidden and buried it must exist.

      – jheriko
      Nov 27 '13 at 12:35






      This answer is a little confused. The heap lives in the data segment? The segments in a PE file are simply not used this way. The heap does not live in a data segment... more generally the 'code segment' will be loaded into executable memory and most OSs provide a mechanism to allocate such memory - although it might be hidden and buried it must exist.

      – jheriko
      Nov 27 '13 at 12:35





      2




      2





      You have to make a distinction between how the CPU defines segments and your linker. For modern x86 processors, there are 6 segment descriptors (usually shortened to 'segment'), labelled CS for code, SS for stack, and DS, ES, FS and GS for data. Your program's heap lives in of the data segments. Compiled object files also have 'segments', but they are simply used to define parts that are code (a.k.a. the 'text segment'), static initialized data ('data') and unitialized data (BSS segment). There is no heap in your object files or executable.

      – JvO
      Nov 27 '13 at 16:44





      You have to make a distinction between how the CPU defines segments and your linker. For modern x86 processors, there are 6 segment descriptors (usually shortened to 'segment'), labelled CS for code, SS for stack, and DS, ES, FS and GS for data. Your program's heap lives in of the data segments. Compiled object files also have 'segments', but they are simply used to define parts that are code (a.k.a. the 'text segment'), static initialized data ('data') and unitialized data (BSS segment). There is no heap in your object files or executable.

      – JvO
      Nov 27 '13 at 16:44













      isn't this stuff massively deprecated since the time of 286, 386 and COM? my memory of this is that its a mechanism to extend the address range beyond 16-bits and provide some protection as you describe - but that it has been completely abandoned for the x64 architecture... let me see if i can find some intel document. :)

      – jheriko
      Dec 6 '13 at 11:22






      isn't this stuff massively deprecated since the time of 286, 386 and COM? my memory of this is that its a mechanism to extend the address range beyond 16-bits and provide some protection as you describe - but that it has been completely abandoned for the x64 architecture... let me see if i can find some intel document. :)

      – jheriko
      Dec 6 '13 at 11:22














      tbh, the documentation is quite deep. i should definitely read that ia32/64 manual more so that I know precisely what i am talking about with reference. there are many links that suggest what i say from googling 'x64 segments', but they aren't intel manuals... :)

      – jheriko
      Dec 6 '13 at 11:50





      tbh, the documentation is quite deep. i should definitely read that ia32/64 manual more so that I know precisely what i am talking about with reference. there are many links that suggest what i say from googling 'x64 segments', but they aren't intel manuals... :)

      – jheriko
      Dec 6 '13 at 11:50













      3














      Yes. How else could Dynamic loading and Linking work? Remembering that some (most?) Operating Systems, and some (most?) Linkers are also written in C/C++. For example,



      #include <dlfcn.h>
      void* initializer = dlsym(sdl_library,"SDL_Init");
      if (initializer == NULL)
      // report error ...
      else
      // cast initializer to its proper type and use



      Also, I believe that a JIT (e.g. GNU lightning and others) in general performs those operations.






      share|improve this answer

























      • Note that operating systems may impose restrictions on what you can do. For example, you may need to register your code with the OS so it knows what to do if an interrupt or exception or signal occurs while the code is running.

        – Raymond Chen
        Nov 27 '13 at 3:36











      • @RaymondChen Perhaps.

        – Elliott Frisch
        Nov 27 '13 at 3:38











      • Not sure what you're getting at by saying "Perhaps." Are you saying that you doubt such restrictions exist?

        – Raymond Chen
        Nov 27 '13 at 3:49











      • @RaymondChen I'm saying it depends on the OS, and if you're writing an OS, or a dynamic linker, or a dynamic loader, or a dynamic translator (e.g. JIT) then you'll be doing this regardless of the "host" OS. Perhaps there are other circumstances as well.

        – Elliott Frisch
        Nov 27 '13 at 3:52











      • clearly they do exist, and are highly specific to the situation. ranging from completely impossible in a Harvard Arch to very easy in a system that has a built in dynamic loader.

        – Grady Player
        Nov 27 '13 at 3:53















      3














      Yes. How else could Dynamic loading and Linking work? Remembering that some (most?) Operating Systems, and some (most?) Linkers are also written in C/C++. For example,



      #include <dlfcn.h>
      void* initializer = dlsym(sdl_library,"SDL_Init");
      if (initializer == NULL)
      // report error ...
      else
      // cast initializer to its proper type and use



      Also, I believe that a JIT (e.g. GNU lightning and others) in general performs those operations.






      share|improve this answer

























      • Note that operating systems may impose restrictions on what you can do. For example, you may need to register your code with the OS so it knows what to do if an interrupt or exception or signal occurs while the code is running.

        – Raymond Chen
        Nov 27 '13 at 3:36











      • @RaymondChen Perhaps.

        – Elliott Frisch
        Nov 27 '13 at 3:38











      • Not sure what you're getting at by saying "Perhaps." Are you saying that you doubt such restrictions exist?

        – Raymond Chen
        Nov 27 '13 at 3:49











      • @RaymondChen I'm saying it depends on the OS, and if you're writing an OS, or a dynamic linker, or a dynamic loader, or a dynamic translator (e.g. JIT) then you'll be doing this regardless of the "host" OS. Perhaps there are other circumstances as well.

        – Elliott Frisch
        Nov 27 '13 at 3:52











      • clearly they do exist, and are highly specific to the situation. ranging from completely impossible in a Harvard Arch to very easy in a system that has a built in dynamic loader.

        – Grady Player
        Nov 27 '13 at 3:53













      3












      3








      3







      Yes. How else could Dynamic loading and Linking work? Remembering that some (most?) Operating Systems, and some (most?) Linkers are also written in C/C++. For example,



      #include <dlfcn.h>
      void* initializer = dlsym(sdl_library,"SDL_Init");
      if (initializer == NULL)
      // report error ...
      else
      // cast initializer to its proper type and use



      Also, I believe that a JIT (e.g. GNU lightning and others) in general performs those operations.






      share|improve this answer















      Yes. How else could Dynamic loading and Linking work? Remembering that some (most?) Operating Systems, and some (most?) Linkers are also written in C/C++. For example,



      #include <dlfcn.h>
      void* initializer = dlsym(sdl_library,"SDL_Init");
      if (initializer == NULL)
      // report error ...
      else
      // cast initializer to its proper type and use



      Also, I believe that a JIT (e.g. GNU lightning and others) in general performs those operations.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 27 '13 at 3:40

























      answered Nov 27 '13 at 3:33









      Elliott FrischElliott Frisch

      155k1394188




      155k1394188












      • Note that operating systems may impose restrictions on what you can do. For example, you may need to register your code with the OS so it knows what to do if an interrupt or exception or signal occurs while the code is running.

        – Raymond Chen
        Nov 27 '13 at 3:36











      • @RaymondChen Perhaps.

        – Elliott Frisch
        Nov 27 '13 at 3:38











      • Not sure what you're getting at by saying "Perhaps." Are you saying that you doubt such restrictions exist?

        – Raymond Chen
        Nov 27 '13 at 3:49











      • @RaymondChen I'm saying it depends on the OS, and if you're writing an OS, or a dynamic linker, or a dynamic loader, or a dynamic translator (e.g. JIT) then you'll be doing this regardless of the "host" OS. Perhaps there are other circumstances as well.

        – Elliott Frisch
        Nov 27 '13 at 3:52











      • clearly they do exist, and are highly specific to the situation. ranging from completely impossible in a Harvard Arch to very easy in a system that has a built in dynamic loader.

        – Grady Player
        Nov 27 '13 at 3:53

















      • Note that operating systems may impose restrictions on what you can do. For example, you may need to register your code with the OS so it knows what to do if an interrupt or exception or signal occurs while the code is running.

        – Raymond Chen
        Nov 27 '13 at 3:36











      • @RaymondChen Perhaps.

        – Elliott Frisch
        Nov 27 '13 at 3:38











      • Not sure what you're getting at by saying "Perhaps." Are you saying that you doubt such restrictions exist?

        – Raymond Chen
        Nov 27 '13 at 3:49











      • @RaymondChen I'm saying it depends on the OS, and if you're writing an OS, or a dynamic linker, or a dynamic loader, or a dynamic translator (e.g. JIT) then you'll be doing this regardless of the "host" OS. Perhaps there are other circumstances as well.

        – Elliott Frisch
        Nov 27 '13 at 3:52











      • clearly they do exist, and are highly specific to the situation. ranging from completely impossible in a Harvard Arch to very easy in a system that has a built in dynamic loader.

        – Grady Player
        Nov 27 '13 at 3:53
















      Note that operating systems may impose restrictions on what you can do. For example, you may need to register your code with the OS so it knows what to do if an interrupt or exception or signal occurs while the code is running.

      – Raymond Chen
      Nov 27 '13 at 3:36





      Note that operating systems may impose restrictions on what you can do. For example, you may need to register your code with the OS so it knows what to do if an interrupt or exception or signal occurs while the code is running.

      – Raymond Chen
      Nov 27 '13 at 3:36













      @RaymondChen Perhaps.

      – Elliott Frisch
      Nov 27 '13 at 3:38





      @RaymondChen Perhaps.

      – Elliott Frisch
      Nov 27 '13 at 3:38













      Not sure what you're getting at by saying "Perhaps." Are you saying that you doubt such restrictions exist?

      – Raymond Chen
      Nov 27 '13 at 3:49





      Not sure what you're getting at by saying "Perhaps." Are you saying that you doubt such restrictions exist?

      – Raymond Chen
      Nov 27 '13 at 3:49













      @RaymondChen I'm saying it depends on the OS, and if you're writing an OS, or a dynamic linker, or a dynamic loader, or a dynamic translator (e.g. JIT) then you'll be doing this regardless of the "host" OS. Perhaps there are other circumstances as well.

      – Elliott Frisch
      Nov 27 '13 at 3:52





      @RaymondChen I'm saying it depends on the OS, and if you're writing an OS, or a dynamic linker, or a dynamic loader, or a dynamic translator (e.g. JIT) then you'll be doing this regardless of the "host" OS. Perhaps there are other circumstances as well.

      – Elliott Frisch
      Nov 27 '13 at 3:52













      clearly they do exist, and are highly specific to the situation. ranging from completely impossible in a Harvard Arch to very easy in a system that has a built in dynamic loader.

      – Grady Player
      Nov 27 '13 at 3:53





      clearly they do exist, and are highly specific to the situation. ranging from completely impossible in a Harvard Arch to very easy in a system that has a built in dynamic loader.

      – Grady Player
      Nov 27 '13 at 3:53











      2














      In windows, for example, this is now very hard to do when it was once very easy. I used to be able to take an array of bytes in C and then cast it to a function pointer type to execute it... but not any more.



      Now, you can do this if you can call Global or VirtualAlloc functions and specifically ask for executable memory. On most platforms its either completely open or massively locked down. Doing this sort of thing on iOS, for example, is a massive headache and it will cause a submission fail on the app store if discovered.



      here is some fantastically out of date and crusty code where i did the original thing you described:



      https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Code/Platform_FSCompiledCode.cpp



      using bytes from https://code.google.com/p/fsassembler



      you may notice in there that i need to provide platform (windows) specific allocation functions to get some executable memory:



      https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Core/Platform_FSExecutableAlloc.cpp






      share|improve this answer



























        2














        In windows, for example, this is now very hard to do when it was once very easy. I used to be able to take an array of bytes in C and then cast it to a function pointer type to execute it... but not any more.



        Now, you can do this if you can call Global or VirtualAlloc functions and specifically ask for executable memory. On most platforms its either completely open or massively locked down. Doing this sort of thing on iOS, for example, is a massive headache and it will cause a submission fail on the app store if discovered.



        here is some fantastically out of date and crusty code where i did the original thing you described:



        https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Code/Platform_FSCompiledCode.cpp



        using bytes from https://code.google.com/p/fsassembler



        you may notice in there that i need to provide platform (windows) specific allocation functions to get some executable memory:



        https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Core/Platform_FSExecutableAlloc.cpp






        share|improve this answer

























          2












          2








          2







          In windows, for example, this is now very hard to do when it was once very easy. I used to be able to take an array of bytes in C and then cast it to a function pointer type to execute it... but not any more.



          Now, you can do this if you can call Global or VirtualAlloc functions and specifically ask for executable memory. On most platforms its either completely open or massively locked down. Doing this sort of thing on iOS, for example, is a massive headache and it will cause a submission fail on the app store if discovered.



          here is some fantastically out of date and crusty code where i did the original thing you described:



          https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Code/Platform_FSCompiledCode.cpp



          using bytes from https://code.google.com/p/fsassembler



          you may notice in there that i need to provide platform (windows) specific allocation functions to get some executable memory:



          https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Core/Platform_FSExecutableAlloc.cpp






          share|improve this answer













          In windows, for example, this is now very hard to do when it was once very easy. I used to be able to take an array of bytes in C and then cast it to a function pointer type to execute it... but not any more.



          Now, you can do this if you can call Global or VirtualAlloc functions and specifically ask for executable memory. On most platforms its either completely open or massively locked down. Doing this sort of thing on iOS, for example, is a massive headache and it will cause a submission fail on the app store if discovered.



          here is some fantastically out of date and crusty code where i did the original thing you described:



          https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Code/Platform_FSCompiledCode.cpp



          using bytes from https://code.google.com/p/fsassembler



          you may notice in there that i need to provide platform (windows) specific allocation functions to get some executable memory:



          https://code.google.com/p/fridgescript/source/browse/trunk/src/w32/Core/Platform_FSExecutableAlloc.cpp







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 27 '13 at 4:06









          jherikojheriko

          2,71011627




          2,71011627





















              0














              Yes, but you must ensure that the memory is marked executable. How you do that depends on the architecture.






              share|improve this answer



























                0














                Yes, but you must ensure that the memory is marked executable. How you do that depends on the architecture.






                share|improve this answer

























                  0












                  0








                  0







                  Yes, but you must ensure that the memory is marked executable. How you do that depends on the architecture.






                  share|improve this answer













                  Yes, but you must ensure that the memory is marked executable. How you do that depends on the architecture.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 27 '13 at 3:36









                  Owen WengerdOwen Wengerd

                  1,5881911




                  1,5881911



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f20233289%2fexecute-instructions-from-the-heap%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme