The processor does only what you tell it. As you noted, the processor cannot determine the difference between โdataโ and โcodeโ in memory: all this is just a sequence of bytes. This is what you say what needs to be done with these bytes, which determine how it is processed.
When the program is compiled, the generated executable file contains information that says which parts are code and which are data. When the program is executed, the operating system loads the code and data into different parts of the memory, and then tells the processor to start executing the code at the program entry point. From there, the processor extracts the first command, executes it, and proceeds to the next command.
This is all very simplified, of course, but I think you understand the idea.
On older processors and older operating systems, nothing prevents you from telling the processor to start executing instructions in the middle of the data segment. Or, in essence, from changing โdataโ in the middle of a code segment, thereby making self-modifying code. Newer processors and operating systems typically have some form of data prevention and locking to prevent code changes. Otherwise, self-modifying code can be a huge security risk.
Short answer: the processor treats the code as code because you are telling it. Otherwise, all are just bytes in memory.
Jim mischel
source share